data
stringlengths
512
2.99k
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.
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
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.
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:
= (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.
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.
[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.
[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.
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.
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.
[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
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.
[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.
[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.
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.
[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.
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.
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:[email protected]/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_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.
[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 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] 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 --
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 --
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 --
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
* ---------------------------------------> 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).
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.
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:
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.
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 :
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 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.
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.
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.
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.
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.
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.
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.
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.
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:
[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.
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.
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 /*
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
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); } }
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.
[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] 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] 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.
[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.
[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] 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] 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 --
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().
[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] 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.
[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
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.
[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] 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)
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 --
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.
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
[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
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 --
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