0% found this document useful (0 votes)
1K views3,154 pages

Esp Idf en v5.2 Dev 3065 g272b4091f1 Esp32

Uploaded by

Luis Araujo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views3,154 pages

Esp Idf en v5.2 Dev 3065 g272b4091f1 Esp32

Uploaded by

Luis Araujo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3154

ESP32

ESP-IDF Programming Guide

Release v5.2-dev-3065-g272b4091f1
Espressif Systems
Sep 25, 2023
Table of contents

Table of contents i

1 Get Started 3
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 What You Need . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
1.3 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
1.3.1 IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
1.3.2 Manual Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
1.4 Build Your First Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
1.5 Uninstall ESP-IDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

2 API Reference 125


2.1 API Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
2.1.1 Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
2.1.2 Configuration Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
2.1.3 Private APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
2.1.4 Components in Example Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
2.1.5 API Stability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
2.2 Application Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
2.2.1 ASIO Port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
2.2.2 ESP-Modbus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
2.2.3 ESP-MQTT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
2.2.4 ESP-TLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
2.2.5 ESP HTTP Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
2.2.6 ESP Local Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
2.2.7 ESP Serial Slave Link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
2.2.8 ESP x509 Certificate Bundle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
2.2.9 HTTP Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
2.2.10 HTTPS Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
2.2.11 ICMP Echo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
2.2.12 mDNS Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
2.2.13 Mbed TLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
2.2.14 IP Network Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
2.3 Bluetooth® API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
2.3.1 Bluetooth® Common . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
2.3.2 Bluetooth® Low Energy (Bluetooth LE) . . . . . . . . . . . . . . . . . . . . . . . . . . 258
2.3.3 Classic Bluetooth® . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
2.3.4 Controller && VHCI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
2.3.5 ESP-BLE-MESH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
2.3.6 NimBLE-based Host APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913
2.4 Error Codes Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 915
2.5 Networking APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 922
2.5.1 Wi-Fi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 922
2.5.2 Ethernet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1056
2.5.3 Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1090

i
2.5.4 ESP-NETIF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1098
2.5.5 IP Network Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1134
2.5.6 Application Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1136
2.6 Peripherals API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1136
2.6.1 Analog to Digital Converter (ADC) Oneshot Mode Driver . . . . . . . . . . . . . . . . . 1136
2.6.2 Analog to Digital Converter (ADC) Continuous Mode Driver . . . . . . . . . . . . . . . 1147
2.6.3 Analog to Digital Converter (ADC) Calibration Driver . . . . . . . . . . . . . . . . . . . 1155
2.6.4 Clock Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1159
2.6.5 Digital To Analog Converter (DAC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1170
2.6.6 GPIO & RTC GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1183
2.6.7 General Purpose Timer (GPTimer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1200
2.6.8 Inter-Integrated Circuit (I2C) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1215
2.6.9 Inter-IC Sound (I2S) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1233
2.6.10 LCD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1269
2.6.11 LED Control (LEDC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1287
2.6.12 Motor Control Pulse Width Modulator (MCPWM) . . . . . . . . . . . . . . . . . . . . . 1306
2.6.13 Pulse Counter (PCNT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1359
2.6.14 Remote Control Transceiver (RMT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1374
2.6.15 SD Pull-up Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1399
2.6.16 SDMMC Host Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1403
2.6.17 SD SPI Host Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1409
2.6.18 SDIO Card Slave Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1415
2.6.19 Sigma-Delta Modulation (SDM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1425
2.6.20 SPI Flash API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1431
2.6.21 SPI Master Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1461
2.6.22 SPI Slave Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1487
2.6.23 ESP32-WROOM-32SE (Secure Element) . . . . . . . . . . . . . . . . . . . . . . . . . 1494
2.6.24 Touch Sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1495
2.6.25 Two-Wire Automotive Interface (TWAI) . . . . . . . . . . . . . . . . . . . . . . . . . . 1512
2.6.26 Universal Asynchronous Receiver/Transmitter (UART) . . . . . . . . . . . . . . . . . . 1530
2.7 Project Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1555
2.7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1555
2.7.2 Project Configuration Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1556
2.7.3 Using sdkconfig.defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1556
2.7.4 Kconfig Format Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1556
2.7.5 Backward Compatibility of Kconfig Options . . . . . . . . . . . . . . . . . . . . . . . . 1556
2.7.6 Configuration Options Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1557
2.8 Provisioning API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1879
2.8.1 Protocol Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1879
2.8.2 Unified Provisioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1894
2.8.3 Wi-Fi Provisioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1901
2.9 Storage API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1919
2.9.1 FAT Filesystem Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1919
2.9.2 Manufacturing Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1928
2.9.3 Non-Volatile Storage Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1933
2.9.4 NVS Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1956
2.9.5 NVS Partition Generator Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1961
2.9.6 NVS Partition Parser Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1967
2.9.7 SD/SDIO/MMC Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1968
2.9.8 Partitions API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1982
2.9.9 SPIFFS Filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1991
2.9.10 Virtual Filesystem Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1995
2.9.11 Wear Levelling API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2011
2.10 System API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2014
2.10.1 App Image Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2014
2.10.2 Bootloader Image Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2020
2.10.3 Application Level Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2022
2.10.4 Call Function with External Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2027

ii
2.10.5 Chip Revision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2028
2.10.6 Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2031
2.10.7 eFuse Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2040
2.10.8 Error Code and Helper Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2063
2.10.9 ESP HTTPS OTA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2066
2.10.10 Event Loop Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2072
2.10.11 FreeRTOS Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2085
2.10.12 FreeRTOS (ESP-IDF) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2087
2.10.13 FreeRTOS (Supplemental Features) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2205
2.10.14 Heap Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2233
2.10.15 Memory Management for MMU Supported Memory . . . . . . . . . . . . . . . . . . . . 2247
2.10.16 Heap Memory Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2254
2.10.17 High Resolution Timer (ESP Timer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2267
2.10.18 Internal and Unstable APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2274
2.10.19 Inter-Processor Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2275
2.10.20 Interrupt Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2281
2.10.21 Logging library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2289
2.10.22 Miscellaneous System APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2297
2.10.23 Over The Air Updates (OTA) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2313
2.10.24 Performance Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2326
2.10.25 Power Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2328
2.10.26 POSIX Threads Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2334
2.10.27 Random Number Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2339
2.10.28 Sleep Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2341
2.10.29 SoC Capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2355
2.10.30 System Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2366
2.10.31 The Himem Allocation API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2372
2.10.32 ULP Coprocessor Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2374
2.10.33 Watchdogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2409

3 Hardware Reference 2417

4 API Guides 2419


4.1 Application Level Tracing Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2419
4.1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2419
4.1.2 Modes of Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2419
4.1.3 Configuration Options and Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . 2420
4.1.4 How to Use This Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2421
4.2 Application Startup Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2430
4.2.1 First Stage Bootloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2430
4.2.2 Second Stage Bootloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2430
4.2.3 Application Startup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2431
4.3 BluFi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2433
4.3.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2433
4.3.2 The BluFi Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2433
4.3.3 The Flow Chart of BluFi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2433
4.3.4 The Frame Formats Defined in BluFi . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2435
4.3.5 The Security Implementation of ESP32 . . . . . . . . . . . . . . . . . . . . . . . . . . . 2439
4.3.6 GATT Related Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2440
4.4 Bluetooth® Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2440
4.4.1 ESP Bluetooth Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2441
4.4.2 Hosts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2441
4.4.3 Profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2442
4.4.4 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2443
4.5 Bootloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2443
4.5.1 Bootloader Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2443
4.5.2 Log Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2444
4.5.3 Factory Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2444

iii
4.5.4 Boot from Test Firmware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2445
4.5.5 Rollback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2445
4.5.6 Watchdog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2445
4.5.7 Bootloader Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2446
4.5.8 Fast Boot from Deep-Sleep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2446
4.5.9 Custom Bootloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2446
4.6 Build System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2446
4.6.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2447
4.6.2 Using the Build System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2447
4.6.3 Example Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2449
4.6.4 Project CMakeLists File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2450
4.6.5 Component CMakeLists Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2451
4.6.6 Component Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2454
4.6.7 Preprocessor Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2454
4.6.8 Component Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2454
4.6.9 Overriding Parts of the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2458
4.6.10 Configuration-Only Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2460
4.6.11 Debugging CMake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2460
4.6.12 Example Component CMakeLists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2461
4.6.13 Custom Sdkconfig Defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2465
4.6.14 Flash Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2465
4.6.15 Building the Bootloader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2466
4.6.16 Writing Pure CMake Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2466
4.6.17 Using Third-Party CMake Projects with Components . . . . . . . . . . . . . . . . . . . 2466
4.6.18 Using Prebuilt Libraries with Components . . . . . . . . . . . . . . . . . . . . . . . . . 2467
4.6.19 Using ESP-IDF in Custom CMake Projects . . . . . . . . . . . . . . . . . . . . . . . . . 2468
4.6.20 ESP-IDF CMake Build System API . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2468
4.6.21 File Globbing & Incremental Builds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2472
4.6.22 Build System Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2473
4.6.23 Build System Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2474
4.6.24 Migrating from ESP-IDF GNU Make System . . . . . . . . . . . . . . . . . . . . . . . 2475
4.7 RF Coexistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2477
4.7.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2477
4.7.2 Supported Coexistence Scenario for ESP32 . . . . . . . . . . . . . . . . . . . . . . . . . 2477
4.7.3 Coexistence Mechanism and Policy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2477
4.7.4 How to Use the Coexistence Feature . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2479
4.8 Core Dump . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2480
4.8.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2480
4.8.2 Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2480
4.8.3 Core Dump to Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2481
4.8.4 Core Dump to UART . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2482
4.8.5 Core Dump Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2483
4.8.6 ROM Functions in Backtraces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2483
4.8.7 Dumping Variables on Demand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2483
4.8.8 Running idf.py coredump-info and idf.py coredump-debug . . . . . . . 2484
4.9 C++ Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2486
4.9.1 esp-idf-cxx Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2486
4.9.2 C++ Language Standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2487
4.9.3 Multithreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2487
4.9.4 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2487
4.9.5 Runtime Type Information (RTTI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2488
4.9.6 Developing in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2488
4.9.7 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2489
4.9.8 What to Avoid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2489
4.10 Current Consumption Measurement of Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . 2489
4.10.1 Notes to Measurement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2490
4.10.2 Hardware Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2490
4.10.3 Measurement Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2492

iv
4.11 Deep Sleep Wake Stubs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2492
4.11.1 Rules for Wake Stubs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2495
4.11.2 Implementing A Stub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2495
4.11.3 Loading Code Into RTC Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2495
4.11.4 Loading Data Into RTC Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2495
4.11.5 CRC Check For Wake Stubs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2496
4.11.6 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2496
4.12 Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2496
4.12.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2497
4.12.2 Error Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2497
4.12.3 Converting Error Codes to Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . 2497
4.12.4 ESP_ERROR_CHECK Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2497
4.12.5 ESP_ERROR_CHECK_WITHOUT_ABORT Macro . . . . . . . . . . . . . . . . . . . . 2498
4.12.6 ESP_RETURN_ON_ERROR Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2498
4.12.7 ESP_GOTO_ON_ERROR Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2498
4.12.8 ESP_RETURN_ON_FALSE Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2498
4.12.9 ESP_GOTO_ON_FALSE Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2498
4.12.10 CHECK MACROS Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2498
4.12.11 Error Handling Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2499
4.12.12 C++ Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2500
4.13 ESP-BLE-MESH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2500
4.13.1 Getting Started with ESP-BLE-MESH . . . . . . . . . . . . . . . . . . . . . . . . . . . 2500
4.13.2 ESP-BLE-MESH Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2508
4.13.3 ESP-BLE-MESH Demo Videos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2508
4.13.4 ESP-BLE-MESH FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2508
4.13.5 Related Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2508
4.14 ESP-WIFI-MESH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2538
4.14.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2538
4.14.2 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2539
4.14.3 ESP-WIFI-MESH Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2539
4.14.4 Building a Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2545
4.14.5 Managing a Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2550
4.14.6 Data Transmission . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2553
4.14.7 Channel Switching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2555
4.14.8 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2558
4.14.9 Further Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2559
4.15 Support for External RAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2559
4.15.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2559
4.15.2 Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2559
4.15.3 Configuring External RAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2559
4.15.4 Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2561
4.15.5 Failure to Initialize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2561
4.15.6 Chip Revisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2561
4.16 Fatal Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2562
4.16.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2562
4.16.2 Panic Handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2562
4.16.3 Register Dump and Backtrace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2563
4.16.4 GDB Stub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2565
4.16.5 RTC Watchdog Timeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2566
4.16.6 Guru Meditation Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2566
4.16.7 Other Fatal Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2568
4.17 Hardware Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2570
4.17.1 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2571
4.17.2 LL (Low Level) Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2572
4.17.3 HAL (Hardware Abstraction Layer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2573
4.18 High Priority Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2574
4.18.1 Interrupt Priorities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2574
4.18.2 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2575

v
4.19 JTAG Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2575
4.19.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2576
4.19.2 How it Works? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2576
4.19.3 Selecting JTAG Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2577
4.19.4 Setup of OpenOCD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2577
4.19.5 Configuring ESP32 Target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2578
4.19.6 Launching Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2583
4.19.7 Debugging Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2583
4.19.8 Building OpenOCD from Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2583
4.19.9 Tips and Quirks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2588
4.19.10 Related Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2593
4.20 Linker Script Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2619
4.20.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2619
4.20.2 Quick Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2620
4.20.3 Linker Script Generation Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2622
4.21 lwIP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2629
4.21.1 Supported APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2629
4.21.2 BSD Sockets API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2629
4.21.3 Netconn API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2633
4.21.4 lwIP FreeRTOS Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2633
4.21.5 IPv6 Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2634
4.21.6 ESP-lwIP Custom Modifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2635
4.21.7 Performance Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2636
4.22 Memory Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2637
4.22.1 DRAM (Data RAM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2637
4.22.2 IRAM (Instruction RAM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2638
4.22.3 IROM (Code Executed from flash) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2639
4.22.4 DROM (Data Stored in flash) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2639
4.22.5 RTC Slow Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2639
4.22.6 RTC FAST Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2640
4.22.7 DMA-Capable Requirement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2640
4.22.8 DMA Buffer in the Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2640
4.23 OpenThread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2641
4.23.1 Modes of the OpenThread Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2641
4.23.2 How to Write an OpenThread Application . . . . . . . . . . . . . . . . . . . . . . . . . 2641
4.23.3 The OpenThread Border Router . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2643
4.24 Partition Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2643
4.24.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2643
4.24.2 Built-in Partition Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2643
4.24.3 Creating Custom Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2644
4.24.4 Generating Binary Partition Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2646
4.24.5 Partition Size Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2647
4.24.6 Flashing the Partition Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2647
4.24.7 Partition Tool (parttool.py) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2647
4.25 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2649
4.25.1 How to Optimize Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2649
4.25.2 Guides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2649
4.26 Reproducible Builds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2669
4.26.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2669
4.26.2 Reasons for Non-Reproducible Builds . . . . . . . . . . . . . . . . . . . . . . . . . . . 2669
4.26.3 Enabling Reproducible Builds in ESP-IDF . . . . . . . . . . . . . . . . . . . . . . . . . 2669
4.26.4 How Reproducible Builds Are Achieved . . . . . . . . . . . . . . . . . . . . . . . . . . 2669
4.26.5 Reproducible Builds and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2670
4.26.6 Factors Which Still Affect Reproducible Builds . . . . . . . . . . . . . . . . . . . . . . . 2670
4.27 RF Calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2670
4.27.1 Partial Calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2670
4.27.2 Full Calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2671
4.27.3 No Calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2671

vi
4.27.4 PHY Initialization Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2671
4.27.5 API Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2671
4.28 Thread Local Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2678
4.28.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2678
4.28.2 FreeRTOS Native APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2678
4.28.3 Pthread APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2679
4.28.4 C11 Standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2679
4.29 Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2679
4.29.1 IDF Frontend - idf.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2679
4.29.2 IDF Docker Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2683
4.29.3 IDF Windows Installer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2685
4.29.4 IDF Component Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2686
4.29.5 IDF Clang-Tidy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2689
4.29.6 Downloadable IDF Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2689
4.30 Unit Testing in ESP32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2703
4.30.1 Normal Test Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2703
4.30.2 Multi-device Test Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2704
4.30.3 Multi-stage Test Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2705
4.30.4 Tests For Different Targets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2705
4.30.5 Building Unit Test App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2706
4.30.6 Running Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2706
4.30.7 Timing Code with Cache Compensated Timer . . . . . . . . . . . . . . . . . . . . . . . 2707
4.30.8 Mocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2708
4.31 Running ESP-IDF Applications on Host . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2710
4.31.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2711
4.31.2 Requirements for Using Mocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2711
4.31.3 Build and Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2712
4.31.4 Component Linux/Mock Support Overview . . . . . . . . . . . . . . . . . . . . . . . . 2712
4.32 Wi-Fi Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2712
4.32.1 ESP32 Wi-Fi Feature List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2713
4.32.2 How To Write a Wi-Fi Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2713
4.32.3 ESP32 Wi-Fi API Error Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2714
4.32.4 ESP32 Wi-Fi API Parameter Initialization . . . . . . . . . . . . . . . . . . . . . . . . . 2714
4.32.5 ESP32 Wi-Fi Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2714
4.32.6 ESP32 Wi-Fi Event Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2714
4.32.7 ESP32 Wi-Fi Station General Scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . 2718
4.32.8 ESP32 Wi-Fi AP General Scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2720
4.32.9 ESP32 Wi-Fi Scan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2722
4.32.10 ESP32 Wi-Fi Station Connecting Scenario . . . . . . . . . . . . . . . . . . . . . . . . . 2728
4.32.11 ESP32 Wi-Fi Station Connecting When Multiple APs Are Found . . . . . . . . . . . . . 2735
4.32.12 Wi-Fi Reconnect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2735
4.32.13 Wi-Fi Beacon Timeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2735
4.32.14 ESP32 Wi-Fi Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2735
4.32.15 Wi-Fi Easy Connect™ (DPP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2741
4.32.16 Wi-Fi AwareTM (NAN) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2742
4.32.17 Wireless Network Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2742
4.32.18 Radio Resource Measurement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2743
4.32.19 Fast BSS Transition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2743
4.32.20 ESP32 Wi-Fi Power-saving Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2743
4.32.21 ESP32 Wi-Fi Throughput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2745
4.32.22 Wi-Fi 80211 Packet Send . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2745
4.32.23 Wi-Fi Sniffer Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2747
4.32.24 Wi-Fi Multiple Antennas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2748
4.32.25 Wi-Fi Channel State Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2749
4.32.26 Wi-Fi Channel State Information Configure . . . . . . . . . . . . . . . . . . . . . . . . . 2751
4.32.27 Wi-Fi HT20/40 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2751
4.32.28 Wi-Fi QoS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2751
4.32.29 Wi-Fi AMSDU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2752

vii
4.32.30 Wi-Fi Fragment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2752
4.32.31 WPS Enrollee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2752
4.32.32 Wi-Fi Buffer Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2752
4.32.33 How to Improve Wi-Fi Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2753
4.32.34 Wi-Fi Menuconfig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2756
4.32.35 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2759
4.33 Wi-Fi Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2762
4.33.1 ESP32 Wi-Fi Security Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2762
4.33.2 Protected Management Frames (PMF) . . . . . . . . . . . . . . . . . . . . . . . . . . . 2765
4.33.3 Wi-Fi Enterprise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2766
4.33.4 WPA3-Personal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2766
4.33.5 Wi-Fi Enhanced Open™ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2767

5 Security Guides 2769


5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2769
5.1.1 Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2769
5.2 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2772
5.2.1 Flash Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2772
5.2.2 Secure Boot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2787
5.2.3 Secure Boot V2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2793
5.3 Workflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2800
5.3.1 Host Based Security Workflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2800

6 Migration Guides 2807


6.1 ESP-IDF 5.x Migration Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2807
6.1.1 Migration from 4.4 to 5.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2807
6.1.2 Migration from 5.0 to 5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2838
6.1.3 Migration from 5.1 to 5.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2841

7 Libraries and Frameworks 2843


7.1 Cloud Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2843
7.1.1 ESP RainMaker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2843
7.1.2 AWS IoT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2843
7.1.3 Azure IoT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2843
7.1.4 Google IoT Core . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2843
7.1.5 Aliyun IoT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2843
7.1.6 Joylink IoT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2843
7.1.7 Tencent IoT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2844
7.1.8 Tencentyun IoT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2844
7.1.9 Baidu IoT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2844
7.2 Espressif’s Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2844
7.2.1 Espressif Audio Development Framework . . . . . . . . . . . . . . . . . . . . . . . . . 2844
7.2.2 ESP-CSI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2844
7.2.3 Espressif DSP Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2844
7.2.4 ESP-WIFI-MESH Development Framework . . . . . . . . . . . . . . . . . . . . . . . . 2845
7.2.5 ESP-WHO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2845
7.2.6 ESP RainMaker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2845
7.2.7 ESP-IoT-Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2845
7.2.8 ESP-Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2845
7.2.9 ESP-BSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2846
7.2.10 ESP-IDF-CXX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2846

8 Contributions Guide 2847


8.1 How to Contribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2847
8.2 Before Contributing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2847
8.3 Pull Request Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2847
8.4 Legal Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2848
8.5 Related Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2848
8.5.1 Espressif IoT Development Framework Style Guide . . . . . . . . . . . . . . . . . . . . 2848

viii
8.5.2 Install Pre-commit Hook for ESP-IDF Project . . . . . . . . . . . . . . . . . . . . . . . 2856
8.5.3 Documenting Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2857
8.5.4 Creating Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2862
8.5.5 API Documentation Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2863
8.5.6 Contributor Agreement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2865
8.5.7 Copyright Header Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2867
8.5.8 pytest in ESP-IDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2869

9 ESP-IDF Versions 2881


9.1 Releases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2881
9.2 Which Version Should I Start With? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2881
9.3 Versioning Scheme . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2882
9.4 Support Periods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2882
9.5 Checking the Current Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2883
9.6 Git Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2884
9.7 Updating ESP-IDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2884
9.7.1 Updating to Stable Release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2885
9.7.2 Updating to a Pre-Release Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2885
9.7.3 Updating to Master Branch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2885
9.7.4 Updating to a Release Branch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2886

10 Resources 2887
10.1 PlatformIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2887
10.1.1 What Is PlatformIO? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2887
10.1.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2887
10.1.3 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2888
10.1.4 Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2888
10.1.5 Project Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2888
10.1.6 Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2888
10.2 CLion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2888
10.2.1 What Is CLion? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2888
10.2.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2888
10.2.3 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2888
10.2.4 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2888
10.3 VisualGDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2888
10.3.1 What Is VisualGDB? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2888
10.3.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2889
10.3.3 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2889
10.3.4 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2889
10.4 Useful Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2889

11 Copyrights and Licenses 2891


11.1 Software Copyrights . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2891
11.1.1 Firmware Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2891
11.1.2 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2892
11.2 ROM Source Code Copyrights . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2892
11.3 Xtensa libhal MIT License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2893
11.4 TinyBasic Plus MIT License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2893
11.5 TJpgDec License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2893

12 About 2895

13 Switch Between Languages 2897

Index 2899

Index 2899

ix
x
Table of contents

This is the documentation for Espressif IoT Development Framework (esp-idf). ESP-IDF is the official development
framework for the ESP32, ESP32-S, ESP32-C and ESP32-H Series SoCs.
This document describes using ESP-IDF with the ESP32 SoC.

Get Started API Reference API Guides

Espressif Systems 1 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Table of contents

Espressif Systems 2 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1

Get Started

This document is intended to help you set up the software development environment for the hardware based on the
ESP32 chip by Espressif. After that, a simple example will show you how to use ESP-IDF (Espressif IoT Development
Framework) for menu configuration, then for building and flashing firmware onto an ESP32 board.

Note: This is documentation for the master branch (latest version) of ESP-IDF. This version is under continual
development. Stable version documentation is available, as well as other ESP-IDF Versions.

1.1 Introduction
ESP32 is a system on a chip that integrates the following features:
• Wi-Fi (2.4 GHz band)
• Bluetooth
• Dual high performance Xtensa® 32-bit LX6 CPU cores
• Ultra Low Power co-processor
• Multiple peripherals
Powered by 40 nm technology, ESP32 provides a robust, highly integrated platform, which helps meet the continuous
demands for efficient power usage, compact design, security, high performance, and reliability.
Espressif provides basic hardware and software resources to help application developers realize their ideas using the
ESP32 series hardware. The software development framework by Espressif is intended for development of Internet-
of-Things (IoT) applications with Wi-Fi, Bluetooth, power management and several other system features.

1.2 What You Need

1.2.1 Hardware

• An ESP32 board.
• USB cable - USB A / micro USB B.
• Computer running Windows, Linux, or macOS.

Note: Currently, some of the development boards are using USB Type C connectors. Be sure you have the correct
cable to connect your board!

3
Chapter 1. Get Started

If you have one of ESP32 official development boards listed below, you can click on the link to learn more about the
hardware.

ESP32-DevKitC V4 Getting Started Guide

This guide shows how to start using the ESP32-DevKitC V4 development board.

What You Need


• ESP32-DevKitC V4 board
• USB A/micro USB B cable
• Computer running Windows, Linux, or macOS
You can skip the introduction sections and go directly to Section Start Application Development.

Overview ESP32-DevKitC V4 is a small-sized ESP32-based development board produced by Espressif. Most of


the I/O pins are broken out to the pin headers on both sides for easy interfacing. Developers can either connect
peripherals with jumper wires or mount ESP32-DevKitC V4 on a breadboard.
To cover a wide range of user requirements, the following versions of ESP32-DevKitC V4 are available:
• different ESP32 modules
– ESP32-WROOM-DA
– ESP32-WROOM-32E
– ESP32-WROOM-32UE
– ESP32-WROOM-32D
– ESP32-WROOM-32U
– ESP32-SOLO-1
– ESP32-WROVER-E
– ESP32-WROVER-IE
• male or female pin headers.
For details please refer to ESP Product Selector.

Functional Description The following figure and the table below describe the key components, interfaces and
controls of the ESP32-DevKitC V4 board.

Key Component Description


ESP32-WROOM-32 A module with ESP32 at its core. For more information, see ESP32-WROOM-32
Datasheet.
EN Reset button.
Boot Download button. Holding down Boot and then pressing EN initiates Firmware
Download mode for downloading firmware through the serial port.
USB-to-UART Bridge Single USB-UART bridge chip provides transfer rates of up to 3 Mbps.
Micro USB Port USB interface. Power supply for the board as well as the communication interface
between a computer and the ESP32-WROOM-32 module.
5V Power On LED Turns on when the USB or an external 5V power supply is connected to the board.
For details see the schematics in Related Documents.
I/O Most of the pins on the ESP module are broken out to the pin headers on the board.
You can program ESP32 to enable multiple functions such as PWM, ADC, DAC,
I2C, I2S, SPI, etc.

Espressif Systems 4 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 1: ESP32-DevKitC V4 with ESP32-WROOM-32 module soldered

Power Supply Options There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V and GND header pins
• 3V3 and GND header pins

Warning: The power supply must be provided using one and only one of the options above, otherwise the
board and/or the power supply source can be damaged.

Header Block The two tables below provide the Name and Function of I/O header pins on both sides of the board,
as shown in ESP32-DevKitC V4 with ESP32-WROOM-32 module soldered.

Espressif Systems 5 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

J2
No. Name TypePage 6,Function
1

1 3V3 P 3.3 V power supply


2 EN I CHIP_PU, Reset
3 VP I GPIO36, ADC1_CH0, S_VP
4 VN I GPIO39, ADC1_CH3, S_VN
5 IO34 I GPIO34, ADC1_CH6, VDET_1
6 IO35 I GPIO35, ADC1_CH7, VDET_2
7 IO32 I/O GPIO32, ADC1_CH4, TOUCH_CH9, XTAL_32K_P
8 IO33 I/O GPIO33, ADC1_CH5, TOUCH_CH8, XTAL_32K_N
9 IO25 I/O GPIO25, ADC1_CH8, DAC_1
10 IO26 I/O GPIO26, ADC2_CH9, DAC_2
11 IO27 I/O GPIO27, ADC2_CH7, TOUCH_CH7
12 IO14 I/O GPIO14, ADC2_CH6, TOUCH_CH6, MTMS
13 IO12 I/O GPIO12, ADC2_CH5, TOUCH_CH5, MTDI
14 GND G Ground
15 IO13 I/O GPIO13, ADC2_CH4, TOUCH_CH4, MTCK
16 D2 I/O GPIO9, D22
17 D3 I/O GPIO10, D3Page 6, 2
18 CMD I/O GPIO11, CMDPage 6, 2
19 5V P 5 V power supply

J3
No. Name Type? Function
1 GND G Ground
2 IO23 I/O GPIO23
3 IO22 I/O GPIO22
4 TX I/O GPIO1, U0TXD
5 RX I/O GPIO3, U0RXD
6 IO21 I/O GPIO21
7 GND G Ground
8 IO19 I/O GPIO19
9 IO18 I/O GPIO18
10 IO5 I/O GPIO5
11 IO17 I/O GPIO173
12 IO16 I/O GPIO163
13 IO4 I/O GPIO4, ADC2_CH0, TOUCH_CH0
14 IO0 I/O GPIO0, ADC2_CH1, TOUCH_CH1, Boot
15 IO2 I/O GPIO2, ADC2_CH2, TOUCH_CH2
16 IO15 I/O GPIO15, ADC2_CH3, TOUCH_CH3, MTDO
17 D1 I/O GPIO8, D1?
18 D0 I/O GPIO7, D0?
19 CLK I/O GPIO6, CLK?

Pin Layout

Note on C15 The component C15 may cause the following issues on earlier ESP32-DevKitC V4 boards:
• The board may boot into Download mode
• If you output clock on GPIO0, C15 may impact the signal
1 P: Power supply; I: Input; O: Output.
2 The pins D0, D1, D2, D3, CMD and CLK are used internally for communication between ESP32 and SPI flash memory. They are grouped
on both sides near the USB connector. Avoid using these pins, as it may disrupt access to the SPI flash memory/SPI RAM.
3 The pins GPIO16 and GPIO17 are available for use only on the boards with the modules ESP32-WROOM and ESP32-SOLO-1. The boards

with ESP32-WROVER modules have the pins reserved for internal use.

Espressif Systems 6 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 2: ESP32-DevKitC Pin Layout (click to enlarge)

In case these issues occur, please remove the component. The figure below shows the location of C15 highlighted in
yellow.

Start Application Development Before powering up your ESP32-DevKitC V4, please make sure that the board
is in good condition with no obvious signs of damage.
After that, proceed to Get Started, where Section Installation will quickly help you set up the development environment
and then flash an example project onto your board.

Board Dimensions

Related Documents
• ESP32-DevKitC V4 schematics (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROOM-32 Datasheet (PDF)
• ESP32-WROOM-32D and ESP32-WROOM-32U Datasheet (PDF)
• ESP32-WROOM-DA Datasheet (PDF)
• ESP32-WROVER Datasheet (PDF)
• ESP32-WROVER-B Datasheet (PDF)
• ESP Product Selector
For further design documentation for the board, please contact us at [email protected].

ESP32-DevKitC V2 Getting Started Guide


This guide shows how to start using the ESP32-DevKitC V2 development board.

Espressif Systems 7 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 3: Location of C15 (yellow) on ESP32-DevKitC V4 board

Fig. 4: Dimensions of ESP32-DevKitC board with ESP32-WROOM-32 module soldered - back (click to enlarge)

Espressif Systems 8 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

What You Need


• ESP32-DevKitC V2 board
• USB A/micro USB B cable
• Computer running Windows, Linux, or macOS
You can skip the introduction sections and go directly to Section Start Application Development.

Overview ESP32-DevKitC V2 is a small-sized ESP32-based development board produced by Espressif. Most of


the I/O pins are broken out to the pin headers on both sides for easy interfacing. Developers can either connect
peripherals with jumper wires or mount ESP32-DevKitC V4 on a breadboard.

Functional Description The following figure and the table below describe the key components, interfaces and
controls of the ESP32-DevKitC V2 board.

Fig. 5: ESP32-DevKitC V2 board layout

Key Component Description


ESP32-WROOM-32 Standard module with ESP32 at its core. For more information, see ESP32-
WROOM-32 Datasheet
EN Reset button.
Boot Download button. Holding down Boot and then pressing EN initiates Firmware
Download mode for downloading firmware through the serial port.
Micro USB Port USB interface. Power supply for the board as well as the communication interface
between a computer and ESP32-WROOM-32.
I/O Most of the pins on the ESP module are broken out to the pin headers on the board.
You can program ESP32 to enable multiple functions such as PWM, ADC, DAC,
I2C, I2S, SPI, etc.

Power Supply Options There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V and GND header pins
• 3V3 and GND header pins

Espressif Systems 9 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Warning: The power supply must be provided using one and only one of the options above, otherwise the
board and/or the power supply source can be damaged.

Start Application Development Before powering up your ESP32-DevKitC V2, please make sure that the board
is in good condition with no obvious signs of damage.
After that, proceed to Get Started, where Section Installation will quickly help you set up the development environment
and then flash an example project onto your board.

Related Documents
• ESP32-DevKitC schematics (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROOM-32 Datasheet (PDF)

ESP-WROVER-KIT V4.1 Getting Started Guide

This guide shows how to get started with the ESP-WROVER-KIT V4.1 development board and also provides infor-
mation about its functionality and configuration options.

What You Need


• ESP-WROVER-KIT V4.1 board
• USB 2.0 cable (A to Micro-B)
• Computer running Windows, Linux, or macOS
You can skip the introduction sections and go directly to Section Start Application Development.

Overview ESP-WROVER-KIT is an ESP32-based development board produced by Espressif.


ESP-WROVER-KIT features the following integrated components:
• ESP32-WROVER-E module
• LCD screen
• microSD card slot
Another distinguishing feature is the embedded FTDI FT2232HL chip, an advanced multi-interface USB bridge.
This chip enables to use JTAG for direct debugging of ESP32 through the USB interface without a separate JTAG
debugger. ESP-WROVER-KIT makes development convenient, easy, and cost-effective.
Most of the ESP32 I/O pins are broken out to the board’s pin headers for easy access.

Note: ESP32’s GPIO16 and GPIO17 are used as chip select and clock signals for PSRAM. By default, the two
GPIOs are not broken out to the board’s pin headers in order to ensure reliable performance.

Functionality Overview The block diagram below shows the main components of ESP-WROVER-KIT and their
interconnections.

Espressif Systems 10 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 6: ESP-WROVER-KIT block diagram

Fig. 7: ESP-WROVER-KIT board layout - front

Fig. 8: ESP-WROVER-KIT board layout - back

Espressif Systems 11 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Functional Description The following two figures and the table below describe the key components, interfaces,
and controls of the ESP-WROVER-KIT board.
The table below provides description in the following manner:
• Starting from the first picture’s top right corner and going clockwise
• Then moving on to the second picture

Espressif Systems 12 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Key Component Description


FT2232HL The FT2232HL chip serves as a multi-protocol USB-to-serial bridge which can
be programmed and controlled via USB to provide communication with ESP32.
FT2232HL also features USB-to-JTAG interface which is available on channel A
of the chip, while USB-to-serial is on channel B. The FT2232HL chip enhances
user-friendliness in terms of application development and debugging. See ESP-
WROVER-KIT V4.1 schematic.
32.768 kHz External precision 32.768 kHz crystal oscillator serves as a clock with low-power
consumption while the chip is in Deep-sleep mode.
0R Zero-ohm resistor intended as a placeholder for a current shunt, can be desoldered
or replaced with a current shunt to facilitate the measurement of ESP32’s current
consumption in different modes.
ESP32-WROVER-E This ESP32 module features 64-Mbit PSRAM for flexible extended storage and data
module processing capabilities.
Diagnostic LEDs Four red LEDs connected to the GPIO pins of FT2232HL. Intended for future use.
UART Serial port. The serial TX/RX signals of FT2232HL and ESP32 are broken out to
the inward and outward sides of JP2 respectively. By default, these pairs of pins are
connected with jumpers. To use ESP32’s serial interface, remove the jumpers and
connect another external serial device to the respective pins.
SPI By default, ESP32 uses its SPI interface to access flash and PSRAM memory inside
the module. Use these pins to connect ESP32 to another SPI device. In this case, an
extra chip select (CS) signal is needed. Please note that the voltage of this interface
is 3.3 V.
CTS/RTS Serial port flow control signals: the pins are not connected to the circuitry by default.
To enable them, short the respective pins of JP14 with jumpers.
JTAG JTAG interface. JTAG signals of FT2232HL and ESP32 are broken out to the in-
ward and outward sides of JP2 respectively. By default, these pairs of pins are dis-
connected. To enable JTAG, short the respective pins with jumpers as shown in
Section Setup Options.
USB Port USB interface. Power supply for the board as well as the communication interface
between a computer and the board.
EN Button Reset button.
BOOT Button Download button. Holding down Boot and then pressing EN initiates Firmware
Download mode for downloading firmware through the serial port.
Power Switch Power On/Off Switch. Toggling toward the Boot button powers the board on, tog-
gling away from Boot powers the board off.
Power Selector Power supply selector interface. The board can be powered either via USB or via the
5V Input interface. Select the power source with a jumper. For more details, see
Section Setup Options, jumper header JP7.
5V Input 5V power supply interface for a standard coaxial power connector, 5.5 x 2.1 mm,
center positive. This interface can be more convenient when the board is operating
autonomously (not connected to a computer).
5V Power On LED This red LED turns on when power is supplied to the board, either from USB or 5V
Input.
LDO NCP1117(1A). 5V-to-3.3V LDO. NCP1117 can provide a maximum current of 1A.
The LDO on the board has a fixed output voltage, but the user can install an LDO
with adjustable output voltage. For details, please refer to ESP-WROVER-KIT V4.1
schematic.
Camera Connector Camera interface, a standard OV7670 camera module.
RGB LED Red, green and blue (RGB) light emitting diodes (LEDs), can be controlled by pulse
width modulation (PWM).
I/O Connector All the pins on the ESP32 module are broken out to pin headers. You can program
ESP32 to enable multiple functions, such as PWM, ADC, DAC, I2C, I2S, SPI, etc.
microSD Card Slot Useful for developing applications that access microSD card for data storage and
retrieval.
LCD Support for mounting and interfacing a 3.2”SPI (standard 4-wire Serial Peripheral
Interface) LCD, as shown in figure ESP-WROVER-KIT board layout - back.

Espressif Systems 13 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Setup Options There are three jumper blocks available to set up the board functionality. The most frequently
required options are listed in the table below.

Espressif Systems 14 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Header Jumper Setting Description of Functionality

JP7 Power ESP-WROVER-KIT via an external


power supply

JP7 Power ESP-WROVER-KIT via USB

JP2 Enable JTAG functionality

JP2 Enable UART communication

Espressif Systems 15 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Allocation of ESP32 Pins Some pins or terminals of ESP32 are allocated for use with the onboard or external
hardware. If that hardware is not used, e.g., nothing is plugged into the Camera (JP4) header, then these GPIOs can
be used for other purposes.
Some of the pins, such as GPIO0 or GPIO2, have multiple functions and some of them are shared among onboard
and external peripheral devices. Certain combinations of peripherals cannot work together. For example, it is not
possible to do JTAG debugging of an application that is using SD card, because several pins are shared by JTAG and
the SD card slot.
In other cases, peripherals can coexist under certain conditions. This is applicable to, for example, LCD screen and
SD card that share only a single pin GPIO21. This pin is used to provide D/C (Data/Control) signal for the LCD as
well as the Card Detect signal read from the SD card slot. If the card detect functionality is not essential, then it may
be disabled by removing R167, so both LCD and SD may operate together.
For more details on which pins are shared among which peripherals, please refer to the table in the next section.

Main I/O Connector/JP1 The JP1 connector consists of 14x2 male pins whose functions are shown in the middle
two “I/O”columns of the table below. The two “Shared With”columns on both sides describe where else on the
board a certain GPIO is used.

Shared With I/O I/O Shared With


n/a 3.3V GND n/a
NC/XTAL IO32 IO33 NC/XTAL
JTAG, microSD IO12 IO13 JTAG,microSD
JTAG, microSD IO14 IO27 Camera
Camera IO26 IO25 Camera, LCD
Camera IO35 IO34 Camera
Camera IO39 IO36 Camera
JTAG EN IO23 Camera, LCD
Camera, LCD IO22 IO21 Camera, LCD, microSD
Camera, LCD IO19 IO18 Camera, LCD
Camera, LCD IO5 IO17 PSRAM
PSRAM IO16 IO4 LED, Camera, microSD
Camera, LED, Boot IO0 IO2 LED, microSD
JTAG, microSD IO15 5V

Legend:
• NC/XTAL - 32.768 kHz Oscillator
• JTAG - JTAG/JP2
• Boot - Boot button/SW2
• Camera - Camera/JP4
• LED - RGB LED
• microSD - microSD Card/J4
• LCD - LCD/U5
• PSRAM - ESP32-WROVER-E’s PSRAM

32.768 kHz Oscillator


. ESP32 Pin
1 GPIO32
2 GPIO33

Note: Since GPIO32 and GPIO33 are connected to the oscillator by default, they are not connected to the JP1 I/O
connector to maintain signal integrity. This allocation may be changed from the oscillator to JP1 by desoldering the
zero-ohm resistors from positions R11 or R23 and re-soldering them to positions R12 or R24.

Espressif Systems 16 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

SPI Flash/JP2
. ESP32 Pin
1 CLK/GPIO6
2 SD0/GPIO7
3 SD1/GPIO8
4 SD2/GPIO9
5 SD3/GPIO10
6 CMD/GPIO11

Note: SPI Flash pins are used to access the internal flash memory. Therefore, they are not available to connect
external SPI devices. Those pins are exposed for monitoring or for advanced usage only.

Important: The module’s flash bus is connected to the jumper block JP2 through zero-ohm resistors R140 ~
R145. If the flash memory needs to operate at the frequency of 80 MHz, for reasons such as improving the integrity
of bus signals, you can desolder these resistors to disconnect the module’s flash bus from the pin header JP2.

JTAG/JP2
. ESP32 Pin JTAG Signal
1 EN TRST_N
2 MTMS/GPIO14 TMS
3 MTDO/GPIO15 TDO
4 MTDI/GPIO12 TDI
5 MTCK/GPIO13 TCK

Camera/JP4
. ESP32 Pin Camera Signal
1 n/a 3.3V
2 n/a Ground
3 GPIO27 SIO_C/SCCB Clock
4 GPIO26 SIO_D/SCCB Data
5 GPIO25 VSYNC/Vertical Sync
6 GPIO23 HREF/Horizontal Reference
7 GPIO22 PCLK/Pixel Clock
8 GPIO21 XCLK/System Clock
9 GPIO35 D7/Pixel Data Bit 7
10 GPIO34 D6/Pixel Data Bit 6
11 GPIO39 D5/Pixel Data Bit 5
12 GPIO36 D4/Pixel Data Bit 4
13 GPIO19 D3/Pixel Data Bit 3
14 GPIO18 D2/Pixel Data Bit 2
15 GPIO5 D1/Pixel Data Bit 1
16 GPIO4 D0/Pixel Data Bit 0
17 GPIO0 RESET/Camera Reset
18 n/a PWDN/Camera Power Down

• Signals D0 .. D7 denote camera data bus

RGB LED
. ESP32 Pin RGB LED
1 GPIO0 Red
2 GPIO2 Green
3 GPIO4 Blue

Espressif Systems 17 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

microSD Card
. ESP32 Pin microSD Signal
1 MTDI/GPIO12 DATA2
2 MTCK/GPIO13 CD/DATA3
3 MTDO/GPIO15 CMD
4 MTMS/GPIO14 CLK
5 GPIO2 DATA0
6 GPIO4 DATA1
7 GPIO21 Card Detect

LCD/U5
. ESP32 Pin LCD Signal
1 GPIO18 RESET
2 GPIO19 SCL
3 GPIO21 D/C
4 GPIO22 CS
5 GPIO23 SDA
6 GPIO25 SDO
7 GPIO5 Backlight

Start Application Development Before powering up your ESP-WROVER-KIT, please make sure that the board
is in good condition with no obvious signs of damage.

Initial Setup Please set only the following jumpers shown in the pictures below:
• Select USB as the power source using the jumper block JP7.
• Enable UART communication using the jumper block JP2.

Power up from USB port Enable UART communication

Do not install any other jumpers.


Turn the Power Switch to ON, and the 5 V Power On LED should light up.

Now to Development Please proceed to Get Started, where Section Installation will quickly help you set up the
development environment and then flash an example project onto your board.
A Board Support Package can be found in IDF Component Registry.

Espressif Systems 18 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

The application examples that use some hardware specific to your ESP-WROVER-KIT can be found below.
• On-board LCD example: peripherals/spi_master/lcd
• SD card slot example: storage/sd_card
• Camera connector example: https://github.com/espressif/esp32-camera

Related Documents
• ESP-WROVER-KIT V4.1 schematic (PDF)
• ESP-WROVER-KIT V4.1 layout (DXF) may be opened online with Autodesk Viewer
• ESP32 Datasheet (PDF)
• ESP32-WROVER-E Datasheet (PDF)
• JTAG Debugging
• Hardware Reference

ESP-WROVER-KIT V3 Getting Started Guide


This guide shows how to get started with the ESP-WROVER-KIT V3 development board and also provides infor-
mation about its functionality and configuration options. For the description of other ESP-WROVER-KIT versions,
please check Hardware Reference.

What You Need


• ESP-WROVER-KIT V3 board
• USB 2.0 cable (A to Micro-B)
• Computer running Windows, Linux, or macOS
You can skip the introduction sections and go directly to Section Start Application Development.

Overview ESP-WROVER-KIT is an ESP32-based development board produced by Espressif. This board features
an integrated LCD screen and microSD card slot.
ESP-WROVER-KIT comes with the following ESP32 modules:
• ESP32-WROOM-32
• ESP32-WROVER series
Its another distinguishing feature is the embedded FTDI FT2232HL chip - an advanced multi-interface USB bridge.
This chip enables to use JTAG for direct debugging of ESP32 through the USB interface without a separate JTAG
debugger. ESP-WROVER-KIT makes development convenient, easy, and cost-effective.
Most of the ESP32 I/O pins are broken out to the board’s pin headers for easy access.

Note: The version with the ESP32-WROVER module uses ESP32’s GPIO16 and GPIO17 as chip
select and clock signals for PSRAM. By default, the two GPIOs are not broken out to the board’s pin
headers in order to ensure reliable performance.

Functionality Overview The block diagram below shows the main components of ESP-WROVER-KIT and their
interconnections.

Functional Description The following two figures and the table below describe the key components, interfaces,
and controls of the ESP-WROVER-KIT board.
The table below provides description in the following manner:
• Starting from the first picture’s top right corner and going clockwise
• Then moving on to the second picture

Espressif Systems 19 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 9: ESP-WROVER-KIT block diagram

Key Component Description


32.768 kHz External precision 32.768 kHz crystal oscillator serves as a clock with low-power
consumption while the chip is in Deep-sleep mode.
0R Zero-ohm resistor intended as a placeholder for a current shunt, can be desoldered
or replaced with a current shunt to facilitate the measurement of ESP32’s current
consumption in different modes.
ESP32 Module Either ESP32-WROOM-32 or ESP32-WROVER with an integrated ESP32. The
ESP32-WROVER module features all the functions of ESP32-WROOM-32 and
integrates an external 32-MBit PSRAM for flexible extended storage and data pro-
cessing capabilities.
FT2232 The FT2232 chip serves as a multi-protocol USB-to-serial bridge which can be pro-
grammed and controlled via USB to provide communication with ESP32. FT2232
also features USB-to-JTAG interface which is available on channel A of the chip,
while USB-to-serial is on channel B. The FT2232 chip enhances user-friendliness
in terms of application development and debugging. See ESP-WROVER-KIT V3
schematic.
UART Serial port. The serial TX/RX signals of FT2232 and ESP32 are broken out to the
inward and outward sides of JP11 respectively. By default, these pairs of pins are
connected with jumpers. To use ESP32’s serial interface, remove the jumpers and
connect another external serial device to the respective pins.
SPI By default, ESP32 uses its SPI interface to access flash and PSRAM memory inside
the module. Use these pins to connect ESP32 to another SPI device. In this case,
an extra chip select (CS) signal is needed. Please note that the interface voltage for
the version with ESP32-WROVER is 1.8V, while that for the version with ESP32-
WROOM-32 is 3.3V.
CTS/RTS Serial port flow control signals: the pins are not connected to the circuitry by default.
To enable them, short the respective pins of JP14 with jumpers.
JTAG JTAG interface. JTAG signals of FT2232 and ESP32 are broken out to the inward
and outward sides of JP8 respectively. By default, these pairs of pins are discon-
nected. To enable JTAG, short the respective pins with jumpers as shown in Section
Setup Options.
EN Reset button.
Boot Download button. Holding down Boot and then pressing EN initiates Firmware
Download mode for downloading firmware through the serial port.
USB USB interface. Power supply for the board as well as the communication interface
between a computer and the board.
Power Key Power On/Off Switch. Toggling toward USB powers the board on, toggling away
Espressif Systems from USB powers the board 20 off. Release v5.2-dev-3065-g272b4091f1
Power Select Submit Document Feedback
Power supply selector interface. The board can be powered either via USB or via the
5V Input interface. Select the power source with a jumper. For more details, see
Section Setup Options, jumper header JP7.
Chapter 1. Get Started

Fig. 10: ESP-WROVER-KIT board layout - front

Espressif Systems 21 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 11: ESP-WROVER-KIT board layout - back

Espressif Systems 22 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Setup Options There are five jumper blocks available to set up the board functionality. The most frequently
required options are listed in the table below.

Espressif Systems 23 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Header Jumper Setting Description of Functionality

JP7 Power ESP-WROVER-KIT via an external power


supply

JP7 Power ESP-WROVER-KIT via USB

JP8 Enable JTAG functionality

Espressif Systems 24 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Allocation of ESP32 Pins Some pins/terminals of ESP32 are allocated for use with the onboard or external hard-
ware. If that hardware is not used, e.g., nothing is plugged into the Camera (JP4) header, then these GPIOs can be
used for other purposes.
Some of the pins, such as GPIO0 or GPIO2, have multiple functions and some of them are shared among onboard
and external peripheral devices. Certain combinations of peripherals cannot work together. For example, it is not
possible to do JTAG debugging of an application that is using SD card, because several pins are shared by JTAG and
the SD card slot.
In other cases, peripherals can coexist under certain conditions. This is applicable to, for example, LCD screen and
SD card that share only a single pin GPIO21. This pin is used to provide D/C (Data/Control) signal for the LCD as
well as the CD (Card Detect) signal read from the SD card slot. If the card detect functionality is not essential, then
it may be disabled by removing R167, so both LCD and SD may operate together.
For more details on which pins are shared among which peripherals, please refer to the table in the next section.

Main I/O Connector/JP1 The JP1 connector consists of 14x2 male pins whose functions are shown in the middle
two “I/O”columns of the table below. The two “Shared With”columns on both sides describe where else on the
board a certain GPIO is used.

Shared With I/O I/O Shared With


n/a 3.3V GND n/a
NC/XTAL IO32 IO33 NC/XTAL
JTAG, microSD IO12 IO13 JTAG, microSD
JTAG, microSD IO14 IO27 Camera
Camera IO26 IO25 Camera, LCD
Camera IO35 IO34 Camera
Camera IO39 IO36 Camera
JTAG EN IO23 Camera, LCD
Camera, LCD IO22 IO21 Camera, LCD, microSD
Camera, LCD IO19 IO18 Camera, LCD
Camera, LCD IO5 IO17 PSRAM
PSRAM IO16 IO4 LED, Camera, microSD
Camera, LED, Boot IO0 IO2 LED, microSD
JTAG, microSD IO15 5V

Legend:
• NC/XTAL - 32.768 kHz Oscillator
• JTAG - JTAG / JP8
• Boot - Boot button / SW2
• Camera - Camera / JP4
• LED - RGB LED
• microSD - microSD Card / J4
• LCD - LCD / U5
• PSRAM - only in case ESP32-WROVER is installed

32.768 kHz Oscillator


. ESP32 Pin
1 GPIO32
2 GPIO33

Note: Since GPIO32 and GPIO33 are connected to the oscillator by default, they are not connected to the JP1 I/O
connector to maintain signal integrity. This allocation may be changed from the oscillator to JP1 by desoldering the
zero-ohm resistors from positions R11/R23 and re-soldering them to positions R12/R24.

Espressif Systems 25 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

SPI Flash/JP13
. ESP32 Pin
1 CLK/GPIO6
2 SD0/GPIO7
3 SD1/GPIO8
4 SD2/GPIO9
5 SD3/GPIO10
6 CMD/GPIO11

Important: The module’s flash bus is connected to the jumper block JP13 through zero-ohm resistors R140 ~
R145. If the flash memory needs to operate at the frequency of 80 MHz, for reasons such as improving the integrity
of bus signals, you can desolder these resistors to disconnect the module’s flash bus from the pin header JP13.

JTAG/JP8
. ESP32 Pin JTAG Signal
1 EN TRST_N
2 MTMS/GPIO14 TMS
3 MTDO/GPIO15 TDO
4 MTDI/GPIO12 TDI
5 MTCK/GPIO13 TCK

Camera/JP4
. ESP32 Pin Camera Signal
1 n/a 3.3V
2 n/a Ground
3 GPIO27 SIO_C/SCCB Clock
4 GPIO26 SIO_D/SCCB Data
5 GPIO25 VSYNC/Vertical Sync
6 GPIO23 HREF/Horizontal Reference
7 GPIO22 PCLK/Pixel Clock
8 GPIO21 XCLK/System Clock
9 GPIO35 D7/Pixel Data Bit 7
10 GPIO34 D6/Pixel Data Bit 6
11 GPIO39 D5/Pixel Data Bit 5
12 GPIO36 D4/Pixel Data Bit 4
13 GPIO19 D3/Pixel Data Bit 3
14 GPIO18 D2/Pixel Data Bit 2
15 GPIO5 D1/Pixel Data Bit 1
16 GPIO4 D0/Pixel Data Bit 0
17 GPIO0 RESET/Camera Reset
18 n/a PWDN/Camera Power Down

• Signals D0 .. D7 denote camera data bus

RGB LED
. ESP32 Pin RGB LED
1 GPIO0 Red
2 GPIO2 Green
3 GPIO4 Blue

Espressif Systems 26 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

microSD Card
. ESP32 Pin microSD Signal
1 MTDI/GPIO12 DATA2
2 MTCK/GPIO13 CD/DATA3
3 MTDO/GPIO15 CMD
4 MTMS/GPIO14 CLK
5 GPIO2 DATA0
6 GPIO4 DATA1
7 GPIO21 CD

LCD/U5
. ESP32 Pin LCD Signal
1 GPIO18 RESET
2 GPIO19 SCL
3 GPIO21 D/C
4 GPIO22 CS
5 GPIO23 SDA
6 GPIO25 SDO
7 GPIO5 Backlight

Start Application Development Before powering up your ESP-WROVER-KIT, please make sure that the board
is in good condition with no obvious signs of damage.

Initial Setup Please set only the following jumpers shown in the pictures below:
• Select USB as the power source using the jumper block JP7.
• Enable UART communication using the jumper block JP11.

Power up from USB port Enable UART communication

Do not install any other jumpers.


Turn the Power Switch to ON, the 5V Power On LED should light up.

Now to Development Please proceed to Get Started, where Section Installation will quickly help you set up the
development environment and then flash an example project onto your board.

Espressif Systems 27 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Related Documents
• ESP-WROVER-KIT V3 schematic (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROVER Datasheet (PDF)
• ESP32-WROOM-32 Datasheet (PDF)
• JTAG Debugging
• Hardware Reference

ESP-WROVER-KIT V2 Getting Started Guide


This guide shows how to get started with the ESP-WROVER-KIT V2 development board and also provides infor-
mation about its functionality and configuration options. For the description of other ESP-WROVER-KIT versions,
please check Hardware Reference.

What You Need


• ESP-WROVER-KIT V2 board
• USB 2.0 cable (A to Micro-B)
• Computer running Windows, Linux, or macOS
You can skip the introduction sections and go directly to Section Start Application Development.

Overview ESP-WROVER-KIT is an ESP32-based development board produced by Espressif. This board features
an integrated LCD screen and microSD card slot.
ESP-WROVER-KIT comes with the following ESP32 modules:
• ESP32-WROOM-32
• ESP32-WROVER series
Its another distinguishing feature is the embedded FTDI FT2232HL chip - an advanced multi-interface USB bridge.
This chip enables to use JTAG for direct debugging of ESP32 through the USB interface without a separate JTAG
debugger. ESP-WROVER-KIT makes development convenient, easy, and cost-effective.
Most of the ESP32 I/O pins are broken out to the board’s pin headers for easy access.

Note: The version with the ESP32-WROVER module uses ESP32’s GPIO16 and GPIO17 as chip
select and clock signals for PSRAM. By default, the two GPIOs are not broken out to the board’s pin
headers in order to ensure reliable performance.

Functionality Overview The block diagram below shows the main components of ESP-WROVER-KIT and their
interconnections.

Functional Description The following two figures and the table below describe the key components, interfaces,
and controls of the ESP-WROVER-KIT board.
The table below provides description in the following manner:
• Starting from the first picture’s top right corner and going clockwise
• Then moving on to the second picture

Espressif Systems 28 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 12: ESP-WROVER-KIT block diagram

Fig. 13: ESP-WROVER-KIT board layout - front

Espressif Systems 29 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 14: ESP-WROVER-KIT board layout - back

Espressif Systems 30 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Key Component Description


32.768 kHz External precision 32.768 kHz crystal oscillator serves as a clock with low-power
consumption while the chip is in Deep-sleep mode.
ESP32 Module Either ESP32-WROOM-32 or ESP32-WROVER with an integrated ESP32. The
ESP32-WROVER module features all the functions of ESP32-WROOM-32 and
integrates an external 32-MBit PSRAM for flexible extended storage and data pro-
cessing capabilities.
CTS/RTS Serial port flow control signals: the pins are not connected to the circuitry by default.
To enable them, short the respective pins of JP14 with jumpers.
UART Serial port. The serial TX/RX signals of FT2232 and ESP32 are broken out to the
inward and outward sides of JP11 respectively. By default, these pairs of pins are
connected with jumpers. To use ESP32’s serial interface, remove the jumpers and
connect another external serial device to the respective pins.
SPI By default, ESP32 uses its SPI interface to access flash and PSRAM memory inside
the module. Use these pins to connect ESP32 to another SPI device. In this case,
an extra chip select (CS) signal is needed. Please note that the interface voltage for
the version with ESP32-WROVER is 1.8V, while that for the version with ESP32-
WROOM-32 is 3.3 V.
JTAG JTAG interface. JTAG signals of FT2232 and ESP32 are broken out to the inward
and outward sides of JP8 respectively. By default, these pairs of pins are discon-
nected. To enable JTAG, short the respective pins with jumpers as shown in Section
Setup Options.
FT2232 The FT2232 chip serves as a multi-protocol USB-to-serial bridge which can be pro-
grammed and controlled via USB to provide communication with ESP32. FT2232
features USB-to-UART and USB-to-JTAG functionalities.
EN Reset button.
Boot Download button. Holding down Boot and then pressing EN initiates Firmware
Download mode for downloading firmware through the serial port.
USB USB interface. Power supply for the board as well as the communication interface
between a computer and the board.
Power Select Power supply selector interface. The board can be powered either via USB or via the
5 V Input interface. Select the power source with a jumper. For more details, see
Section Setup Options, jumper header JP7.
Power Key Power On/Off Switch. Toggling toward USB powers the board on, toggling away
from USB powers the board off.
5V Input The 5 V power supply interface can be more convenient when the board is operating
autonomously (not connected to a computer).
LDO NCP1117(1 A). 5V-to-3.3V LDO. NCP1117 can provide a maximum current of 1
A. The LDO on the board has a fixed output voltage. Although, the user can install an
LDO with adjustable output voltage. For details, please refer to ESP-WROVER-KIT
V2 schematic.
Camera Camera interface, a standard OV7670 camera module.
RGB Red, green and blue (RGB) light emitting diodes (LEDs), can be controlled by pulse
width modulation (PWM).
I/O All the pins on the ESP32 module are broken out to pin headers. You can program
ESP32 to enable multiple functions, such as PWM, ADC, DAC, I2C, I2S, SPI, etc.
microSD Card microSD card slot for data storage: when ESP32 enters the download mode, GPIO2
cannot be held high. However, a pull-up resistor is required on GPIO2 to enable the
microSD Card. By default, GPIO2 and the pull-up resistor R153 are disconnected.
To enable the SD Card, use jumpers on JP1 as shown in Section Setup Options.
LCD Support for mounting and interfacing a 3.2”SPI (standard 4-wire Serial Peripheral
Interface) LCD, as shown on figure ESP-WROVER-KIT board layout - back.

Setup Options There are five jumper blocks available to set up the board functionality. The most frequently
required options are listed in the table below.

Espressif Systems 31 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Header Jumper Setting Description of Functionality

JP1 Enable pull up for the microSD Card

JP1 Assert GPIO2 low during each download (by jumping it to


GPIO0)

JP7 Power ESP-WROVER-KIT via an external power supply

JP7 Power ESP-WROVER-KIT via USB

Espressif
JP8 Systems Enable32JTAG functionality Release v5.2-dev-3065-g272b4091f1
Submit Document Feedback
Chapter 1. Get Started

Start Application Development Before powering up your ESP-WROVER-KIT, please make sure that the board
is in good condition with no obvious signs of damage.

Initial Setup Please set only the following jumpers shown in the pictures below:
• Select USB as the power source using the jumper block JP7.
• Enable UART communication using the jumper block JP11.

Power up from USB port Enable UART communication

Do not install any other jumpers.


Turn the Power Switch to ON, the 5V Power On LED should light up.

Now to Development Please proceed to Get Started, where Section Installation will quickly help you set up the
development environment and then flash an example project onto your board.

Related Documents
• ESP-WROVER-KIT V2 schematic (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROVER Datasheet (PDF)
• ESP32-WROOM-32 Datasheet (PDF)
• JTAG Debugging
• Hardware Reference

ESP32-PICO-KIT V4/V4.1 Getting Started Guide

This guide shows how to get started with the ESP32-PICO-KIT V4/V4.1 mini development board. For the description
of other ESP32-PICO-KIT versions, please check Hardware Reference.
This particular description covers ESP32-PICO-KIT V4 and V4.1. The difference is the upgraded USB-UART
bridge from CP2102 in V4 with up to 1 Mbps transfer rates to CP2102N in V4.1 with up to 3 Mbps transfer rates.

What You Need


• ESP32-PICO-KIT mini development board
• USB 2.0 A to Micro B cable
• Computer running Windows, Linux, or macOS
You can skip the introduction sections and go directly to Section Start Application Development.

Espressif Systems 33 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Overview ESP32-PICO-KIT is an ESP32-based mini development board produced by Espressif.


The core of this board is ESP32-PICO-D4 - a System-in-Package (SiP) module with complete Wi-Fi and Bluetooth®
functionalities. Compared to other ESP32 modules, ESP32-PICO-D4 integrates the following peripheral components
in one single package, which otherwise would need to be installed separately:
• 40 MHz crystal oscillator
• 4 MB flash
• Filter capacitors
• RF matching links
This setup reduces the costs of additional external components as well as the cost of assembly and testing and also
increases the overall usability of the product.
The development board features a USB-UART Bridge circuit which allows developers to connect the board to a
computer’s USB port for flashing and debugging.
All the IO signals and system power on ESP32-PICO-D4 are led out to two rows of 20 x 0.1”header pads on both sides
of the development board for easy access. For compatibility with Dupont wires, 2 x 17 header pads are populated
with two rows of male pin headers. The remaining 2 x 3 header pads beside the antenna are not populated. These
pads may be populated later by the user if required.

Note:
1. There are two versions of ESP32-PICO-KIT boards, respectively with male headers and female headers. In
this guide, the male header version is taken as an example.
2. The 2 x 3 pads not populated with pin headers are connected to the flash memory embedded in the ESP32-
PICO-D4 SiP module. For more details, see module’s datasheet in Related Documents.

Functionality Overview The block diagram below shows the main components of ESP32-PICO-KIT and their
interconnections.

Fig. 15: ESP32-PICO-KIT block diagram

Espressif Systems 34 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Functional Description The following figure and the table below describe the key components, interfaces, and
controls of the ESP32-PICO-KIT board.

Fig. 16: ESP32-PICO-KIT board layout (with female headers)

Below is the description of the items identified in the figure starting from the top left corner and going clockwise.

Key Component Description


ESP32-PICO-D4 Standard ESP32-PICO-D4 module soldered to the ESP32-PICO-KIT board. The
complete ESP32 system on a chip (ESP32 SoC) has been integrated into the SiP
module, requiring only an external antenna with LC matching network, decoupling
capacitors, and a pull-up resistor for EN signals to function properly.
LDO 5V-to-3.3V Low dropout voltage regulator (LDO).
USB-UART bridge Single-chip USB-UART bridge: CP2102 in V4 provides up to 1 Mbps transfer rates
and CP2102N in V4.1 offers up to 3 Mbps transfers rates.
Micro USB Port USB interface. Power supply for the board as well as the communication interface
between a computer and the board.
5V Power On LED This red LED turns on when power is supplied to the board. For details, see the
schematics in Related Documents.
I/O All the pins on ESP32-PICO-D4 are broken out to pin headers. You can program
ESP32 to enable multiple functions, such as PWM, ADC, DAC, I2C, I2S, SPI, etc.
For details, please see Section Pin Descriptions.
BOOT Button Download button. Holding down Boot and then pressing EN initiates Firmware
Download mode for downloading firmware through the serial port.
EN Button Reset button.

Power Supply Options There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V / GND header pins
• 3V3 / GND header pins

Warning: The power supply must be provided using one and only one of the options above, otherwise the
board and/or the power supply source can be damaged.

Espressif Systems 35 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Pin Descriptions The two tables below provide the Name and Function of I/O header pins on both sides of the
board, see ESP32-PICO-KIT board layout (with female headers). The pin numbering and header names are the same
as in the schematic given in Related Documents.

Espressif Systems 36 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Espressif Systems 37 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Header J2

No. Name Type Function


1 FLASH_SD1 (FSD1) I/O
GPIO8, SD_DATA1,
SPID, HS1_DATA1 (See
1) , U2CTS

2 FLASH_SD3 (FSD3) I/O


GPIO7, SD_DATA0,
SPIQ, HS1_DATA0 (See
1) , U2RTS

3 FLASH_CLK (FCLK) I/O


GPIO6, SD_CLK,
SPICLK, HS1_CLK (See
1) , U1CTS

4 IO21 I/O
GPIO21, VSPIHD,
EMAC_TX_EN

5 IO22 I/O
GPIO22, VSPIWP,
U0RTS, EMAC_TXD1

6 IO19 I/O
GPIO19, VSPIQ,
U0CTS, EMAC_TXD0

7 IO23 I/O
GPIO23, VSPID,
HS1_STROBE

8 IO18 I/O
GPIO18, VSPICLK,
HS1_DATA7

9 IO5 I/O
GPIO5, VSPICS0,
HS1_DATA6,
EMAC_RX_CLK

10 IO10 I/O
GPIO10, SD_DATA3,
SPIWP, HS1_DATA3,
U1TXD

11 IO9 I/O
GPIO9, SD_DATA2,
SPIHD, HS1_DATA2,
U1RXD

12 RXD0 I/O
Espressif Systems 38 Release v5.2-dev-3065-g272b4091f1
Submit Document Feedback GPIO3, U0RXD (See 3) ,
CLK_OUT2
Chapter 1. Get Started

Espressif Systems 39 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Header J3

No. Name Type Function


1 FLASH_CS (FCS) I/O
GPIO16, HS1_DATA4
(See 1) , U2RXD,
EMAC_CLK_OUT

2 FLASH_SD0 (FSD0) I/O


GPIO17, HS1_DATA5
(See 1) , U2TXD,
EMAC_CLK_OUT_180

3 FLASH_SD2 (FSD2) I/O


GPIO11, SD_CMD,
SPICS0, HS1_CMD (See
1) , U1RTS

4 SENSOR_VP (FSVP) I
GPIO36, ADC1_CH0,
RTC_GPIO0

5 SENSOR_VN (FSVN) I
GPIO39, ADC1_CH3,
RTC_GPIO3

6 IO25 I/O
GPIO25, DAC_1,
ADC2_CH8,
RTC_GPIO6,
EMAC_RXD0

7 IO26 I/O
GPIO26, DAC_2,
ADC2_CH9,
RTC_GPIO7,
EMAC_RXD1

8 IO32 I/O
32K_XP (See 2a) ,
ADC1_CH4, TOUCH9,
RTC_GPIO9

9 IO33 I/O
32K_XN (See 2b) ,
ADC1_CH5, TOUCH8,
RTC_GPIO8

10 IO27 I/O
GPIO27, ADC2_CH7,
TOUCH7,
RTC_GPIO17
EMAC_RX_DV

11
Espressif Systems IO14 40 I/O Release v5.2-dev-3065-g272b4091f1
Submit Document Feedback
ADC2_CH6, TOUCH6,
RTC_GPIO16, MTMS,
HSPICLK,
Chapter 1. Get Started

Note:
1. This pin is connected to the flash pin of ESP32-PICO-D4.
2. 32.768 kHz crystal oscillator: a) input, b) output.
3. This pin is connected to the pin of the USB bridge chip on the board.
4. The operating voltage of ESP32-PICO-KIT’s embedded SPI flash is 3.3 V. Therefore, the strapping pin MTDI
should hold bit zero during the module power-on reset. If connected, please make sure that this pin is not held
up on reset.

Fig. 17: ESP32-PICO-KIT Pin Layout (click to enlarge)

Pin Layout

Start Application Development Before powering up your ESP32-PICO-KIT, please make sure that the board is
in good condition with no obvious signs of damage.
After that, proceed to Get Started, where Section Installation will quickly help you set up the development environment
and then flash an example project onto your board.

Board Dimensions The dimensions are 52 x 20.3 x 10 mm (2.1”x 0.8”x 0.4”).

Fig. 18: ESP32-PICO-KIT dimensions - back (with male headers)

For the board physical construction details, please refer to its Reference Design listed below.

Espressif Systems 41 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 19: ESP32-PICO-KIT dimensions - side (with male headers)

Related Documents
• ESP32-PICO-KIT V4 schematic (PDF)
• ESP32-PICO-KIT V4.1 schematic (PDF)
• ESP32-PICO-KIT Reference Design containing OrCAD schematic, PCB layout, gerbers and BOM
• ESP32-PICO-D4 Datasheet (PDF)
• Hardware Reference

ESP32-PICO-KIT V3 Getting Started Guide


This guide shows how to get started with the ESP32-PICO-KIT V3 mini development board. For the description of
other ESP32-PICO-KIT versions, please check Hardware Reference.

What You Need


• ESP32-PICO-KIT V3 mini development board
• USB 2.0 A to Micro B cable
• Computer running Windows, Linux, or macOS
You can skip the introduction sections and go directly to Section Start Application Development.

Overview ESP32-PICO-KIT V3 is an ESP32-based mini development board produced by Espressif. The core of
this board is ESP32-PICO-D4 - a System-in-Package (SiP) module.
The development board features a USB-UART Bridge circuit, which allows developers to connect the board to a
computer’s USB port for flashing and debugging.
All the IO signals and system power on ESP32-PICO-D4 are led out to two rows of 20 x 0.1”header pads on both
sides of the development board for easy access.

Functional Description The following figure and the table below describe the key components, interfaces, and
controls of the ESP32-PICO-KIT V3 board.
Below is the description of the items identified in the figure starting from the top left corner and going clockwise.

Espressif Systems 42 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 20: ESP32-PICO-KIT V3 board layout

Espressif Systems 43 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Key Component Description


ESP32-PICO-D4 Standard ESP32-PICO-D4 module soldered to the ESP32-PICO-KIT V3 board.
The complete ESP32 system on a chip (ESP32 SoC) has been integrated into the
SiP module, requiring only an external antenna with LC matching network, decou-
pling capacitors, and a pull-up resistor for EN signals to function properly.
LDO 5V-to-3.3V Low dropout voltage regulator (LDO).
USB-UART bridge Single-chip USB-UART bridge provides up to 1 Mbps transfers rates.
Micro USB Port USB interface. Power supply for the board as well as the communication interface
between a computer and the board.
Power On LED This red LED turns on when power is supplied to the board.
I/O All the pins on ESP32-PICO-D4 are broken out to pin headers. You can program
ESP32 to enable multiple functions, such as PWM, ADC, DAC, I2C, I2S, SPI, etc.
BOOT Button Download button. Holding down Boot and then pressing EN initiates Firmware
Download mode for downloading firmware through the serial port.
EN Button Reset button.

Start Application Development Before powering up your ESP32-PICO-KIT V3, please make sure that the board
is in good condition with no obvious signs of damage.
After that, proceed to Get Started, where Section Installation will quickly help you set up the development environment
and then flash an example project onto your board.

Related Documents
• ESP32-PICO-KIT V3 schematic (PDF)
• ESP32-PICO-D4 Datasheet (PDF)
• Hardware Reference

ESP32-Ethernet-Kit V1.2 Getting Started Guide

This guide shows how to get started with the ESP32-Ethernet-Kit development board and also provides information
about its functionality and configuration options.
The ESP32-Ethernet-Kit is an Ethernet-to-Wi-Fi development board that enables Ethernet devices to be intercon-
nected over Wi-Fi. At the same time, to provide more flexible power supply options, the ESP32-Ethernet-Kit also
supports power over Ethernet (PoE).

What You Need


• ESP32-Ethernet-Kit V1.2 board
• USB 2.0 A to Micro B Cable
• Computer running Windows, Linux, or macOS
You can skip the introduction sections and go directly to Section Start Application Development.

Overview ESP32-Ethernet-Kit is an ESP32-based development board produced by Espressif.


It consists of two development boards, the Ethernet board A and the PoE board B. The Ethernet board (A) con-
tains Bluetooth®/Wi-Fi dual-mode ESP32-WROVER-E module and IP101GRI, a Single Port 10/100 Fast Ethernet
Transceiver (PHY). The PoE board (B) provides power over Ethernet functionality. The A board can work indepen-
dently, without the board B installed.
For the application loading and monitoring, the Ethernet board (A) also features FTDI FT2232H chip - an advanced
multi-interface USB bridge. This chip enables to use JTAG for direct debugging of ESP32 through the USB interface
without a separate JTAG debugger.

Espressif Systems 44 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 21: ESP32-Ethernet-Kit V1.2 Overview (click to enlarge)

Espressif Systems 45 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 22: ESP32-Ethernet-Kit V1.2 (click to enlarge)

Espressif Systems 46 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Functionality Overview The block diagram below shows the main components of ESP32-Ethernet-Kit and their
interconnections.

Fig. 23: ESP32-Ethernet-Kit block diagram (click to enlarge)

Functional Description The following figures and tables describe the key components, interfaces, and controls of
the ESP32-Ethernet-Kit.

Ethernet Board (A) The table below provides description starting from the picture’s top right corner and going
clockwise.

Espressif Systems 47 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 24: ESP32-Ethernet-Kit - Ethernet board (A) layout (click to enlarge)

Table 1: Table 1 Component Description


Key Component Description
ESP32-WROVER- This ESP32 module features 64-Mbit PSRAM for flexible extended storage and data
E processing capabilities.
GPIO Header 2 Five unpopulated through-hole solder pads to provide access to selected GPIOs of ESP32.
For details, see GPIO Header 2.
Function Switch A 4-bit DIP switch used to configure the functionality of selected GPIOs of ESP32. For
details see Function Switch.
Tx/Rx LEDs Two LEDs to show the status of UART transmission.
FT2232H The FT2232H chip serves as a multi-protocol USB-to-serial bridge which can be pro-
grammed and controlled via USB to provide communication with ESP32. FT2232H
also features USB-to-JTAG interface which is available on channel A of the chip, while
USB-to-serial is on channel B. The FT2232H chip enhances user-friendliness in terms of
application development and debugging. See ESP32-Ethernet-Kit V1.2 Ethernet board
(A) schematic.
USB Port USB interface. Power supply for the board as well as the communication interface be-
tween a computer and the board.
Power Switch Power On/Off Switch. Toggling the switch to 5V0 position powers the board on, toggling
to GND position powers the board off.
5V Input The 5 V power supply interface can be more convenient when the board is operating
autonomously (not connected to a computer).
5V Power On LED This red LED turns on when power is supplied to the board, either from USB or 5 V
Input.
DC/DC Converter Provided DC 5 V to 3.3 V conversion, output current up to 2 A.
Board B Connectors A pair male and female header pins for mounting the PoE board (B)
IP101GRI (PHY) The physical layer (PHY) connection to the Ethernet cable is implemented using the
IP101GRI chip. The connection between PHY and ESP32 is done through the reduced
media-independent interface (RMII), a variant of the media-independent interface (MII)
standard. The PHY supports the IEEE 802.3/802.3u standard of 10/100 Mbps.
RJ45 Port Ethernet network data transmission port.
Magnetics Module The Magnetics are part of the Ethernet specification to protect against faults and transients,
including rejection of common mode signals between the transceiver IC and the cable.
Espressif Systems The magnetics also provide galvanic
48 isolation between the transceiver
Release and the Ethernet
v5.2-dev-3065-g272b4091f1
device. Submit Document Feedback
Link/Activity LEDs Two LEDs (green and red) that respectively indicate the“Link”and“Activity”statuses
of the PHY.
Chapter 1. Get Started

Note: Automatic firmware download is supported. If following steps and using software described in Section Start
Application Development, users do not need to do any operation with BOOT button or EN button.

PoE Board (B) This board coverts power delivered over the Ethernet cable (PoE) to provide a power supply for the
Ethernet board (A). The main components of the PoE board (B) are shown on the block diagram under Functionality
Overview.
The PoE board (B) has the following features:
• Support for IEEE 802.3at
• Power output: 5 V, 1.4 A
To take advantage of the PoE functionality the RJ45 Port of the Ethernet board (A) should be connected with an
Ethernet cable to a switch that supports PoE. When the Ethernet board (A) detects 5 V power output from the PoE
board (B), the USB power will be automatically cut off.

Fig. 25: ESP32-Ethernet-Kit - PoE board (B) layout (click to enlarge)

Table 2: Table PoE board (B)


Key Component Description
Board A Connector Four female (left) and four male (right) header pins for connecting the PoE board (B) to
Ethernet board (A). The pins on the left accept power coming from a PoE switch. The
pins on the right deliver 5 V power supply to the Ethernet board (A).
External Power Ter- Optional power supply (26.6 ~ 54 V) to the PoE board (B).
minals

Setup Options This section describes options to configure the ESP32-Ethernet-Kit hardware.

Function Switch When in On position, this DIP switch is routing listed GPIOs to FT2232H to provide JTAG
functionality. When in Off position, the GPIOs may be used for other purposes.

DIP SW GPIO Pin


1 GPIO13
2 GPIO12
3 GPIO15
4 GPIO14

RMII Clock Selection The ethernet MAC and PHY under RMII working mode need a common 50 MHz refer-
ence clock (i.e., RMII clock) that can be provided either externally, or generated from internal ESP32 APLL (not
recommended).

Espressif Systems 49 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Note: For additional information on the RMII clock selection, please refer to ESP32-Ethernet-Kit V1.2 Ethernet
board (A) schematic, sheet 2, location D2.

RMII Clock Sourced Externally by PHY By default, the ESP32-Ethernet-Kit is configured to provide RMII
clock for the IP101GRI PHY’s 50M_CLKO output. The clock signal is generated by the frequency multiplication
of 25 MHz crystal connected to the PHY. For details, please see the figure below.

Fig. 26: RMII Clock from IP101GRI PHY

Please note that the PHY is reset on power up by pulling the RESET_N signal down with a resistor. ESP32 should
assert RESET_N high with GPIO5 to enable PHY. Only this can ensure the power-up of system. Otherwise ESP32
may enter download mode (when the clock signal of REF_CLK_50M is at a high logic level during the GPIO0
power-up sampling phase).

RMII Clock Sourced Internally from ESP32’s APLL Another option is to source the RMII Clock from internal
ESP32 APLL, see figure below. The clock signal coming from GPIO0 is first inverted, to account for transmission
line delay, and then supplied to the PHY.
To implement this option, users need to remove or add some RC components on the board. For details please refer
to ESP32-Ethernet-Kit V1.2 Ethernet board (A) schematic, sheet 2, location D2. Please note that if the APLL is
already used for other purposes (e.g., I2S peripheral), then you have no choice but use an external RMII clock.

Espressif Systems 50 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 27: RMII Clock from ESP Internal APLL

Espressif Systems 51 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

GPIO Allocation This section describes allocation of ESP32 GPIOs to specific interfaces or functions of the
ESP32-Ethernet-Kit.

IP101GRI (PHY) Interface The allocation of the ESP32 (MAC) pins to IP101GRI (PHY) is shown in the table
below. Implementation of ESP32-Ethernet-Kit defaults to Reduced Media-Independent Interface (RMII).

No. ESP32 Pin (MAC) IP101GRI (PHY)


RMII Interface
1 GPIO21 TX_EN
2 GPIO19 TXD[0]
3 GPIO22 TXD[1]
4 GPIO25 RXD[0]
5 GPIO26 RXD[1]
6 GPIO27 CRS_DV
7 GPIO0 REF_CLK
Serial Management Interface
8 GPIO23 MDC
9 GPIO18 MDIO
PHY Reset
10 GPIO5 Reset_N

Note: The allocation of all pins under the ESP32’s RMII Interface is fixed and cannot be changed either through IO
MUX or GPIO Matrix. REF_CLK can only be selected from GPIO0, GPIO16 or GPIO17 and it can not be changed
through GPIO Matrix.

GPIO Header 1 This header exposes some GPIOs that are not used elsewhere on the ESP32-Ethernet-Kit.

No. ESP32 Pin


1 GPIO32
2 GPIO33
3 GPIO34
4 GPIO35
5 GPIO36
6 GPIO39

GPIO Header 2 This header contains GPIOs that may be used for other purposes depending on scenarios described
in column “Comments”.

No. ESP32 Pin Comments


1 GPIO17 See note 1
2 GPIO16 See note 1
3 GPIO4
4 GPIO2
5 GPIO13 See note 2
6 GPIO12 See note 2
7 GPIO15 See note 2
8 GPIO14 See note 2
9 GND Ground
10 3V3 3.3 V power supply

Note:

Espressif Systems 52 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

1. The ESP32 pins GPIO16 and GPIO17 are not broken out to the ESP32-WROVER-E module and therefore
not available for use. If you need to use these pins, please solder a module without PSRAM memory inside,
e.g., the ESP32-WROOM-32D or ESP32-SOLO-1.
2. Functionality depends on the settings of the Function Switch.

GPIO Allocation Summary

ESP32-WROVER-E IP101GRI UART JTAG GPIO Comments


S_VP IO36
S_VN IO39
IO34 IO34
IO35 IO35
IO32 IO32
IO33 IO33
IO25 RXD[0]
IO26 RXD[1]
IO27 CRS_DV
IO14 TMS IO14
IO12 TDI IO12
IO13 TCK IO13
IO15 TDO IO15
IO2 IO2
IO0 REF_CLK See note 1
IO4 IO4
IO16 IO16 (NC) See note 2
IO17 IO17 (NC) See note 2
IO5 Reset_N See note 1
IO18 MDIO
IO19 TXD[0]
IO21 TX_EN
RXD0 RXD
TXD0 TXD
IO22 TXD[1]
IO23 MDC

Note:
1. To prevent the power-on state of the GPIO0 from being affected by the clock output on the PHY side, the
RESET_N signal to PHY defaults to low, turning the clock output off. After power-on you can control RE-
SET_N with GPIO5 to turn the clock output on. See also RMII Clock Sourced Externally by PHY. For PHYs
that cannot turn off the clock output through RESET_N, it is recommended to use a crystal module that can be
disabled/enabled externally. Similarly like when using RESET_N, the oscillator module should be disabled by
default and turned on by ESP32 after power-up. For a reference design please see ESP32-Ethernet-Kit V1.2
Ethernet board (A) schematic.
2. The ESP32 pins GPIO16 and GPIO17 are not broken out to the ESP32-WROVER-E module and therefore
not available for use. If you need to use these pins, please solder a module without PSRAM memory inside,
e.g., the ESP32-WROOM-32D or ESP32-SOLO-1.

Start Application Development Before powering up your ESP32-Ethernet-Kit, please make sure that the board
is in good condition with no obvious signs of damage.

Initial Setup

Espressif Systems 53 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

1. Set the Function Switch on the Ethernet board (A) to its default position by turning all the switches to ON.
2. To simplify flashing and testing of the application, do not input extra signals to the board headers.
3. The PoE board (B) can now be plugged in, but do not connect external power to it.
4. Connect the Ethernet board (A) to the PC with a USB cable.
5. Turn the Power Switch from GND to 5V0 position, the 5V Power On LED should light up.

Now to Development Proceed to Get Started, where Section Installation will quickly help you set up the develop-
ment environment and then flash an example project onto your board.
Move on to the next section only if you have successfully completed all the above steps.

Configure and Load the Ethernet Example After setting up the development environment and testing the board,
you can configure and flash the ethernet/basic example. This example has been created for testing Ethernet function-
ality. It supports different PHY, including IP101GRI installed on ESP32-Ethernet-Kit V1.2 (click to enlarge).

Summary of Changes from ESP32-Ethernet-Kit V1.1


• Correct the placement of GPIO pin number marking on the board’s silkscreen besides the DIP switch.
• Values of C1, C2, C42, and C43 are updated to 20 pF. For more information, please check ESP32-Ethernet-Kit
V1.2 Ethernet board (A) schematic.
• Replace ESP32-WROVER-B with ESP32-WROVER-E.

Other Versions of ESP32-Ethernet-Kit


• ESP32-Ethernet-Kit V1.0 Getting Started Guide
• ESP32-Ethernet-Kit V1.1 Getting Started Guide

Related Documents
• ESP32-Ethernet-Kit V1.2 Ethernet Board (A) Schematic (PDF)
• ESP32-Ethernet-Kit PoE Board (B) Schematic (PDF)
• ESP32-Ethernet-Kit V1.2 Ethernet Board (A) PCB Layout (PDF)
• ESP32-Ethernet-Kit PoE Board (B) PCB Layout (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROVER-E Datasheet (PDF)
• JTAG Debugging
• Hardware Reference
For other design documentation for the board, please contact us at [email protected].

ESP32-Ethernet-Kit V1.0 Getting Started Guide


This guide shows how to get started with the ESP32-Ethernet-Kit development board and also provides information
about its functionality and configuration options.
The ESP32-Ethernet-Kit is an Ethernet-to-Wi-Fi development board that enables Ethernet devices to be intercon-
nected over Wi-Fi. At the same time, to provide more flexible power supply options, the ESP32-Ethernet-Kit also
supports power over Ethernet (PoE).

What You Need


• ESP32-Ethernet-Kit V1.0 board
• USB 2.0 A to Micro B Cable
• Computer running Windows, Linux, or macOS
You can skip the introduction sections and go directly to Section Start Application Development.

Espressif Systems 54 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Overview ESP32-Ethernet-Kit is an ESP32-based development board produced by Espressif.


It consists of two development boards, the Ethernet board A and the PoE board B. The Ethernet board (A) con-
tains Bluetooth®/Wi-Fi dual-mode ESP32-WROVER-B module and IP101GRI, a Single Port 10/100 Fast Ethernet
Transceiver (PHY). The PoE board (B) provides power over Ethernet functionality. The A board can work indepen-
dently, without the board B installed.

Fig. 28: ESP32-Ethernet-Kit V1.0

For the application loading and monitoring the Ethernet board (A) also features FTDI FT2232H chip - an advanced
multi-interface USB bridge. This chip enables to use JTAG for direct debugging of ESP32 through the USB interface
without a separate JTAG debugger.

Functionality Overview The block diagram below shows the main components of ESP32-Ethernet-Kit and their
interconnections.

Functional Description The following two figures and tables describe the key components, interfaces, and controls
of the ESP32-Ethernet-Kit.

Ethernet Board (A) The table below provides description starting from the picture’s top right corner and going
clockwise.

Espressif Systems 55 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 29: ESP32-Ethernet-Kit block diagram (click to enlarge)

Fig. 30: ESP32-Ethernet-Kit - Ethernet board (A) layout (click to enlarge)

Espressif Systems 56 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Key Description
Com-
po-
nent
ESP32- This ESP32 module features 64-Mbit PSRAM for flexible extended storage and data processing capabil-
WROVER- ities.
B
GPIO Five unpopulated through-hole solder pads to provide access to selected GPIOs of ESP32. For details,
Header see GPIO Header 2.
2
Flow A jumper header with access to the board signals. For details, see Flow Control.
Con-
trol
Func- A DIP switch used to configure the functionality of selected GPIOs of ESP32. For details, see Function
tion Switch.
Switch
Tx/Rx Two LEDs to show the status of UART transmission.
LEDs
GPIO Provides access to some GPIOs of ESP32 that can be used depending on the position of the Function
Header Switch.
3
FT2232H The FT2232H chip serves as a multi-protocol USB-to-serial bridge which can be programmed and con-
trolled via USB to provide communication with ESP32. FT2232H also features USB-to-JTAG interface
which is available on channel A of the chip, while USB-to-serial is on channel B. The FT2232H chip
enhances user-friendliness in terms of application development and debugging. See ESP32-Ethernet-Kit
V1.0 Ethernet board (A) schematic.
USB USB interface. Power supply for the board as well as the communication interface between a computer
Port and the board.
Power Power On/Off Switch. Toggling toward the Boot button powers the board on, toggling away from Boot
Switch powers the board off.
5V The 5V power supply interface can be more convenient when the board is operating autonomously (not
In- connected to a computer).
put
5V This red LED turns on when power is supplied to the board, either from USB or 5 V Input.
Power
On
LED
DC/DC Provided DC 5 V to 3.3 V conversion, output current up to 2 A.
Con-
verter
Board A pair male header pins for mounting the PoE board (B).
B
Con-
nec-
tors
IP101GRI The physical layer (PHY) connection to the Ethernet cable is implemented using the IP101GRI chip. The
(PHY) connection between PHY and ESP32 is done through the reduced media-independent interface (RMII),
a variant of the media-independent interface (MII) standard. The PHY supports the IEEE 802.3/802.3u
standard of 10/100 Mbps.
RJ45 Ethernet network data transmission port.
Port
Mag- The Magnetics are part of the Ethernet specification to protect against faults and transients, including
net- rejection of common mode signals between the transceiver IC and the cable. The magnetics also provide
ics galvanic isolation between the transceiver and the Ethernet device.
Mod-
ule
Link/Activity
Two LEDs (green and red) that respectively indicate the “Link”and “Activity”statuses of the PHY.
LEDs
BOOT Download button. Holding down BOOT and then pressing CH_PU initiates Firmware Download mode
Espressif
But- for Systems 57
downloading firmware through the serial port. Release v5.2-dev-3065-g272b4091f1
ton Submit Document Feedback
CH_PUReset button.
But-
Chapter 1. Get Started

PoE Board (B) This board coverts power delivered over the Ethernet cable (PoE) to provide a power supply for the
Ethernet board (A). The main components of the PoE board (B) are shown on the block diagram under Functionality
Overview.
The PoE board (B) has the following features:
• Support for IEEE 802.3at
• Power output: 5 V, 1.4 A
To take advantage of the PoE functionality the RJ45 Port of the Ethernet board (A) should be connected with an
Ethernet cable to a switch that supports PoE. When the Ethernet board (A) detects 5 V power output from the PoE
board (B), the USB power will be automatically cut off.

Fig. 31: ESP32-Ethernet-Kit - PoE board (B) layout (click to enlarge)

Key Component Description


Board A Connector Four female header pins for mounting this board onto Ethernet board (A).
External Power Terminals Optional power supply to the PoE board (B).

Setup Options This section describes options to configure the ESP32-Ethernet-Kit hardware.

Function Switch The functions for specific GPIO pins can be selected with the Function Switch.

DIP SW GPIO Pin Pin Functionality if DIP SW is ON


1 GPIO14 Connected to FT2232H to provide JTAG functionality
2 GPIO12 Connected to FT2232H to provide JTAG functionality
3 GPIO13 Connected to FT2232H to provide JTAG functionality
4 GPIO15 Connected to FT2232H to provide JTAG functionality
5 GPIO4 Connected to FT2232H to provide JTAG functionality
6 GPIO2 Connected to on-board 25 MHz oscillator
7 GPIO5 Connected to RESET_N input of IP101GRI
8 n/a

You can make a certain GPIO pin available for other purposes by putting its DIP SW to the Off position.

Flow Control This is a 2 x 2 jumper pin header intended for the UART flow control.

. Signal Comment
1 MTDO GPIO13, see also Function Switch
2 MTCK GPIO15, see also Function Switch
3 RTS RTS signal of FT2232H
4 CTS CTS signal of FT2232H

GPIO Allocation This section describes allocation of ESP32 GPIOs to specific interfaces or functions of the
ESP32-Ethernet-Kit.

Espressif Systems 58 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

IP101GRI (PHY) Interface The allocation of the ESP32 (MAC) pins to IP101GRI (PHY) is shown in the table
below. Implementation of ESP32-Ethernet-Kit defaults to Reduced Media-Independent Interface (RMII).

. ESP32 Pin (MAC) IP101GRI (PHY)


RMII Interface
1 GPIO21 TX_EN
2 GPIO19 TXD[0]
3 GPIO22 TXD[1]
4 GPIO25 RXD[0]
5 GPIO26 RXD[1]
6 GPIO27 CRS_DV
7 GPIO0 REF_CLK
Serial Management Interface
8 GPIO23 MDC
9 GPIO18 MDIO
PHY Reset
10 GPIO5 Reset_N

Note: Except for REF_CLK, the allocation of all pins under the RMII Interface is fixed and cannot be changed either
through IOMUX or GPIO Matrix.

GPIO Header 1 This header exposes some GPIOs that are not used elsewhere on the ESP32-Ethernet-Kit.

. ESP32 Pin
1 GPIO32
2 GPIO33
3 GPIO34
4 GPIO35
5 GPIO36
6 GPIO39

GPIO Header 2 This header contains the GPIOs with specific MII functionality (except GPIO2), as opposed to
Reduced Media-Independent Interface (RMII) functionality implemented on ESP32-Ethernet-Kit board by default,
see IP101GRI (PHY) Interface. Depending on the situation, if MMI is used, specific Ethernet applications might
require this functionality.

. ESP32 Pin MII Function Comments


1 GPIO17 EMAC_CLK_180 See note 1
2 GPIO16 EMAC_CLK_OUT See note 1
3 GPIO4 EMAC_TX_ER
4 GPIO2 n/a See note 2
5 GPIO5 EMAC_RX_CLK See note 2

Note:
1. The ESP32 pins GPIO16 and GPIO17 are not broken out to the ESP32-WROVER-B module and therefore
not available for use. If you need to use these pins, please solder a module without SPIRAM memory inside,
e.g., the ESP32-WROOM-32D or ESP32-SOLO-1.
2. Functionality depends on the settings of the Function Switch.

Espressif Systems 59 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

GPIO Header 3 The functionality of GPIOs connected to this header depends on the settings of the Function
Switch.

. ESP32 Pin
1 GPIO15
2 GPIO13
3 GPIO12
4 GPIO14
5 GND
6 3V3

GPIO Allocation Summary

ESP32-WROVER-B IP101GRI UART JTAG GPIO Comments


S_VP IO36
S_VN IO39
IO34 IO34
IO35 IO35
IO32 IO32
IO33 IO33
IO25 RXD[0]
IO26 RXD[1]
IO27 CRS_DV
IO14 TMS IO14
IO12 TDI IO12
IO13 RTS TCK IO13
IO15 CTS TDO IO15
IO2 IO2 See notes 1 and 3 below
IO0 REF_CLK See notes 2 and 3 below
IO4 nTRST IO4
IO16 IO16 (NC) See note 4 below
IO17 IO17 (NC) See note 4 below
IO5 Reset_N IO5
IO18 MDIO
IO19 TXD[0]
IO21 TX_EN
RXD0 RXD
TXD0 TXD
IO22 TXD[1]
IO23 MDC

Note:
1. GPIO2 is used to enable external oscillator of the PHY.
2. GPIO0 is a source of 50 MHz reference clock for the PHY. The clock signal is first inverted, to account for
transmission line delay, and then supplied to the PHY.
3. To prevent affecting the power-on state of GPIO0 by the clock output on the PHY side, the PHY external
oscillator is enabled using GPIO2 after ESP32 is powered up.
4. The ESP32 pins GPIO16 and GPIO17 are not broken out to the ESP32-WROVER-B module and therefore
not available for use. If you need to use these pins, please solder a module without SPIRAM memory inside,
e.g., the ESP32-WROOM-32D or ESP32-SOLO-1.

Start Application Development Before powering up your ESP32-Ethernet-Kit, please make sure that the board
is in good condition with no obvious signs of damage.

Espressif Systems 60 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Initial Setup
1. Set the Function Switch on the Ethernet board (A) to its default position by turning all the switches to ON.
2. To simplify flashing and testing the application, do not install any jumpers and do not connect any signals to
the board headers.
3. The PoE board (B) can now be plugged in, but do not connect external power to it.
4. Connect the Ethernet board (A) to the PC with a USB cable.
5. Turn the Power Switch from GND to 5V0 position, the 5V Power On LED should light up.

Now to Development Proceed to Get Started, where Section Installation will quickly help you set up the develop-
ment environment and then flash an example project onto your board.
To use the older GNU Make compilation system, please refer to Installation section.
Move on to the next section only if you have successfully completed all the above steps.

Configure and Load the Ethernet Example After setting up the development environment and testing the board,
you can configure and flash the ethernet/basic example. This example has been created for testing Ethernet function-
ality. It supports different PHY, including IP101GRI installed on ESP32-Ethernet-Kit V1.0 board.

Related Documents
• ESP32-Ethernet-Kit V1.0 Ethernet board (A) schematic (PDF)
• ESP32-Ethernet-Kit V1.0 PoE board (B) schematic (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROVER-B Datasheet (PDF)
• JTAG Debugging
• Hardware Reference
For other design documentation for the board, please contact us at [email protected].

ESP32-Ethernet-Kit V1.1 Getting Started Guide


This guide shows how to get started with the ESP32-Ethernet-Kit development board and also provides information
about its functionality and configuration options.
The ESP32-Ethernet-Kit is an Ethernet-to-Wi-Fi development board that enables Ethernet devices to be intercon-
nected over Wi-Fi. At the same time, to provide more flexible power supply options, the ESP32-Ethernet-Kit also
supports power over Ethernet (PoE).

What You Need


• ESP32-Ethernet-Kit V1.1 board
• USB 2.0 A to Micro B Cable
• Computer running Windows, Linux, or macOS
You can skip the introduction sections and go directly to Section Start Application Development.

Overview ESP32-Ethernet-Kit is an ESP32-based development board produced by Espressif.


It consists of two development boards, the Ethernet board A and the PoE board B. The Ethernet board (A) con-
tains Bluetooth®/Wi-Fi dual-mode ESP32-WROVER-B module and IP101GRI, a Single Port 10/100 Fast Ethernet
Transceiver (PHY). The PoE board (B) provides power over Ethernet functionality. The A board can work indepen-
dently, without the board B installed.
For the application loading and monitoring, the Ethernet board (A) also features FTDI FT2232H chip - an advanced
multi-interface USB bridge. This chip enables to use JTAG for direct debugging of ESP32 through the USB interface
without a separate JTAG debugger.

Espressif Systems 61 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 32: ESP32-Ethernet-Kit V1.1

Espressif Systems 62 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Functionality Overview The block diagram below shows the main components of ESP32-Ethernet-Kit and their
interconnections.

Fig. 33: ESP32-Ethernet-Kit block diagram (click to enlarge)

Functional Description The following figures and tables describe the key components, interfaces, and controls of
the ESP32-Ethernet-Kit.

Ethernet Board (A) The table below provides description starting from the picture’s top right corner and going
clockwise.

Espressif Systems 63 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 34: ESP32-Ethernet-Kit - Ethernet board (A) layout (click to enlarge)

Table 3: Table 1 Component Description


Key Component Description
ESP32-WROVER- This ESP32 module features 64-Mbit PSRAM for flexible extended storage and data
B processing capabilities.
GPIO Header 2 Five unpopulated through-hole solder pads to provide access to selected GPIOs of ESP32.
For details, see GPIO Header 2.
Function Switch A 4-bit DIP switch used to configure the functionality of selected GPIOs of ESP32.
Please note that placement of GPIO pin number marking on the board’s silkscreen
besides the DIP switch is incorrect. For details and correct pin allocation see Function
Switch.
Tx/Rx LEDs Two LEDs to show the status of UART transmission.
FT2232H The FT2232H chip serves as a multi-protocol USB-to-serial bridge which can be pro-
grammed and controlled via USB to provide communication with ESP32. FT2232H
also features USB-to-JTAG interface which is available on channel A of the chip, while
USB-to-serial is on channel B. The FT2232H chip enhances user-friendliness in terms of
application development and debugging. See ESP32-Ethernet-Kit V1.1 Ethernet board
(A) schematic.
USB Port USB interface. Power supply for the board as well as the communication interface be-
tween a computer and the board.
Power Switch Power On/Off Switch. Toggling the switch to 5V0 position powers the board on, toggling
to GND position powers the board off.
5V Input The 5 V power supply interface can be more convenient when the board is operating
autonomously (not connected to a computer).
5V Power On LED This red LED turns on when power is supplied to the board, either from USB or 5 V
Input.
DC/DC Converter Provided DC 5 V to 3.3 V conversion, output current up to 2 A.
Board B Connectors A pair male and female header pins for mounting the PoE board (B).
IP101GRI (PHY) The physical layer (PHY) connection to the Ethernet cable is implemented using the
IP101GRI chip. The connection between PHY and ESP32 is done through the reduced
media-independent interface (RMII), a variant of the media-independent interface (MII)
standard. The PHY supports the IEEE 802.3/802.3u standard of 10/100 Mbps.
RJ45 Port Ethernet network data transmission port.
Espressif
MagneticsSystems
Module 64
The Magnetics are part of the Ethernet specification toRelease
protect v5.2-dev-3065-g272b4091f1
against faults and transients,
Submit Document Feedback
including rejection of common mode signals between the transceiver IC and the cable.
The magnetics also provide galvanic isolation between the transceiver and the Ethernet
device.
Chapter 1. Get Started

PoE Board (B) This board coverts power delivered over the Ethernet cable (PoE) to provide a power supply for the
Ethernet board (A). The main components of the PoE board (B) are shown on the block diagram under Functionality
Overview.
The PoE board (B) has the following features:
• Support for IEEE 802.3at
• Power output: 5 V, 1.4 A
To take advantage of the PoE functionality the RJ45 Port of the Ethernet board (A) should be connected with an
Ethernet cable to a switch that supports PoE. When the Ethernet board (A) detects 5 V power output from the PoE
board (B), the USB power will be automatically cut off.

Fig. 35: ESP32-Ethernet-Kit - PoE board (B) layout (click to enlarge)

Table 4: Table PoE board (B)


Key Component Description
Board A Connector Four female (left) and four male (right) header pins for connecting the PoE board (B) to
Ethernet board (A). The pins on the left accept power coming from a PoE switch. The
pins on the right deliver 5 V power supply to the Ethernet board (A).
External Power Ter- Optional power supply (26.6 ~ 54 V) to the PoE board (B).
minals

Setup Options This section describes options to configure the ESP32-Ethernet-Kit hardware.

Function Switch When in On position, this DIP switch is routing listed GPIOs to FT2232H to provide JTAG
functionality. When in Off position, the GPIOs may be used for other purposes.

DIP SW GPIO Pin


1 GPIO13
2 GPIO12
3 GPIO15
4 GPIO14

Note: Placement of GPIO pin number marking on the board’s silkscreen besides the DIP switch is incorrect.
Please use instead the pin order as in the table above.

RMII Clock Selection The ethernet MAC and PHY under RMII working mode need a common 50 MHz reference
clock (i.e., RMII clock) that can be provided either externally, or generated from internal ESP32 APLL.

Note: For additional information on the RMII clock selection, please refer to ESP32-Ethernet-Kit V1.1 Ethernet
board (A) schematic, sheet 2, location D2.

Espressif Systems 65 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

RMII Clock Sourced Externally by PHY By default, the ESP32-Ethernet-Kit is configured to provide RMII
clock for the IP101GRI PHY’s 50M_CLKO output. The clock signal is generated by the frequency multiplication
of 25 MHz crystal connected to the PHY. For details, please see the figure below.

Fig. 36: RMII Clock from IP101GRI PHY

Please note that the PHY is reset on power up by pulling the RESET_N signal down with a resistor. ESP32 should
assert RESET_N high with GPIO5 to enable PHY. Only this can ensure the power-up of system. Otherwise ESP32
may enter download mode (when the clock signal of REF_CLK_50M is at a high logic level during the GPIO0
power-up sampling phase).

RMII Clock Sourced Internally from ESP32’s APLL Another option is to source the RMII Clock from internal
ESP32 APLL, see figure below. The clock signal coming from GPIO0 is first inverted, to account for transmission
line delay, and then supplied to the PHY.
To implement this option, users need to remove or add some RC components on the board. For details please refer
to ESP32-Ethernet-Kit V1.1 Ethernet board (A) schematic, sheet 2, location D2. Please note that if the APLL is
already used for other purposes (e.g., I2S peripheral), then you have no choice but use an external RMII clock.

GPIO Allocation This section describes allocation of ESP32 GPIOs to specific interfaces or functions of the
ESP32-Ethernet-Kit.

Espressif Systems 66 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 37: RMII Clock from ESP Internal APLL

Espressif Systems 67 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

IP101GRI (PHY) Interface The allocation of the ESP32 (MAC) pins to IP101GRI (PHY) is shown in the table
below. Implementation of ESP32-Ethernet-Kit defaults to Reduced Media-Independent Interface (RMII).

. ESP32 Pin (MAC) IP101GRI (PHY)


RMII Interface
1 GPIO21 TX_EN
2 GPIO19 TXD[0]
3 GPIO22 TXD[1]
4 GPIO25 RXD[0]
5 GPIO26 RXD[1]
6 GPIO27 CRS_DV
7 GPIO0 REF_CLK
Serial Management Interface
8 GPIO23 MDC
9 GPIO18 MDIO
PHY Reset
10 GPIO5 Reset_N

Note: Except for REF_CLK, the allocation of all pins under the ESP32’s RMII Interface is fixed and cannot be
changed either through IOMUX or GPIO Matrix.

GPIO Header 1 This header exposes some GPIOs that are not used elsewhere on the ESP32-Ethernet-Kit.

. ESP32 Pin
1 GPIO32
2 GPIO33
3 GPIO34
4 GPIO35
5 GPIO36
6 GPIO39

GPIO Header 2 This header contains GPIOs that may be used for other purposes depending on scenarios described
in column “Comments”.

. ESP32 Pin Comments


1 GPIO17 See note 1
2 GPIO16 See note 1
3 GPIO4
4 GPIO2
5 GPIO13 See note 2
6 GPIO12 See note 2
7 GPIO15 See note 2
8 GPIO14 See note 2
9 GND Ground
10 3V3 3.3 V power supply

Note:
1. The ESP32 pins GPIO16 and GPIO17 are not broken out to the ESP32-WROVER-B module and therefore
not available for use. If you need to use these pins, please solder a module without PSRAM memory inside,
e.g., the ESP32-WROOM-32D or ESP32-SOLO-1.
2. Functionality depends on the settings of the Function Switch.

Espressif Systems 68 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

GPIO Allocation Summary

ESP32-WROVER-B IP101GRI UART JTAG GPIO Comments


S_VP IO36
S_VN IO39
IO34 IO34
IO35 IO35
IO32 IO32
IO33 IO33
IO25 RXD[0]
IO26 RXD[1]
IO27 CRS_DV
IO14 TMS IO14
IO12 TDI IO12
IO13 RTS TCK IO13
IO15 CTS TDO IO15
IO2 IO2
IO0 REF_CLK See note 1
IO4 IO4
IO16 IO16 (NC) See note 2
IO17 IO17 (NC) See note 2
IO5 Reset_N See note 1
IO18 MDIO
IO19 TXD[0]
IO21 TX_EN
RXD0 RXD
TXD0 TXD
IO22 TXD[1]
IO23 MDC

Note:
1. To prevent the power-on state of the GPIO0 from being affected by the clock output on the PHY side, the
RESET_N signal to PHY defaults to low, turning the clock output off. After power-on you can control RE-
SET_N with GPIO5 to turn the clock output on. See also RMII Clock Sourced Externally by PHY. For PHYs
that cannot turn off the clock output through RESET_N, it is recommended to use a crystal module that can be
disabled/enabled externally. Similarly like when using RESET_N, the oscillator module should be disabled by
default and turned on by ESP32 after power-up. For a reference design please see ESP32-Ethernet-Kit V1.1
Ethernet board (A) schematic.
2. The ESP32 pins GPIO16 and GPIO17 are not broken out to the ESP32-WROVER-B module and therefore
not available for use. If you need to use these pins, please solder a module without PSRAM memory inside,
e.g., the ESP32-WROOM-32D or ESP32-SOLO-1.

Start Application Development Before powering up your ESP32-Ethernet-Kit, please make sure that the board
is in good condition with no obvious signs of damage.

Initial Setup
1. Set the Function Switch on the Ethernet board (A) to its default position by turning all the switches to ON.
2. To simplify flashing and testing of the application, do not input extra signals to the board headers.
3. The PoE board (B) can now be plugged in, but do not connect external power to it.
4. Connect the Ethernet board (A) to the PC with a USB cable.

Espressif Systems 69 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

5. Turn the Power Switch from GND to 5V0 position, the 5V Power On LED should light up.

Now to Development Proceed to Get Started, where Section Installation will quickly help you set up the develop-
ment environment and then flash an example project onto your board.
Move on to the next section only if you have successfully completed all the above steps.

Configure and Load the Ethernet Example After setting up the development environment and testing the board,
you can configure and flash the ethernet/basic example. This example has been created for testing Ethernet function-
ality. It supports different PHY, including IP101GRI installed on ESP32-Ethernet-Kit V1.1.

Summary of Changes from ESP32-Ethernet-Kit V1.0


• The original inverted clock provided to the PHY by ESP32 using GPIO0 has been replaced by a clock generated
on PHY side. The PHY’s clock is connected to the ESP32 with same GPIO0. The GPIO2 which was originally
used to control the active crystal oscillator on the PHY side, can now be used for other purposes.
• On power up, the ESP32 boot strapping pin GPIO0 may be affected by clock generated on the PHY side. To
resolve this issue the PHY’s Reset-N signal is pulled low using resistor R17 and effectively turning off the
PHY’s clock output. The Reset-N signal can be then pulled high by ESP32 using GPIO5.
• Removed FT2232H chip’s external SPI Flash U6.
• Removed flow control jumper header J4.
• Removed nTRST JTAG signal. The corresponding GPIO4 can now be used for other purposes.
• Pull-up resistor R68 on the GPIO15 line is moved to the MTDO side of JTAG.
• To make the A and B board connections more foolproof (reduce chances of plugging in the B board in reverse
orientation), the original two 4-pin male rows on board A were changed to one 4-pin female row and one 4-pin
male row. Corresponding male and female 4-pins rows were installed on board B.

Other Versions of ESP32-Ethernet-Kit


• ESP32-Ethernet-Kit V1.0 Getting Started Guide

Related Documents
• ESP32-Ethernet-Kit V1.1 Ethernet board (A) schematic (PDF)
• ESP32-Ethernet-Kit V1.0 PoE board (B) schematic (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROVER-B Datasheet (PDF)
• JTAG Debugging
• Hardware Reference
For other design documentation for the board, please contact us at [email protected].

ESP32-DevKitS(-R)

This user guide provides information on ESP32-DevKitS(-R), an ESP32-based flashing board produced by Espressif.
ESP32-DevKitS(-R) is a combination of two board names: ESP32-DevKitS and ESP32-DevKitS-R. S stands for
springs, and R stands for WROVER.

Espressif Systems 70 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

ESP32-DevKitS ESP32-DevKitS-R

The document consists of the following major sections:


• Getting Started: Provides an overview of ESP32-DevKitS(-R) and hardware/software setup instructions to get
started.
• Hardware Reference: Provides more detailed information about ESP32-DevKitS(-R)’s hardware.
• Related Documents: Gives links to related documentation.

Getting Started This section describes how to get started with ESP32-DevKitS(-R). It begins with a few introduc-
tory sections about ESP32-DevKitS(-R), then Section How to Flash a Board provides instructions on how to mount
a module onto ESP32-DevKitS(-R), get it ready, and flash firmware onto it.

Overview ESP32-DevKitS(-R) is Espressif’s flashing board designed specifically for ESP32. It can be used to
flash an ESP32 module without soldering the module to the power supply and signal lines. With a module mounted,
ESP32-DevKitS(-R) can also be used as a mini development board like ESP32-DevKitC.
ESP32-DevKitS and ESP32-DevKitS-R boards vary only in layout of spring pins to fit the following ESP32 modules.
• ESP32-DevKitS:
– ESP32-WROOM-32
– ESP32-WROOM-32D
– ESP32-WROOM-32U
– ESP32-SOLO-1
– ESP32-WROOM-32E
– ESP32-WROOM-32UE
• ESP32-DevKitS-R:
– ESP32-WROVER (PCB & IPEX)
– ESP32-WROVER-B (PCB & IPEX)
– ESP32-WROVER-E
– ESP32-WROVER-IE
For information about above modules, please refer to ESP32 Series Modules.

Description of Components

Espressif Systems 71 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 38: ESP32-DevKitS - front

Fig. 39: ESP32-DevKitS-R - front

Espressif Systems 72 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Key Component Description


Spring Pins Click the module in. The pins will fit into the module’s castellated holes.
2.54 mm Female Headers These female headers are connected to pins of the module mounted on this
board. For description of female headers, please refer to Header Blocks.
USB-to-UART Bridge Single-chip USB to UART bridge provides transfer rates of up to 3 Mbps.
LDO 5V-to-3.3V low-dropout voltage regulator (LDO).
Micro-USB Connector/Micro USB interface. Power supply for the board as well as the communication in-
USB Port terface between a computer and the board.
EN Button Reset button.
Boot Button Download button. Holding down Boot and then pressing EN initiates
Firmware Download mode for downloading firmware through the serial port.
Power On LED Turns on when the USB or power supply is connected to the board.

How to Flash a Board Before powering up your ESP32-DevKitS(-R), please make sure that it is in good condition
with no obvious signs of damage.

Required Hardware
• An ESP32 module of your choice
• USB 2.0 cable (Standard-A to Micro-B)
• Computer running Windows, Linux, or macOS

Hardware Setup Please mount a module of your choice onto your ESP32-DevKitS(-R) according to the following
steps:
• Gently put your module on the ESP32-DevKitS(-R) board. Make sure that castellated holes on your module
are aligned with spring pins on the board.
• Press your module down into the board until it clicks.
• Check whether all spring pins are inserted into castellated holes. If there are some misaligned spring pins,
place them into castellated holes with tweezers.

Software Setup

Preferred Method The ESP-IDF development framework provides a preferred way of flashing binaries onto
ESP32-DevKitS(-R). Please proceed to Get Started, where Section Installation will quickly help you set up the de-
velopment environment and then flash an application example onto your ESP32-DevKitS(-R).

Alternative Method As an alternative, Windows users can flash binaries using the Flash Download Tool. Just
download it, unzip it, and follow the instructions inside the doc folder.

Note:
1. To flash binary files, ESP32 should be set to Firmware Download mode. This can be done either
by the flash tool automatically, or by holding down the Boot button and tapping the EN button.
2. After flashing binary files, the Flash Download Tool restarts your ESP32 module and boots the
flashed application by default.

Board Dimensions

Contents and Packaging

Espressif Systems 73 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 40: ESP32-DevKitS board dimensions - back

Fig. 41: ESP32-DevKitS-R board dimensions - back

Espressif Systems 74 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Retail Orders If you order a few samples, each ESP32-DevKitS(-R) comes in an individual package in either
antistatic bag or any packaging depending on a retailer.
For retail orders, please go to https://www.espressif.com/en/contact-us/get-samples.

Wholesale Orders If you order in bulk, the boards come in large cardboard boxes.
For wholesale orders, please go to https://www.espressif.com/en/contact-us/sales-questions.

Hardware Reference

Block Diagram A block diagram below shows the components of ESP32-DevKitS(-R) and their interconnections.

Fig. 42: ESP32-DevKitS(-R) (click to enlarge)

Power Supply Options There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V and GND header pins
• 3V3 and GND header pins
It is advised to use the first option: micro USB port.

. Label Signal
L1 3V3 VDD 3V3
L2 EN CHIP_PU
L3 VP SENSOR_VP
L4 VN SENSOR_VN
L5 34 GPIO34
L6 35 GPIO35
L7 32 GPIO32
L8 33 GPIO33
continues on next page

Espressif Systems 75 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Table 5 – continued from previous page


. Label Signal
L9 25 GPIO25
L10 26 GPIO26
L11 27 GPIO27
L12 14 GPIO14
L13 12 GPIO12
L14 GND GND
L15 13 GPIO13
L16 D2 SD_DATA2
L17 D3 SD_DATA3
L18 CMD SD_CMD
L19 5V External 5V
R1 GND GND
R2 23 GPIO23
R3 22 GPIO22
R4 TX U0TXD
R5 RX U0RXD
R6 21 GPIO21
R7 GND GND
R8 19 GPIO19
R9 18 GPIO18
R10 5 GPIO5
R11 17 GPIO17
R12 16 GPIO16
R13 4 GPIO4
R14 0 GPIO0
R15 2 GPIO2
R16 15 GPIO15
R17 D1 SD_DATA1
R18 D0 SD_DATA0
R19 CLK SD_CLK

Header Blocks For the image of header blocks, please refer to Description of Components.

Related Documents
• ESP32-DevKitS(-R) Schematics (PDF)
• ESP32 Datasheet (PDF)
• ESP32-WROOM-32 Datasheet (PDF)
• ESP32-WROOM-32D & ESP32-WROOM-32U Datasheet (PDF)
• ESP32-SOLO-1 Datasheet (PDF)
• ESP32-WROVER Datasheet (PDF)
• ESP32-WROVER-B Datasheet (PDF)
• ESP Product Selector

ESP32-PICO-KIT-1

Overview ESP32-PICO-KIT-1 is an ESP32-based development board produced by Espressif.


The core of this board is ESP32-PICO-V3 - a System-in-Package (SiP) module with complete Wi-Fi and Bluetooth®
functionalities. Compared to other ESP32 modules, ESP32-PICO-V3 integrates the following peripheral components
in one single package, which otherwise would need to be installed separately:

Espressif Systems 76 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

• 40 MHz crystal oscillator


• 4 MB flash
• Filter capacitors
• RF matching network
This setup reduces the costs of additional external components as well as the cost of assembly and testing and also
increases the overall usability of the product.
The development board features a USB-to-UART Bridge circuit which allows developers to connect the board to a
computer’s USB port for flashing and debugging.
All the IO signals and system power on ESP32-PICO-V3 are led out to two rows of 18 x 0.1”header pads on both
sides of the development board for easy access. For compatibility with Dupont wires, all header pads are populated
with two rows of male pin headers.

Note: ESP32-PICO-KIT-1 comes with male headers by default.

ESP32-PICO-KIT-1 provides the users with hardware for development of applications based on the ESP32, making
it easier for users to explore ESP32 functionalities.
This guide covers:
• Getting Started: Provides an overview of the ESP32-PICO-KIT-1 and software setup instructions to get started.
• Contents and Packaging: Provides information about packaging and contents for retail and wholesale orders.
• Hardware Reference: Provides more detailed information about the ESP32-PICO-KIT-1’s hardware.
• Hardware Revision Details: Covers revision history, known issues, and links to user guides for previous versions
of the ESP32-PICO-KIT-1.
• Related Documents: Gives links to related documentation.

Getting Started This section describes how to get started with the ESP32-PICO-KIT-1. It begins with a few
introductory sections about the ESP32-PICO-KIT-1, then Section Start Application Development provides instructions
on how to flash firmware onto the ESP32-PICO-KIT-1.

Description of Components The following figure and the table below describe the key components, interfaces,
and controls of the ESP32-PICO-KIT-1 board.
Below is the description of the items identified in the figure starting from the top left corner and going clockwise.

Key Component Description


ESP32-PICO-V3 Standard ESP32-PICO-V3 module soldered to the ESP32-PICO-KIT-1 board.
The complete ESP32 system on a chip (ESP32 SoC) has been integrated into
the SiP module, requiring only an external antenna with LC matching network,
decoupling capacitors, and a pull-up resistor for EN signals to function properly.
LDO 5V-to-3.3V Low dropout voltage regulator (LDO).
USB-to-UART bridge CP2102N, single-chip USB-to-UART bridge that offers up to 3 Mbps transfers
rates.
Micro USB Port USB interface. Power supply for the board as well as the communication inter-
face between a computer and the board.
5V Power On LED This red LED turns on when power is supplied to the board. For details, see the
schematic in Related Documents.
I/O Connector All the pins on ESP32-PICO-V3 are broken out to pin headers. You can program
ESP32 to enable multiple functions, such as PWM, ADC, DAC, I2C, I2S, SPI,
etc. For details, please see Section Pin Descriptions.
BOOT Button Download button. Holding down Boot and then pressing EN initiates Firmware
Download mode for downloading firmware through the serial port.
EN Button Reset button.

Espressif Systems 77 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 43: ESP32-PICO-KIT-1 Overview (click to enlarge)

Espressif Systems 78 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 44: ESP32-PICO-KIT-1 board layout - front (click to enlarge)

Start Application Development Before powering up your ESP32-PICO-KIT-1, please make sure that the board
is in good condition with no obvious signs of damage.

Required Hardware
• 1 x ESP32-PICO-KIT-1
• 1 x USB 2.0 A to Micro B cable
• 1 x Computer running Windows, Linux, or macOS

Software Setup Please proceed to Get Started, where Section Installation will quickly help you set up the develop-
ment environment.

Contents and Packaging

Retail Orders If you order one or several samples of the board, each ESP32-PICO-KIT-1 development board
comes in an individual package.
For retail orders, please go to https://www.espressif.com/en/contact-us/get-samples.

Wholesale Orders If you order in bulk, the boards come in large cardboard boxes.
For wholesale orders, please go to https://www.espressif.com/en/contact-us/sales-questions.

Hardware Reference

Block Diagram The block diagram below shows the main components of ESP32-PICO-KIT-1 and their intercon-
nections.

Power Supply Options There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V/GND header pins
• 3V3/GND header pins

Espressif Systems 79 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 45: ESP32-PICO-KIT-1 Block Diagram (click to enlarge)

Warning: The power supply must be provided using one and only one of the options above, otherwise the
board and/or the power supply source can be damaged.

Pin Descriptions The two tables below provide the Name and Function of I/O header pins on both sides of the
board, see Description of Components. The pin numbering and header names are the same as in the schematic given
in Related Documents.

Header J2

No. Name Type Function


1 IO20 I/O GPIO20
2 IO21 I/O GPIO21, VSPIHD, EMAC_TX_EN
3 IO22 I/O GPIO22, VSPIWP, U0RTS, EMAC_TXD1
4 IO19 I/O GPIO19, VSPIQ, U0CTS, EMAC_TXD0
5 IO8 I/O GPIO8, SD_DATA1, HS1_DATA1, U2CTS
6 IO7 I/O GPIO7, SD_DATA0, HS1_DATA0, U2RTS
7 IO5 I/O GPIO5, VSPICS0, HS1_DATA6, EMAC_RX_CLK
8 IO10 I/O GPIO10, SD_DATA3, SPIWP, HS1_DATA3, U1TXD
9 IO9 I/O GPIO9, SD_DATA2, SPIHD, HS1_DATA2, U1RXD
10 RXD0 I/O GPIO3, U0RXD (See 1), CLK_OUT2
11 TXD0 I/O GPIO1, U0TXD (See 1), CLK_OUT3, EMAC_RXD2
12 IO35 I ADC1_CH7, RTC_GPIO5
13 IO34 I ADC1_CH6, RTC_GPIO4
14 IO38 I GPIO38, ADC1_CH2, RTC_GPIO2
15 IO37 I GPIO37, ADC1_CH1, RTC_GPIO1
16 EN I CHIP_PU
17 GND P Ground
18 VDD33 P 3.3 V power supply
(3V3)

Espressif Systems 80 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Header J3

No. Name Type Function


1 GND P Ground
2 SEN- I GPIO36, ADC1_CH0, RTC_GPIO0
SOR_VP
(FSVP)
3 SEN- I GPIO39, ADC1_CH3, RTC_GPIO3
SOR_VN
(FSVN)
4 IO25 I/O GPIO25, DAC_1, ADC2_CH8, RTC_GPIO6, EMAC_RXD0
5 IO26 I/O GPIO26, DAC_2, ADC2_CH9, RTC_GPIO7, EMAC_RXD1
6 IO32 I/O 32K_XP (See 2a), ADC1_CH4, TOUCH9, RTC_GPIO9
7 IO33 I/O 32K_XN (See 2b), ADC1_CH5, TOUCH8, RTC_GPIO8
8 IO27 I/O GPIO27, ADC2_CH7, TOUCH7, RTC_GPIO17, EMAC_RX_DV
9 IO14 I/O ADC2_CH6, TOUCH6, RTC_GPIO16, MTMS, HSPICLK, HS2_CLK,
SD_CLK, EMAC_TXD2
10 IO12 I/O ADC2_CH5, TOUCH5, RTC_GPIO15, MTDI (See 3), HSPIQ,
HS2_DATA2, SD_DATA2, EMAC_TXD3
11 IO13 I/O ADC2_CH4, TOUCH4, RTC_GPIO14, MTCK, HSPID, HS2_DATA3,
SD_DATA3, EMAC_RX_ER
12 IO15 I/O ADC2_CH3, TOUCH3, RTC_GPIO13, MTDO, HSPICS0, HS2_CMD,
SD_CMD, EMAC_RXD3
13 IO2 I/O ADC2_CH2, TOUCH2, RTC_GPIO12, HSPIWP, HS2_DATA0,
SD_DATA0
14 IO4 I/O ADC2_CH0, TOUCH0, RTC_GPIO10, HSPIHD, HS2_DATA1,
SD_DATA1, EMAC_TX_ER
15 IO0 I/O ADC2_CH1, TOUCH1, RTC_GPIO11, CLK_OUT1, EMAC_TX_CLK
16 VDD33 P 3.3V power supply
(3V3)
17 GND P Ground
18 EXT_5V P 5V power supply
(5V)

Note:
1. This pin is connected to the pin of the USB bridge chip on the board.
2. 32.768 kHz crystal oscillator: a) input b) output
3. The operating voltage of ESP32-PICO-KIT-1’s embedded SPI flash is 3.3 V. Therefore, the strapping pin
MTDI should be pulled down during the module power-on reset. If connected, please make sure that this pin
is not held up on reset.

Pin Layout

Hardware Revision Details No previous versions available.

Related Documents
• ESP32-PICO-V3 Datasheet (PDF)
• ESP Product Selector
• ESP32-PICO-KIT-1 Schematic (PDF)
• ESP32-PICO-KIT-1 PCB Layout (PDF)
For other design documentation for the board, please contact us at [email protected].

Espressif Systems 81 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 46: ESP32-PICO-KIT-1 Pin Layout(click to enlarge)

ESP32-PICO-DevKitM-2

Overview ESP32-PICO-DevKitM-2 is an ESP32-based development board produced by Espressif.


The core of this board is ESP32-PICO-MINI-02(02U) module with complete Wi-Fi and Bluetooth® functionalities.
The development board features a USB-to-UART Bridge circuit which allows developers to connect the board to a
computer’s USB port for flashing and debugging.
All the IO signals and system power on ESP32-PICO-MINI-02(02U) are led out to two rows of 18 x 0.1”header
pads on both sides of the development board for easy access. For compatibility with Dupont wires, all header pads
are populated with two rows of male pin headers.

Note: ESP32-PICO-DevKitM-2 comes with male headers by default.

ESP32-PICO-DevKitM-2 provides the users with hardware for development of applications based on the ESP32,
making it easier for users to explore ESP32 functionalities.
This guide covers:
• Getting Started: Provides an overview of the ESP32-PICO-DevKitM-2 and software setup instructions to get
started.
• Contents and Packaging: Provides information about packaging and contents for retail and wholesale orders.
• Hardware Reference: Provides more detailed information about the ESP32-PICO-DevKitM-2’s hardware.
• Hardware Revision Details: Covers revision history, known issues, and links to user guides for previous versions
(if any) of the ESP32-PICO-DevKitM-2.
• Related Documents: Gives links to related documentation.

Getting Started This section describes how to get started with the ESP32-PICO-DevKitM-2. It begins with a
few introductory sections about the ESP32-PICO-DevKitM-2, then Section Start Application Development provides
instructions on how to flash firmware onto the ESP32-PICO-DevKitM-2.

Espressif Systems 82 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 47: ESP32-PICO-DevKitM-2 Overview (click to enlarge)

Espressif Systems 83 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Description of Components The following figure and the table below describe the key components, interfaces,
and controls of the ESP32-PICO-DevKitM-2 board. We take the board with a ESP32-PICO-MINI-02 module as an
example in the following sections.

Fig. 48: ESP32-PICO-DevKitM-2 board layout - front (click to enlarge)

Below is the description of the items identified in the figure starting from the top left corner and going clockwise.

Key Component Description


ESP32-PICO-MINI-02 Standard ESP32-PICO-MINI-02 module soldered to the ESP32-PICO-
DevKitM-2 board. The complete ESP32 system on a chip (ESP32 SoC) has
been integrated into the module. Users can also select the board with ESP32-
PICO-MINI-02U soldered.
LDO V-to-3.3V Low dropout voltage regulator (LDO).
USB-to-UART bridge CP2102N, single-chip USB-UART bridge that offers up to 3 Mbps transfers
rates.
Micro-B USB Port USB interface. Power supply for the board as well as the communication inter-
face between a computer and the board.
5V Power On LED This red LED turns on when power is supplied to the board. For details, see the
schematic in Related Documents.
I/O Connector All the pins on ESP32-PICO-MINI-02 are broken out to pin headers. You can
program ESP32 to enable multiple functions, such as PWM, ADC, DAC, I2C,
I2S, SPI, etc. For details, please see Section Pin Descriptions.
BOOT Button Download button. Holding down Boot and then pressing EN initiates Firmware
Download mode for downloading firmware through the serial port.
EN Button Reset button.

Start Application Development Before powering up your ESP32-PICO-DevKitM-2, please make sure that the
board is in good condition with no obvious signs of damage.

Required Hardware
• 1 x ESP32-PICO-DevKitM-2
• 1 x USB 2.0 A to Micro B cable
• 1 x Computer running Windows, Linux, or macOS

Espressif Systems 84 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Software Setup Please proceed to Get Started, where Section Installation will quickly help you set up the develop-
ment environment.

Contents and Packaging

Retail Orders If you order one or several samples of the board, each ESP32-PICO-DevKitM-2 development board
comes in an individual package.
For retail orders, please go to https://www.espressif.com/en/contact-us/get-samples.

Wholesale Orders If you order in bulk, the boards come in large cardboard boxes.
For wholesale orders, please go to https://www.espressif.com/en/contact-us/sales-questions.

Hardware Reference

Block Diagram The block diagram below shows the main components of ESP32-PICO-DevKitM-2 and their
interconnections.

Fig. 49: ESP32-PICO-DevKitM-2 Block Diagram (click to enlarge)

Power Supply Options There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V/GND header pins
• 3V3/GND header pins

Warning: The power supply must be provided using one and only one of the options above, otherwise the
board and/or the power supply source can be damaged.

Pin Descriptions The two tables below provide the Name and Function of I/O header pins on both sides of the
board, see Description of Components. The pin numbering and header names are the same as in the schematic given
in Related Documents.

Espressif Systems 85 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Header J2

No. Name Type Function


1 IO20 I/O GPIO20
2 IO21 I/O GPIO21, VSPIHD, EMAC_TX_EN
3 IO22 I/O GPIO22, VSPIWP, U0RTS, EMAC_TXD1
4 IO19 I/O GPIO19, VSPIQ, U0CTS, EMAC_TXD0
5 IO8 I/O GPIO8, SD_DATA1, HS1_DATA1, U2CTS
6 IO7 I/O GPIO7, SD_DATA0, HS1_DATA0, U2RTS
7 IO5 I/O GPIO5, VSPICS0, HS1_DATA6, EMAC_RX_CLK
8 NC - NC
9 NC - NC
10 RXD0 I/O GPIO3, U0RXD (See 1), CLK_OUT2
11 TXD0 I/O GPIO1, U0TXD (See 1), CLK_OUT3, EMAC_RXD2
12 IO35 I ADC1_CH7, RTC_GPIO5
13 IO34 I ADC1_CH6, RTC_GPIO4
14 IO38 I GPIO38, ADC1_CH2, RTC_GPIO2
15 IO37 I GPIO37, ADC1_CH1, RTC_GPIO1
16 EN I CHIP_PU
17 GND P Ground
18 VDD33 P 3.3 V power supply
(3V3)

Header J3

No. Name Type Function


1 GND P Ground
2 SEN- I GPIO36, ADC1_CH0, RTC_GPIO0
SOR_VP
(FSVP)
3 SEN- I GPIO39, ADC1_CH3, RTC_GPIO3
SOR_VN
(FSVN)
4 IO25 I/O GPIO25, DAC_1, ADC2_CH8, RTC_GPIO6, EMAC_RXD0
5 IO26 I/O GPIO26, DAC_2, ADC2_CH9, RTC_GPIO7, EMAC_RXD1
6 IO32 I/O 32K_XP (See 2a), ADC1_CH4, TOUCH9, RTC_GPIO9
7 IO33 I/O 32K_XN (See 2b), ADC1_CH5, TOUCH8, RTC_GPIO8
8 IO27 I/O GPIO27, ADC2_CH7, TOUCH7, RTC_GPIO17, EMAC_RX_DV
9 IO14 I/O ADC2_CH6, TOUCH6, RTC_GPIO16, MTMS, HSPICLK, HS2_CLK,
SD_CLK, EMAC_TXD2
10 IO12 I/O ADC2_CH5, TOUCH5, RTC_GPIO15, MTDI (See 3), HSPIQ,
HS2_DATA2, SD_DATA2, EMAC_TXD3
11 IO13 I/O ADC2_CH4, TOUCH4, RTC_GPIO14, MTCK, HSPID, HS2_DATA3,
SD_DATA3, EMAC_RX_ER
12 IO15 I/O ADC2_CH3, TOUCH3, RTC_GPIO13, MTDO, HSPICS0, HS2_CMD,
SD_CMD, EMAC_RXD3
13 IO2 I/O ADC2_CH2, TOUCH2, RTC_GPIO12, HSPIWP, HS2_DATA0,
SD_DATA0
14 IO4 I/O ADC2_CH0, TOUCH0, RTC_GPIO10, HSPIHD, HS2_DATA1,
SD_DATA1, EMAC_TX_ER
15 IO0 I/O ADC2_CH1, TOUCH1, RTC_GPIO11, CLK_OUT1, EMAC_TX_CLK
16 VDD33 P 3.3V power supply
(3V3)
17 GND P Ground
18 EXT_5V P 5V power supply
(5V)

Espressif Systems 86 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Note:
1. This pin is connected to the pin of the USB bridge chip on the board.
2. 32.768 kHz crystal oscillator: a) input b) output
3. The operating voltage of ESP32-PICO-DevKitM-2’s embedded SPI flash is 3.3 V. Therefore, the strapping
pin MTDI should be pulled down during the module power-on reset. If connected, please make sure that this
pin is not held up on reset.

Fig. 50: ESP32-PICO-DevKitM-2 Pin Layout (click to enlarge)

Pin Layout

Hardware Revision Details No previous versions available.

Related Documents
• ESP32-PICO-MINI-02 & ESP32-PICO-MINI-1U Datasheet (PDF)
• ESP Product Selector
• ESP32-PICO-DevKitM-2 Schematic (PDF)
• ESP32-PICO-DevKitM-2 PCB Layout (PDF)
For other design documentation for the board, please contact us at [email protected].

ESP32-DevKitM-1

This user guide will help you get started with ESP32-DevKitM-1 and will also provide more in-depth information.
ESP32-DevKitM-1 is an ESP32-MINI-1(1U)-based development board produced by Espressif. Most of the I/O pins
are broken out to the pin headers on both sides for easy interfacing. Users can either connect peripherals with jumper
wires or mount ESP32-DevKitM-1 on a breadboard.

Espressif Systems 87 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

ESP32-DevKitM-1 - front ESP32-DevKitM-1 - isometric

The document consists of the following major sections:


• Getting started: Provides an overview of the ESP32-DevKitM-1 and hardware/software setup instructions to
get started.
• Hardware reference: Provides more detailed information about the ESP32-DevKitM-1’s hardware.
• Related Documents: Gives links to related documentaiton.

Getting Started This section describes how to get started with ESP32-DevKitM-1. It begins with a few introduc-
tory sections about the ESP32-DevKitM-1, then Section Start Application Development provides instructions on how
to do the initial hardware setup and then how to flash firmware onto the ESP32-DevKitM-1.

Overview This is a small and convenient development board that features:


• ESP32-MINI-1, or ESP32-MINI-1U module
• USB-to-serial programming interface that also provides power supply for the board
• pin headers
• pushbuttons for reset and activation of Firmware Download mode
• a few other components

Contents and Packaging

Retail Orders If you order a few samples, each ESP32-DevKitM-1 comes in an individual package in either anti-
static bag or any packaging depending on your retailer.
For retail orders, please go to https://www.espressif.com/en/contact-us/get-samples.

Wholesale Orders If you order in bulk, the boards come in large cardboard boxes.
For wholesale orders, please go to https://www.espressif.com/en/contact-us/sales-questions.

Description of Components The following figure and the table below describe the key components, interfaces and
controls of the ESP32-DevKitM-1 board. We take the board with a ESP32-MINI-1 module as an example in the
following sections.

Espressif Systems 88 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 51: ESP32-DevKitM-1 - front

Key Component Description


On-board module ESP32-MINI-1 module or ESP32-MINI-1U module. ESP32-MINI-1 comes with an
on-board PCB antenna. ESP32-MINI-1U comes with an external antenna connector.
The two modules both have a 4 MB flash in chip package. For details, please see
ESP32-MINI-1 & ESP32-MINI-1U Datasheet.
5 V to 3.3 V LDO Power regulator converts 5 V to 3.3 V.
Boot Button Download button. Holding down Boot and then pressing Reset initiates Firmware
Download mode for downloading firmware through the serial port.
Reset Button Reset Button
Micro-USB Port USB interface. Power supply for the board as well as the communication interface
between a computer and the ESP32 chip.
USB-to-UART Bridge Single USB-UART bridge chip provides transfer rates up to 3 Mbps.
3.3 V Power On LED Turns on when the USB is connected to the board. For details, please see the
schematics in Related Documents.
I/O Connector All available GPIO pins (except for the SPI bus for flash) are broken out to the pin
headers on the board. Users can program ESP32 chip to enable multiple functions.

Start Application Development Before powering up your ESP32-DevKitM-1, please make sure that it is in good
condition with no obvious signs of damage.

Required Hardware
• ESP32-DevKitM-1
• USB 2.0 cable (Standard-A to Micro-B)
• Computer running Windows, Linux, or macOS

Software Setup Please proceed to Get Started, where Section Installation will quickly help you set up the develop-
ment environment and then flash an application example onto your ESP32-DevKitM-1.

Espressif Systems 89 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Attention: ESP32-DevKitM-1 boards manufactured before December 2, 2021 have a single core module in-
stalled. To verify what module you have, please check module marking information in PCN-2021-021 . If your
board has a single core module installed, please enable single core mode (CONFIG_FREERTOS_UNICORE) in
menuconfig before flashing your applications.

Hardware Reference

Block Diagram A block diagram below shows the components of ESP32-DevKitM-1 and their interconnections.

Fig. 52: ESP32-DevKitM-1

Power Source Select There are three mutually exclusive ways to provide power to the board:
• Micro USB port, default power supply
• 5V and GND header pins
• 3V3 and GND header pins

Warning:
• The power supply must be provided using one and only one of the options above, otherwise the board
and/or the power supply source can be damaged.
• Power supply by micro USB port is recommended.

Pin Descriptions The table below provides the Name and Function of pins on both sides of the board. For pe-
ripheral pin configurations, please refer to ESP32 Datasheet.

No. Name TypePage 91, 1 Function


1 GND P Ground
2 3V3 P 3.3 V power supply
continues on next page

Espressif Systems 90 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Table 6 – continued from previous page


No. Name TypePage 91, 1 Function
3 I36 I GPIO36, ADC1_CH0, RTC_GPIO0
4 I37 I GPIO37, ADC1_CH1, RTC_GPIO1
5 I38 I GPIO38, ADC1_CH2, RTC_GPIO2
6 I39 I GPIO39, ADC1_CH3, RTC_GPIO3
7 RST I Reset; High: enable; Low: powers off
8 I34 I GPIO34, ADC1_CH6, RTC_GPIO4
9 I35 I GPIO35, ADC1_CH7, RTC_GPIO5
10 IO32 I/O GPIO32, XTAL_32K_P (32.768 kHz crystal oscillator input),
ADC1_CH4, TOUCH9, RTC_GPIO9
11 IO33 I/O GPIO33, XTAL_32K_N (32.768 kHz crystal oscillator output),
ADC1_CH5, TOUCH8, RTC_GPIO8
12 IO25 I/O GPIO25, DAC_1, ADC2_CH8, RTC_GPIO6, EMAC_RXD0
13 IO26 I/O GPIO26, DAC_2, ADC2_CH9, RTC_GPIO7, EMAC_RXD1
14 IO27 I/O GPIO27, ADC2_CH7, TOUCH7, RTC_GPIO17, EMAC_RX_DV
15 IO14 I/O GPIO14, ADC2_CH6, TOUCH6, RTC_GPIO16, MTMS, HSPICLK,
HS2_CLK, SD_CLK, EMAC_TXD2
16 5V P 5 V power supply
17 IO12 I/O GPIO12, ADC2_CH5, TOUCH5, RTC_GPIO15, MTDI2 , HSPIQ,
HS2_DATA2, SD_DATA2, EMAC_TXD3
18 IO13 I/O GPIO13, ADC2_CH4, TOUCH4, RTC_GPIO14, MTCK, HSPID,
HS2_DATA3, SD_DATA3, EMAC_RX_ER
19 IO15 I/O GPIO15, ADC2_CH3, TOUCH3, RTC_GPIO13, MTDOPage 91, 2 ,
HSPICS0, HS2_CMD, SD_CMD, EMAC_RXD3
20 IO2 I/O GPIO2Page 91, 2 , ADC2_CH2, TOUCH2, RTC_GPIO12, HSPIWP,
HS2_DATA0, SD_DATA0
21 IO0 I/O GPIO0Page 91, 2 , ADC2_CH1, TOUCH1, RTC_GPIO11, CLK_OUT1,
EMAC_TX_CLK
22 IO4 I/O GPIO4, ADC2_CH0, TOUCH0, RTC_GPIO10, HSPIHD,
HS2_DATA1, SD_DATA1, EMAC_TX_ER
23 IO9 I/O GPIO9, HS1_DATA2, U1RXD, SD_DATA2
24 IO10 I/O GPIO10, HS1_DATA3, U1TXD, SD_DATA3
25 IO5 I/O GPIO5Page 91, 2 , HS1_DATA6, VSPICS0, EMAC_RX_CLK
26 IO18 I/O GPIO18, HS1_DATA7, VSPICLK
27 IO23 I/O GPIO23, HS1_STROBE, VSPID
28 IO19 I/O GPIO19, VSPIQ, U0CTS, EMAC_TXD0
29 IO22 I/O GPIO22, VSPIWP, U0RTS, EMAC_TXD1
30 IO21 I/O GPIO21, VSPIHD, EMAC_TX_EN
31 TXD0 I/O GPIO1, U0TXD, CLK_OUT3, EMAC_RXD2
32 RXD0 I/O GPIO3, U0RXD, CLK_OUT2

Pin Layout

Hardware Revision Details No previous versions available.

Related Documents
• ESP32-MINI-1 & ESP32-MINI-1U Datasheet (PDF)
• ESP32-DevKitM-1 Schematics (PDF)
• ESP32-DevKitM-1 PCB layout (PDF)
1 P: Power supply; I: Input; O: Output.
2 MTDI, GPIO0, GPIO2, MTDO, and GPIO5 are strapping pins. These pins are used to control several chip functions depending on binary
voltage values applied to the pins during chip power-up or system reset. For description and application of the strapping pins, please refer to
ESP32 Datasheet > Section Strapping Pins.

Espressif Systems 91 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 53: ESP32-DevKitM-1 (click to enlarge)

• ESP32-DevKitM-1 layout (DXF) - You can view it with Autodesk Viewer online
• ESP32 Datasheet (PDF)
• ESP Product Selector
For other design documentation for the board, please contact us at [email protected].

1.2.2 Software

To start using ESP-IDF on ESP32, install the following software:


• Toolchain to compile code for ESP32
• Build tools - CMake and Ninja to build a full Application for ESP32
• ESP-IDF that essentially contains API (software libraries and source code) for ESP32 and scripts to operate
the Toolchain

Espressif Systems 92 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

1.3 Installation
To install all the required software, we offer some different ways to facilitate this task. Choose from one of the
available options.

1.3.1 IDE

Note: We highly recommend installing the ESP-IDF through your favorite IDE.

• Eclipse Plugin
• VSCode Extension

1.3.2 Manual Installation

For the manual procedure, please select according to your operating system.

Standard Setup of Toolchain for Windows

Introduction ESP-IDF requires some prerequisite tools to be installed so you can build firmware for supported
chips. The prerequisite tools include Python, Git, cross-compilers, CMake and Ninja build tools.
For this Getting Started we are going to use the Command Prompt, but after ESP-IDF is installed you can use Eclipse
Plugin or another graphical IDE with CMake support instead.

Note: Limitations: - The installation path of ESP-IDF and ESP-IDF Tools must not be longer than 90 characters.
Too long installation paths might result in a failed build. - The installation path of Python or ESP-IDF must not contain
white spaces or parentheses. - The installation path of Python or ESP-IDF should not contain special characters (non-
ASCII) unless the operating system is configured with “Unicode UTF-8”support.
System Administrator can enable the support via Control Panel > Change date, time, or number formats
> Administrative tab > Change system locale > check the option Beta: Use Unicode UTF-8
for worldwide language support > Ok > reboot the computer.

ESP-IDF Tools Installer The easiest way to install ESP-IDF’s prerequisites is to download one of ESP-IDF
Tools Installers.

Windows Installer Download

Espressif Systems 93 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

What Is the Usecase for Online and Offline Installer Online Installer is very small and allows the installation of
all available releases of ESP-IDF. The installer downloads only necessary dependencies including Git For Windows
during the installation process. The installer stores downloaded files in the cache directory %userprofile%\.
espressif
Offline Installer does not require any network connection. The installer contains all required dependencies including
Git For Windows .

Components of the Installation The installer deploys the following components:


• Embedded Python
• Cross-compilers
• OpenOCD
• CMake and Ninja build tools
• ESP-IDF
The installer also allows reusing the existing directory with ESP-IDF. The recommended directory is %userpro-
file%\Desktop\esp-idf where %userprofile% is your home directory.

Launching ESP-IDF Environment At the end of the installation process you can check out option Run
ESP-IDF PowerShell Environment or Run ESP-IDF Command Prompt (cmd.exe). The
installer launches ESP-IDF environment in selected prompt.
Run ESP-IDF PowerShell Environment:

Fig. 54: Completing the ESP-IDF Tools Setup Wizard with Run ESP-IDF PowerShell Environment

Run ESP-IDF Command Prompt (cmd.exe):

Espressif Systems 94 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 55: ESP-IDF PowerShell

Fig. 56: Completing the ESP-IDF Tools Setup Wizard with Run ESP-IDF Command Prompt (cmd.exe)

Espressif Systems 95 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 57: ESP-IDF Command Prompt

Espressif Systems 96 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Using the Command Prompt For the remaining Getting Started steps, we are going to use the Windows Command
Prompt.
ESP-IDF Tools Installer also creates a shortcut in the Start menu to launch the ESP-IDF Command Prompt. This
shortcut launches the Command Prompt (cmd.exe) and runs export.bat script to set up the environment variables
(PATH, IDF_PATH and others). Inside this command prompt, all the installed tools are available.
Note that this shortcut is specific to the ESP-IDF directory selected in the ESP-IDF Tools Installer. If you have
multiple ESP-IDF directories on the computer (for example, to work with different versions of ESP-IDF), you have
two options to use them:
1. Create a copy of the shortcut created by the ESP-IDF Tools Installer, and change the working directory of the
new shortcut to the ESP-IDF directory you wish to use.
2. Alternatively, run cmd.exe, then change to the ESP-IDF directory you wish to use, and run export.bat.
Note that unlike the previous option, this way requires Python and Git to be present in PATH. If you get errors
related to Python or Git not being found, use the first option.

First Steps on ESP-IDF Now since all requirements are met, the next topic guides you on how to start your first
project.
This guide helps you on the first steps using ESP-IDF. Follow this guide to start a new project on the ESP32 and
build, flash, and monitor the device output.

Note: If you have not yet installed ESP-IDF, please go to Installation and follow the instruction in order to get all
the software needed to use this guide.

Start a Project Now you are ready to prepare your application for ESP32. You can start with get-
started/hello_world project from examples directory in ESP-IDF.

Important: The ESP-IDF build system does not support spaces in the paths to either ESP-IDF or to projects.

Copy the project get-started/hello_world to ~/esp directory:

cd %userprofile%\esp
xcopy /e /i %IDF_PATH%\examples\get-started\hello_world hello_world

Note: There is a range of example projects in the examples directory in ESP-IDF. You can copy any project in the
same way as presented above and run it. It is also possible to build examples in-place without copying them first.

Connect Your Device Now connect your ESP32 board to the computer and check under which serial port the
board is visible.
Serial port names start with COM in Windows.
If you are not sure how to check the serial port name, please refer to Establish Serial Connection with ESP32 for full
details.

Note: Keep the port name handy as it is needed in the next steps.

Configure Your Project Navigate to your hello_world directory, set ESP32 as the target, and run the project
configuration utility menuconfig.

Espressif Systems 97 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Windows
cd %userprofile%\esp\hello_world
idf.py set-target esp32
idf.py menuconfig

After opening a new project, you should first set the target with idf.py set-target esp32. Note that existing
builds and configurations in the project, if any, are cleared and initialized in this process. The target may be saved in
the environment variable to skip this step at all. See Select the Target Chip: set-target for additional information.
If the previous steps have been done correctly, the following menu appears:

Fig. 58: Project configuration - Home window

You are using this menu to set up project specific variables, e.g., Wi-Fi network name and password, the processor
speed, etc. Setting up the project with menuconfig may be skipped for “hello_word”, since this example runs with
default configuration.

Attention: If you use ESP32-DevKitC board with the ESP32-SOLO-1 module, or ESP32-DevKitM-1 board
with the ESP32-MIN1-1(1U) module, please enable single core mode (CONFIG_FREERTOS_UNICORE) in
menuconfig before flashing examples.

Note: The colors of the menu could be different in your terminal. You can change the appearance with the option
--style. Please run idf.py menuconfig --help for further information.

If you are using one of the supported development boards, you can speed up your development by using Board Support
Package. See Additional Tips for more information.

Build the Project Build the project by running:

idf.py build

This command compiles the application and all ESP-IDF components, then it generates the bootloader, partition
table, and application binaries.

Espressif Systems 98 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

$ idf.py build
Running cmake in directory /path/to/hello_world/build
Executing "cmake -G Ninja --warn-uninitialized /path/to/hello_world"...
Warn about uninitialized values.
-- Found Git: /usr/bin/git (found version "2.17.0")
-- Building empty aws_iot component due to configuration
-- Component names: ...
-- Component paths: ...

... (more lines of build system output)

[527/527] Generating hello_world.bin


esptool.py v2.3.1

Project build complete. To flash, run this command:


../../../components/esptool_py/esptool/esptool.py -p (PORT) -b 921600 write_flash -
,→-flash_mode dio --flash_size detect --flash_freq 40m 0x10000 build/hello_world.

,→bin build 0x1000 build/bootloader/bootloader.bin 0x8000 build/partition_table/


,→partition-table.bin

or run 'idf.py -p PORT flash'

If there are no errors, the build finishes by generating the firmware binary .bin files.

Flash onto the Device To flash the binaries that you just built for the ESP32 in the previous step, you need to run
the following command:
idf.py -p PORT flash

Replace PORT with your ESP32 board’s USB port name. If the PORT is not defined, the idf.py will try to connect
automatically using the available USB ports.
For more information on idf.py arguments, see idf.py.

Note: The option flash automatically builds and flashes the project, so running idf.py build is not necessary.

Encountered Issues While Flashing? See this Flashing Troubleshooting page or Establish Serial Connection with ESP32
for more detailed information.

Normal Operation When flashing, you will see the output log similar to the following:
...
esptool.py --chip esp32 -p /dev/ttyUSB0 -b 460800 --before=default_reset --
,→after=hard_reset write_flash --flash_mode dio --flash_freq 40m --flash_size 2MB␣

,→0x8000 partition_table/partition-table.bin 0x1000 bootloader/bootloader.bin␣

,→0x10000 hello_world.bin

esptool.py v3.0-dev
Serial port /dev/ttyUSB0
Connecting........_
Chip is ESP32D0WDQ6 (revision 0)
Features: WiFi, BT, Dual Core, Coding Scheme None
Crystal is 40MHz
MAC: 24:0a:c4:05:b9:14
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Compressed 3072 bytes to 103...
(continues on next page)

Espressif Systems 99 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

(continued from previous page)


Writing at 0x00008000... (100 %)
Wrote 3072 bytes (103 compressed) at 0x00008000 in 0.0 seconds (effective 5962.8␣
,→kbit/s)...

Hash of data verified.


Compressed 26096 bytes to 15408...
Writing at 0x00001000... (100 %)
Wrote 26096 bytes (15408 compressed) at 0x00001000 in 0.4 seconds (effective 546.7␣
,→kbit/s)...

Hash of data verified.


Compressed 147104 bytes to 77364...
Writing at 0x00010000... (20 %)
Writing at 0x00014000... (40 %)
Writing at 0x00018000... (60 %)
Writing at 0x0001c000... (80 %)
Writing at 0x00020000... (100 %)
Wrote 147104 bytes (77364 compressed) at 0x00010000 in 1.9 seconds (effective 615.
,→5 kbit/s)...

Hash of data verified.

Leaving...
Hard resetting via RTS pin...
Done

If there are no issues by the end of the flash process, the board will reboot and start up the“hello_world”application.
If you would like to use the Eclipse or VS Code IDE instead of running idf.py, check out Eclipse Plugin, VSCode
Extension.

Monitor the Output To check if “hello_world”is indeed running, type idf.py -p PORT monitor (Do
not forget to replace PORT with your serial port name).
This command launches the IDF Monitor application:
$ idf.py -p <PORT> monitor
Running idf_monitor in directory [...]/esp/hello_world/build
Executing "python [...]/esp-idf/tools/idf_monitor.py -b 115200 [...]/esp/hello_
,→world/build/hello_world.elf"...

--- idf_monitor on <PORT> 115200 ---


--- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
ets Jun 8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)


ets Jun 8 2016 00:22:57
...

After startup and diagnostic logs scroll up, you should see “Hello world!”printed out by the application.
...
Hello world!
Restarting in 10 seconds...
This is esp32 chip with 2 CPU core(s), WiFi/BT/BLE, silicon revision 1, 2 MB␣
,→external flash

Minimum free heap size: 298968 bytes


Restarting in 9 seconds...
Restarting in 8 seconds...
Restarting in 7 seconds...

To exit IDF monitor use the shortcut Ctrl+].


If IDF monitor fails shortly after the upload, or, if instead of the messages above, you see random garbage similar to
what is given below, your board is likely using a 26 MHz crystal. Most development board designs use 40 MHz, so
ESP-IDF uses this frequency as a default value.

Espressif Systems 100 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

If you have such a problem, do the following:


1. Exit the monitor.
2. Go back to menuconfig.
3. Go to Component config –> Hardware Settings –> Main XTAL Config –> Main XTAL
frequency, then change CONFIG_XTAL_FREQ_SEL to 26 MHz.
4. After that, build and flash the application again.
In the current version of ESP-IDF, main XTAL frequencies supported by ESP32 are as follows:

• 26 MHz
• 40 MHz

Note: You can combine building, flashing and monitoring into one step by running:

idf.py -p PORT flash monitor

See also:
• IDF Monitor for handy shortcuts and more details on using IDF monitor.
• idf.py for a full reference of idf.py commands and options.
That is all that you need to get started with ESP32!
Now you are ready to try some other examples, or go straight to developing your own applications.

Important: Some of examples do not support ESP32 because required hardware is not included in ESP32 so it
cannot be supported.
If building an example, please check the README file for the Supported Targets table. If this is present
including ESP32 target, or the table does not exist at all, the example will work on ESP32.

Additional Tips

Permission Issues /dev/ttyUSB0 With some Linux distributions, you may get the Failed to open port
/dev/ttyUSB0 error message when flashing the ESP32. This can be solved by adding the current user to the dialout
group.

Python Compatibility ESP-IDF supports Python 3.8 or newer. It is recommended to upgrade your operating
system to a recent version satisfying this requirement. Other options include the installation of Python from sources
or the use of a Python version management system such as pyenv.

Start with Board Support Package To speed up prototyping on some development boards, you can use Board
Support Packages (BSPs), which makes initialization of a particular board as easy as few function calls.
A BSP typically supports all of the hardware components provided on development board. Apart from the pinout
definition and initialization functions, a BSP ships with drivers for the external components such as sensors, displays,
audio codecs etc.
The BSPs are distributed via IDF Component Manager, so they can be found in IDF Component Registry.

Espressif Systems 101 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Here is an example of how to add ESP-WROVER-KIT BSP to your project:

idf.py add-dependency esp_wrover_kit

More examples of BSP usage can be found in BSP examples folder.

Flash Erase Erasing the flash is also possible. To erase the entire flash memory you can run the following command:

idf.py -p PORT erase-flash

For erasing the OTA data, if present, you can run this command:

idf.py -p PORT erase-otadata

The flash erase command can take a while to be done. Do not disconnect your device while the flash erasing is in
progress.

Related Documents For advanced users who want to customize the install process:
• Updating ESP-IDF Tools on Windows
• Establish Serial Connection with ESP32
• Eclipse Plugin
• VSCode Extension
• IDF Monitor

Updating ESP-IDF Tools on Windows

Install ESP-IDF Tools Using a Script From the Windows Command Prompt, change to the directory where
ESP-IDF is installed. Then run:

install.bat

For Powershell, change to the directory where ESP-IDF is installed. Then run:

install.ps1

This downloads and installs the tools necessary to use ESP-IDF. If the specific version of the tool is already installed,
no action will be taken. The tools are downloaded and installed into a directory specified during ESP-IDF Tools
Installer process. By default, this is C:\Users\username\.espressif.

Add ESP-IDF Tools to PATH Using an Export Script ESP-IDF tools installer creates a Start menu shortcut for
“ESP-IDF Command Prompt”. This shortcut opens a Command Prompt window where all the tools are already
available.
In some cases, you may want to work with ESP-IDF in a Command Prompt window which was not started using that
shortcut. If this is the case, follow the instructions below to add ESP-IDF tools to PATH.
In the command prompt where you need to use ESP-IDF, change to the directory where ESP-IDF is installed, then
execute export.bat:

cd %userprofile%\esp\esp-idf
export.bat

Alternatively in the Powershell where you need to use ESP-IDF, change to the directory where ESP-IDF is installed,
then execute export.ps1:

cd ~/esp/esp-idf
export.ps1

Espressif Systems 102 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

When this is done, the tools will be available in this command prompt.

Establish Serial Connection with ESP32


Establishing a serial connection with the ESP32 target device could be done using a USB-to-UART bridge.
Some development boards have the USB-to-UART bridge installed. If a board does not have a bridge then an external
bridge may be used.

USB-to-UART Bridge on Development Board For boards with an installed USB-to-UART bridge, the connection
between the personal computer and the bridge is USB and between the bridge and ESP32 is UART.

Fig. 59: Development Board with USB-to-UART Bridge

External USB-to-UART Bridge Sometimes the USB-to-UART bridge is external. This is often used in small
development boards or finished products when space and costs are crucial.

Fig. 60: External USB-to-UART Bridge

Flash Using UART This section provides guidance on how to establish a serial connection between ESP32 and
PC using USB-to-UART Bridge, either installed on the development board or external.

Connect ESP32 to PC Connect the ESP32 board to the PC using the USB cable. If device driver does not install
automatically, identify USB-to-UART bridge on your ESP32 board (or external converter dongle), search for drivers
in internet and install them.
Below is the list of USB to serial converter chips installed on most of the ESP32 boards produced by Espressif together
with links to the drivers:

Espressif Systems 103 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

• CP210x: CP210x USB to UART Bridge VCP Drivers


• FTDI: FTDI Virtual COM Port Drivers
Please check the board user guide for specific USB-to-UART bridge chip used. The drivers above are primarily for
reference. Under normal circumstances, the drivers should be bundled with an operating system and automatically
installed upon connecting the board to the PC.
For devices downloaded using a USB-to-UART bridge, you can run the following command including the optional
argument to define the baud rate.

idf.py -p PORT [-b BAUD] flash

You can change the flasher baud rate by replacing BAUD with the baud rate you need. The default baud rate is
460800.

Note: If the device does not support the auto download mode, you need to get into the download mode manually. To
do so, press and hold the BOOT button and then press the RESET button once. After that release the BOOT button.

Check Port on Windows Check the list of identified COM ports in the Windows Device Manager. Disconnect
ESP32 and connect it back, to verify which port disappears from the list and then shows back again.
Figures below show serial port for ESP32 DevKitC and ESP32 WROVER KIT

Fig. 61: USB to UART bridge of ESP32-DevKitC in Windows Device Manager

Check Port on Linux and macOS To check the device name for the serial port of your ESP32 board (or external
converter dongle), run this command two times, first with the board/dongle unplugged, then with plugged in. The
port which appears the second time is the one you need:

Espressif Systems 104 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 62: Two USB Serial Ports of ESP-WROVER-KIT in Windows Device Manager

Espressif Systems 105 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Linux

ls /dev/tty*

macOS

ls /dev/cu.*

Note: macOS users: if you do not see the serial port then check you have the USB/serial drivers installed. See
Section Connect ESP32 to PC for links to drivers. For macOS High Sierra (10.13), you may also have to explicitly
allow the drivers to load. Open System Preferences -> Security & Privacy -> General and check if there is a message
shown here about “System Software from developer …”where the developer name is Silicon Labs or FTDI.

Adding User to dialout on Linux The currently logged user should have read and write access the serial port
over USB. On most Linux distributions, this is done by adding the user to dialout group with the following
command:

sudo usermod -a -G dialout $USER

on Arch Linux this is done by adding the user to uucp group with the following command:

sudo usermod -a -G uucp $USER

Make sure you re-login to enable read and write permissions for the serial port.

Verify Serial Connection Now verify that the serial connection is operational. You can do this using a serial
terminal program by checking if you get any output on the terminal after resetting ESP32.
The default console baud rate on ESP32 is 115200.

Windows and Linux In this example, we use PuTTY SSH Client that is available for both Windows and Linux.
You can use other serial programs and set communication parameters like below.
Run terminal and set identified serial port. Baud rate = 115200 (if needed, change this to the default baud rate of the
chip in use), data bits = 8, stop bits = 1, and parity = N. Below are example screenshots of setting the port and such
transmission parameters (in short described as 115200-8-1-N) on Windows and Linux. Remember to select exactly
the same serial port you have identified in steps above.
Then open serial port in terminal and check, if you see any log printed out by ESP32. The log contents depend on
application loaded to ESP32, see Example Output. Reset the board if no log has been printed out.

Note: Close the serial terminal after verification that communication is working. If you keep the terminal session
open, the serial port will be inaccessible for uploading firmware later.

Note: If there is no log output, check


• if the required power is supplied to ESP32
• if the board was reset after starting the terminal program
• if the selected serial port is the correct one by using the method stated in Check Port on Windows and Check
Port on Linux and macOS
• if the serial port is not being used by another program
• if the identified port has been selected in serial terminal programs you are using, as stated in Windows and
Linux
• if settings of the serial port in serial terminal programs are applicable to corresponding applications
• if the correct USB connector (UART) is used on the development board

Espressif Systems 106 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 63: Setting Serial Communication in PuTTY on Windows

Espressif Systems 107 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Fig. 64: Setting Serial Communication in PuTTY on Linux

Espressif Systems 108 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

• if your application is expected to output some log


• if the log output has not been disabled (use hello world application to test)

macOS To spare you the trouble of installing a serial terminal program, macOS offers the screen command.
• As discussed in Check port on Linux and macOS, run:

ls /dev/cu.*

• You should see similar output:

/dev/cu.Bluetooth-Incoming-Port /dev/cu.SLAB_USBtoUART /dev/cu.SLAB_


,→USBtoUART7

• The output varies depending on the type and the number of boards connected to your PC. Then pick the device
name of your board and run (if needed, change “115200”to the default baud rate of the chip in use):

screen /dev/cu.device_name 115200

Replace device_name with the name found running ls /dev/cu.*.


• What you are looking for is some log displayed by the screen. The log contents depend on application loaded
to ESP32, see Example Output. To exit the screen session type Ctrl-A + \ .

Note: Do not forget to exit the screen session after verifying that the communication is working. If you fail to do
it and just close the terminal window, the serial port will be inaccessible for uploading firmware later.

Example Output An example log is shown below. Reset the board if you do not see anything.

ets Jun 8 2016 00:22:57

rst:0x5 (DEEPSLEEP_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)


ets Jun 8 2016 00:22:57

rst:0x7 (TG0WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)


configsip: 0, SPIWP:0x00
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0008,len:8
load:0x3fff0010,len:3464
load:0x40078000,len:7828
load:0x40080000,len:252
entry 0x40080034
I (44) boot: ESP-IDF v2.0-rc1-401-gf9fba35 2nd stage bootloader
I (45) boot: compile time 18:48:10
...

If you can see readable log output, it means serial connection is working and you are ready to proceed with installation
and finally upload an application to ESP32.

Note: For some serial port wiring configurations, the serial RTS & DTR pins need to be disabled in the terminal
program before the ESP32 booting and producing serial output. This depends on the hardware itself, most develop-
ment boards (including all Espressif boards) do not have this issue. The issue is present if RTS & DTR are wired
directly to the EN & GPIO0 pins. See the esptool documentation for more details.

If you got here from Step 5. First Steps on ESP-IDF when installing s/w for ESP32 development, then you can continue
with Step 5. First Steps on ESP-IDF.

Espressif Systems 109 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Flashing Troubleshooting

Failed to Connect If you run the given command and see errors such as “Failed to connect”, there might be
several reasons for this. One of the reasons might be issues encountered by esptool.py, the utility that is called
by the build system to reset the chip, interact with the ROM bootloader, and flash firmware. One simple solution to
try is to manually reset as described below. If it does not help, you can find more details about possible issues in the
esptool troubleshooting page.
esptool.py resets ESP32 automatically by asserting DTR and RTS control lines of the USB-to-UART bridge,
i.e., FTDI or CP210x (for more information, see Establish Serial Connection with ESP32). The DTR and RTS control
lines are in turn connected to GPIO0 and CHIP_PU (EN) pins of ESP32, thus changes in the voltage levels of DTR
and RTS will boot ESP32 into Firmware Download mode. As an example, check the schematic for the ESP32
DevKitC development board.
In general, you should have no problems with the official esp-idf development boards. However, esptool.py is
not able to reset your hardware automatically in the following cases:
• Your hardware does not have the DTR and RTS lines connected to GPIO0 and CHIP_PU.
• The DTR and RTS lines are configured differently.
• There are no such serial control lines at all.
Depending on the kind of hardware you have, it may also be possible to manually put your ESP32 board into Firmware
Download mode (reset).
• For development boards produced by Espressif, this information can be found in the respective getting started
guides or user guides. For example, to manually reset an ESP-IDF development board, hold down the Boot
button (GPIO0) and press the EN button (CHIP_PU).
• For other types of hardware, try pulling GPIO0 down.

IDF Monitor
IDF Monitor uses the esp-idf-monitor package as a serial terminal program which relays serial data to and from the
target device’s serial port. It also provides some ESP-IDF-specific features.
IDF Monitor can be launched from an ESP-IDF project by running idf.py monitor.

Keyboard Shortcuts For easy interaction with IDF Monitor, use the keyboard shortcuts given in the table.

Espressif Systems 110 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Keyboard Action Description


Shortcut
Ctrl + ] Exit the program
Ctrl + T Menu escape key Press and follow it by one of the keys given below.
Send the menu character it-
• Ctrl + T
self to remote
Send the exit character it-
• Ctrl + ]
self to remote
Reset target into bootloader Resets the target, into bootloader via the RTS line (if connected),
• Ctrl + P
to pause app via RTS line so that the board runs nothing. Useful when you need to wait for
another device to startup.
Reset target board via RTS Resets the target board and re-starts the application via the RTS
• Ctrl + R
line (if connected).
Build and flash the project Pauses idf_monitor to run the project flash target, then re-
• Ctrl + F
sumes idf_monitor. Any changed source files are recompiled
and then re-flashed. Target encrypted-flash is run if
idf_monitor was started with argument -E.
Build and flash the app only Pauses idf_monitor to run the app-flash target, then resumes
• Ctrl + A
idf_monitor. Similar to the flash target, but only the main app
(or A)
is built and re-flashed. Target encrypted-app-flash is
run if idf_monitor was started with argument -E.
Stop/resume log output Discards all incoming serial data while activated. Allows to
• Ctrl + Y
printing on screen quickly pause and examine log output without quitting the mon-
itor.
Stop/resume log output Creates a file in the project directory and the output is written to
• Ctrl + L
saved to file that file until this is disabled with the same keyboard shortcut (or
IDF Monitor exits).
Stop/resume printing IDF Monitor can print a timestamp in the beginning of
• Ctrl + I
timestamps each line. The timestamp format can be changed by the
(or I)
--timestamp-format command line argument.
Display all keyboard short-
• Ctrl + H
cuts
(or H)

Exit the program


• Ctrl + X
(or X)

Ctrl + C Interrupt running applica- Pauses IDF Monitor and runs GDB project debug-
tion ger to debug the application at runtime. This requires
:ref:CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME option
to be enabled.

Any keys pressed, other than Ctrl-] and Ctrl-T, will be sent through the serial port.

ESP-IDF-specific Features

Automatic Address Decoding Whenever the chip outputs a hexadecimal address that points to executable code,
IDF monitor looks up the location in the source code (file name and line number) and prints the location on the next
line in yellow.

If an ESP-IDF app crashes and panics, a register dump and backtrace are produced, such as the following:

Espressif Systems 111 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Guru Meditation Error of type StoreProhibited occurred on core 0. Exception was␣


,→unhandled.

Register dump:
PC : 0x400f360d PS : 0x00060330 A0 : 0x800dbf56 A1 :␣
,→0x3ffb7e00

A2 : 0x3ffb136c A3 : 0x00000005 A4 : 0x00000000 A5 :␣


,→0x00000000

A6 : 0x00000000 A7 : 0x00000080 A8 : 0x00000000 A9 :␣


,→0x3ffb7dd0

A10 : 0x00000003 A11 : 0x00060f23 A12 : 0x00060f20 A13 :␣


,→0x3ffba6d0

A14 : 0x00000047 A15 : 0x0000000f SAR : 0x00000019 EXCCAUSE:␣


,→0x0000001d

EXCVADDR: 0x00000000 LBEG : 0x4000c46c LEND : 0x4000c477 LCOUNT :␣


,→0x00000000

Backtrace: 0x400f360d:0x3ffb7e00 0x400dbf56:0x3ffb7e20 0x400dbf5e:0x3ffb7e40␣


,→0x400dbf82:0x3ffb7e60 0x400d071d:0x3ffb7e90

IDF Monitor adds more details to the dump:

Guru Meditation Error of type StoreProhibited occurred on core 0. Exception was␣


,→unhandled.

Register dump:
PC : 0x400f360d PS : 0x00060330 A0 : 0x800dbf56 A1 :␣
,→0x3ffb7e00

0x400f360d: do_something_to_crash at /home/gus/esp/32/idf/examples/get-started/


,→hello_world/main/./hello_world_main.c:57

(inlined by) inner_dont_crash at /home/gus/esp/32/idf/examples/get-started/hello_


,→world/main/./hello_world_main.c:52

A2 : 0x3ffb136c A3 : 0x00000005 A4 : 0x00000000 A5 :␣


,→0x00000000

A6 : 0x00000000 A7 : 0x00000080 A8 : 0x00000000 A9 :␣


,→0x3ffb7dd0

A10 : 0x00000003 A11 : 0x00060f23 A12 : 0x00060f20 A13 :␣


,→0x3ffba6d0

A14 : 0x00000047 A15 : 0x0000000f SAR : 0x00000019 EXCCAUSE:␣


,→0x0000001d

EXCVADDR: 0x00000000 LBEG : 0x4000c46c LEND : 0x4000c477 LCOUNT :␣


,→0x00000000

Backtrace: 0x400f360d:0x3ffb7e00 0x400dbf56:0x3ffb7e20 0x400dbf5e:0x3ffb7e40␣


,→0x400dbf82:0x3ffb7e60 0x400d071d:0x3ffb7e90

0x400f360d: do_something_to_crash at /home/gus/esp/32/idf/examples/get-started/


,→hello_world/main/./hello_world_main.c:57

(inlined by) inner_dont_crash at /home/gus/esp/32/idf/examples/get-started/hello_


,→world/main/./hello_world_main.c:52

0x400dbf56: still_dont_crash at /home/gus/esp/32/idf/examples/get-started/hello_


,→world/main/./hello_world_main.c:47

0x400dbf5e: dont_crash at /home/gus/esp/32/idf/examples/get-started/hello_world/


,→main/./hello_world_main.c:42

0x400dbf82: app_main at /home/gus/esp/32/idf/examples/get-started/hello_world/main/


,→./hello_world_main.c:33

0x400d071d: main_task at /home/gus/esp/32/idf/components/esp32/./cpu_start.c:254

To decode each address, IDF Monitor runs the following command in the background:

xtensa-esp32-elf-addr2line -pfiaC -e build/PROJECT.elf ADDRESS

If an address is not matched in the app source code, IDF monitor also checks the ROM code. Instead of printing the
source file name and line number, only the function name followed by in ROM is displayed:

Espressif Systems 112 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

abort() was called at PC 0x40007c69 on core 0


0x40007c69: ets_write_char in ROM

Backtrace: 0x40081656:0x3ffb4ac0 0x40085729:0x3ffb4ae0 0x4008a7ce:0x3ffb4b00␣


,→0x40007c69:0x3ffb4b70 0x40008148:0x3ffb4b90 0x400d51d7:0x3ffb4c20␣

,→0x400e31bc:0x3ffb4c50 0x40087bc5:0x3ffb4c80

0x40081656: panic_abort at /Users/espressif/esp-idf/components/esp_system/panic.


,→c:452

0x40085729: esp_system_abort at /Users/espressif/esp-idf/components/esp_system/


,→port/esp_system_chip.c:90

0x4008a7ce: abort at /Users/espressif/esp-idf/components/newlib/abort.c:38


0x40007c69: ets_write_char in ROM
0x40008148: ets_printf in ROM
0x400d51d7: app_main at /Users/espressif/esp-idf/examples/get-started/hello_world/
,→main/hello_world_main.c:49

0x400e31bc: main_task at /Users/espressif/esp-idf/components/freertos/app_startup.


,→c:208 (discriminator 13)

0x40087bc5: vPortTaskWrapper at /Users/espressif/esp-idf/components/freertos/


,→FreeRTOS-Kernel/portable/xtensa/port.c:162

.....

The ROM ELF file is automatically loaded from a location based on the IDF_PATH and ESP_ROM_ELF_DIR
environment variables. This can be overridden by calling esp_idf_monitor and providing a path to a specific
ROM ELF file: python -m esp_idf_monitor --rom-elf-file [path to ROM ELF file].

Note: Set environment variable ESP_MONITOR_DECODE to 0 or call esp_idf_monitor with specific command line
option: python -m esp_idf_monitor --disable-address-decoding to disable address decoding.

Target Reset on Connection By default, IDF Monitor will reset the target when connecting to it. The reset of the
target chip is performed using the DTR and RTS serial lines. To prevent IDF Monitor from automatically resetting the
target on connection, call IDF Monitor with the --no-reset option (e.g., idf.py monitor --no-reset).

Note: The --no-reset option applies the same behavior even when connecting IDF Monitor to a particular port
(e.g., idf.py monitor --no-reset -p [PORT]).

Launching GDB with GDBStub GDBStub is a useful runtime debugging feature that runs on the target and
connects to the host over the serial port to receive debugging commands. GDBStub supports commands such as
reading memory and variables, examining call stack frames etc. Although GDBStub is less versatile than JTAG
debugging, it does not require any special hardware (such as a JTAG to USB bridge) as communication is done
entirely over the serial port.
A target can be configured to run GDBStub in the background by setting the CON-
FIG_ESP_SYSTEM_GDBSTUB_RUNTIME. GDBStub will run in the background until a Ctrl+C message is
sent over the serial port and causes the GDBStub to break (i.e., stop the execution of) the program, thus allowing
GDBStub to handle debugging commands.
Furthermore, the panic handler can be configured to run GDBStub on a crash by setting the CON-
FIG_ESP_SYSTEM_PANIC to GDBStub on panic. When a crash occurs, GDBStub will output a special string
pattern over the serial port to indicate that it is running.
In both cases (i.e., sending the Ctrl+C message, or receiving the special string pattern), IDF Monitor will automat-
ically launch GDB in order to allow the user to send debugging commands. After GDB exits, the target is reset via
the RTS serial line. If this line is not connected, users can reset their target (by pressing the board’s Reset button).

Note: In the background, IDF Monitor runs the following command to launch GDB:

Espressif Systems 113 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

xtensa-esp32-elf-gdb -ex "set serial baud BAUD" -ex "target remote PORT" -ex␣
,→interrupt build/PROJECT.elf :idf_target:`Hello NAME chip`

Output Filtering IDF monitor can be invoked as idf.py monitor --print-filter="xyz", where
--print-filter is the parameter for output filtering. The default value is an empty string, which means that
everything is printed.
Restrictions on what to print can be specified as a series of <tag>:<log_level> items where <tag> is the tag
string and <log_level> is a character from the set {N, E, W, I, D, V, *} referring to a level for logging.
For example, PRINT_FILTER="tag1:W" matches and prints only the outputs written with
ESP_LOGW("tag1", ...) or at lower verbosity level, i.e., ESP_LOGE("tag1", ...). Not speci-
fying a <log_level> or using * defaults to Verbose level.

Note: Use primary logging to disable at compilation the outputs you do not need through the logging library.
Output filtering with ESP- monitor is a secondary solution which can be useful for adjusting the filtering options
without recompiling the application.

Your app tags must not contain spaces, asterisks *, or colons : to be compatible with the output filtering feature.
If the last line of the output in your app is not followed by a carriage return, the output filtering might get confused, i.e.,
the monitor starts to print the line and later finds out that the line should not have been written. This is a known issue
and can be avoided by always adding a carriage return (especially when no output follows immediately afterwards).

Examples of Filtering Rules:


• * can be used to match any tags. However, the string PRINT_FILTER="*:I tag1:E" with regards to
tag1 prints errors only, because the rule for tag1 has a higher priority over the rule for *.
• The default (empty) rule is equivalent to *:V because matching every tag at the Verbose level or lower means
matching everything.
• "*:N" suppresses not only the outputs from logging functions, but also the prints made by printf, etc. To
avoid this, use *:E or a higher verbosity level.
• Rules "tag1:V", "tag1:v", "tag1:", "tag1:*", and "tag1" are equivalent.
• Rule "tag1:W tag1:E" is equivalent to "tag1:E" because any consequent occurrence of the same tag
name overwrites the previous one.
• Rule "tag1:I tag2:W" only prints tag1 at the Info verbosity level or lower and tag2 at the Warning
verbosity level or lower.
• Rule "tag1:I tag2:W tag3:N" is essentially equivalent to the previous one because tag3:N specifies
that tag3 should not be printed.
• tag3:N in the rule "tag1:I tag2:W tag3:N *:V" is more meaningful because without tag3:N the
tag3 messages could have been printed; the errors for tag1 and tag2 will be printed at the specified (or
lower) verbosity level and everything else will be printed by default.

A More Complex Filtering Example The following log snippet was acquired without any filtering options:

load:0x40078000,len:13564
entry 0x40078d4c
E (31) esp_image: image at 0x30000 has invalid magic byte
W (31) esp_image: image at 0x30000 has invalid SPI mode 255
E (39) boot: Factory app partition is not bootable
I (568) cpu_start: Pro cpu up.
I (569) heap_init: Initializing. RAM available for dynamic allocation:
I (603) cpu_start: Pro cpu start user code
D (309) light_driver: [light_init, 74]:status: 1, mode: 2
(continues on next page)

Espressif Systems 114 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

(continued from previous page)


D (318) vfs: esp_vfs_register_fd_range is successful for range <54; 64) and VFS ID␣
,→1

I (328) wifi: wifi driver task: 3ffdbf84, prio:23, stack:4096, core=0

The captured output for the filtering options PRINT_FILTER="wifi esp_image:E light_driver:I"
is given below:

E (31) esp_image: image at 0x30000 has invalid magic byte


I (328) wifi: wifi driver task: 3ffdbf84, prio:23, stack:4096, core=0

The options ``PRINT_FILTER="light_driver:D esp_image:N boot:N cpu_start:N


vfs:N wifi:N *:V" show the following output:

load:0x40078000,len:13564
entry 0x40078d4c
I (569) heap_init: Initializing. RAM available for dynamic allocation:
D (309) light_driver: [light_init, 74]:status: 1, mode: 2

Known Issues with IDF Monitor

Issues Observed on Windows


• Arrow keys, as well as some other keys, do not work in GDB due to Windows Console limitations.
• Occasionally, when “idf.py”exits, it might stall for up to 30 seconds before IDF Monitor resumes.
• When “gdb”is run, it might stall for a short time before it begins communicating with the GDBStub.

Standard Toolchain Setup for Linux and macOS

Installation Step by Step This is a detailed roadmap to walk you through the installation process.

Setting up Development Environment These are the steps for setting up the ESP-IDF for your ESP32.
• Step 1. Install Prerequisites
• Step 2. Get ESP-IDF
• Step 3. Set up the Tools
• Step 4. Set up the Environment Variables
• Step 5. First Steps on ESP-IDF

Step 1. Install Prerequisites In order to use ESP-IDF with the ESP32, you need to install some software packages
based on your Operating System. This setup guide helps you on getting everything installed on Linux and macOS
based systems.

For Linux Users To compile using ESP-IDF, you need to get the following packages. The command to run
depends on which distribution of Linux you are using:
• Ubuntu and Debian:

sudo apt-get install git wget flex bison gperf python3 python3-pip python3-
,→venv cmake ninja-build ccache libffi-dev libssl-dev dfu-util libusb-1.0-0

• CentOS 7 & 8:

Espressif Systems 115 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

sudo yum -y update && sudo yum install git wget flex bison gperf python3 cmake␣
,→ninja-build ccache dfu-util libusbx

CentOS 7 is still supported but CentOS version 8 is recommended for a better user experience.
• Arch:

sudo pacman -S --needed gcc git make flex bison gperf python cmake ninja␣
,→ccache dfu-util libusb

Note:
• CMake version 3.16 or newer is required for use with ESP-IDF. Run “tools/idf_tools.py install cmake”to
install a suitable version if your OS versions does not have one.
• If you do not see your Linux distribution in the above list then please check its documentation to find out which
command to use for package installation.

For macOS Users ESP-IDF uses the version of Python installed by default on macOS.
• Install CMake & Ninja build:
– If you have HomeBrew, you can run:

brew install cmake ninja dfu-util

– If you have MacPorts, you can run:

sudo port install cmake ninja dfu-util

– Otherwise, consult the CMake and Ninja home pages for macOS installation downloads.
• It is strongly recommended to also install ccache for faster builds. If you have HomeBrew, this can be done
via brew install ccache or sudo port install ccache on MacPorts.

Note: If an error like this is shown during any step:

xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools),␣


,→missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun

Then you need to install the XCode command line tools to continue. You can install these by running
xcode-select --install.

Apple M1 Users If you use Apple M1 platform and see an error like this:

WARNING: directory for tool xtensa-esp32-elf version esp-2021r2-patch3-8.4.0 is␣


,→present, but tool was not found

ERROR: tool xtensa-esp32-elf has no installed versions. Please run 'install.sh' to␣
,→install it.

or:

zsh: bad CPU type in executable: ~/.espressif/tools/xtensa-esp32-elf/esp-2021r2-


,→patch3-8.4.0/xtensa-esp32-elf/bin/xtensa-esp32-elf-gcc

Then you need to install Apple Rosetta 2 by running

/usr/sbin/softwareupdate --install-rosetta --agree-to-license

Espressif Systems 116 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Installing Python 3 Based on macOS Catalina 10.15 release notes, use of Python 2.7 is not recommended and
Python 2.7 is not included by default in future versions of macOS. Check what Python you currently have:

python --version

If the output is like Python 2.7.17, your default interpreter is Python 2.7. If so, also check if Python 3 is not
already installed on your computer:

python3 --version

If the above command returns an error, it means Python 3 is not installed.


Below is an overview of the steps to install Python 3.
• Installing with HomeBrew can be done as follows:

brew install python3

• If you have MacPorts, you can run:

sudo port install python38

Step 2. Get ESP-IDF To build applications for the ESP32, you need the software libraries provided by Espressif
in ESP-IDF repository.
To get ESP-IDF, navigate to your installation directory and clone the repository with git clone, following in-
structions below specific to your operating system.
Open Terminal, and run the following commands:

mkdir -p ~/esp
cd ~/esp
git clone --recursive https://github.com/espressif/esp-idf.git

ESP-IDF is downloaded into ~/esp/esp-idf.


Consult ESP-IDF Versions for information about which ESP-IDF version to use in a given situation.

Step 3. Set up the Tools Aside from the ESP-IDF, you also need to install the tools used by ESP-IDF, such as the
compiler, debugger, Python packages, etc, for projects supporting ESP32.

cd ~/esp/esp-idf
./install.sh esp32

or with Fish shell

cd ~/esp/esp-idf
./install.fish esp32

The above commands install tools for ESP32 only. If you intend to develop projects for more chip targets then you
should list all of them and run for example:

cd ~/esp/esp-idf
./install.sh esp32,esp32s2

or with Fish shell

cd ~/esp/esp-idf
./install.fish esp32,esp32s2

In order to install tools for all supported targets please run the following command:

Espressif Systems 117 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

cd ~/esp/esp-idf
./install.sh all

or with Fish shell

cd ~/esp/esp-idf
./install.fish all

Note: For macOS users, if an error like this is shown during any step:

<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable␣


,→to get local issuer certificate (_ssl.c:xxx)

You may run Install Certificates.command in the Python folder of your computer to install certificates.
For details, see Download Error While Installing ESP-IDF Tools.

Alternative File Downloads The tools installer downloads a number of files attached to GitHub Releases. If
accessing GitHub is slow then it is possible to set an environment variable to prefer Espressif’s download server for
GitHub asset downloads.

Note: This setting only controls individual tools downloaded from GitHub releases, it does not change the URLs
used to access any Git repositories.

To prefer the Espressif download server when installing tools, use the following sequence of commands when running
install.sh:

cd ~/esp/esp-idf
export IDF_GITHUB_ASSETS="dl.espressif.com/github_assets"
./install.sh

Note: For users in China, we recommend using our download server located in China for faster download speed.

cd ~/esp/esp-idf
export IDF_GITHUB_ASSETS="dl.espressif.cn/github_assets"
./install.sh

Customizing the Tools Installation Path The scripts introduced in this step install compilation tools required by
ESP-IDF inside the user home directory: $HOME/.espressif on Linux. If you wish to install the tools into a
different directory, set the environment variable IDF_TOOLS_PATH before running the installation scripts. Make
sure that your user account has sufficient permissions to read and write this path.
If changing the IDF_TOOLS_PATH, make sure it is set to the same value every time the Install script (install.
bat, install.ps1 or install.sh) and an Export script (export.bat, export.ps1 or export.sh)
are executed.

Step 4. Set up the Environment Variables The installed tools are not yet added to the PATH environment
variable. To make the tools usable from the command line, some environment variables must be set. ESP-IDF
provides another script which does that.
In the terminal where you are going to use ESP-IDF, run:

. $HOME/esp/esp-idf/export.sh

Espressif Systems 118 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

or for fish (supported only since fish version 3.0.0):

. $HOME/esp/esp-idf/export.fish

Note the space between the leading dot and the path!
If you plan to use esp-idf frequently, you can create an alias for executing export.sh:
1. Copy and paste the following command to your shell’s profile (.profile, .bashrc, .zprofile, etc.)

alias get_idf='. $HOME/esp/esp-idf/export.sh'

2. Refresh the configuration by restarting the terminal session or by running source [path to profile],
for example, source ~/.bashrc.
Now you can run get_idf to set up or refresh the esp-idf environment in any terminal session.
Technically, you can add export.sh to your shell’s profile directly; however, it is not recommended. Doing so
activates IDF virtual environment in every terminal session (including those where IDF is not needed), defeating the
purpose of the virtual environment and likely affecting other software.

Step 5. First Steps on ESP-IDF Now since all requirements are met, the next topic will guide you on how to start
your first project.
This guide helps you on the first steps using ESP-IDF. Follow this guide to start a new project on the ESP32 and
build, flash, and monitor the device output.

Note: If you have not yet installed ESP-IDF, please go to Installation and follow the instruction in order to get all
the software needed to use this guide.

Start a Project Now you are ready to prepare your application for ESP32. You can start with get-
started/hello_world project from examples directory in ESP-IDF.

Important: The ESP-IDF build system does not support spaces in the paths to either ESP-IDF or to projects.

Copy the project get-started/hello_world to ~/esp directory:

cd ~/esp
cp -r $IDF_PATH/examples/get-started/hello_world .

Note: There is a range of example projects in the examples directory in ESP-IDF. You can copy any project in the
same way as presented above and run it. It is also possible to build examples in-place without copying them first.

Connect Your Device Now connect your ESP32 board to the computer and check under which serial port the
board is visible.
Serial ports have the following naming patterns:
• Linux: starting with /dev/tty
• macOS: starting with /dev/cu.
If you are not sure how to check the serial port name, please refer to Establish Serial Connection with ESP32 for full
details.

Note: Keep the port name handy as it is needed in the next steps.

Espressif Systems 119 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Configure Your Project Navigate to your hello_world directory, set ESP32 as the target, and run the project
configuration utility menuconfig.

cd ~/esp/hello_world
idf.py set-target esp32
idf.py menuconfig

After opening a new project, you should first set the target with idf.py set-target esp32. Note that existing
builds and configurations in the project, if any, are cleared and initialized in this process. The target may be saved in
the environment variable to skip this step at all. See Select the Target Chip: set-target for additional information.
If the previous steps have been done correctly, the following menu appears:

Fig. 65: Project configuration - Home window

You are using this menu to set up project specific variables, e.g., Wi-Fi network name and password, the processor
speed, etc. Setting up the project with menuconfig may be skipped for“hello_world”, since this example runs with
default configuration.

Attention: If you use ESP32-DevKitC board with the ESP32-SOLO-1 module, or ESP32-DevKitM-1 board
with the ESP32-MIN1-1(1U) module, please enable single core mode (CONFIG_FREERTOS_UNICORE) in
menuconfig before flashing examples.

Note: The colors of the menu could be different in your terminal. You can change the appearance with the option
--style. Please run idf.py menuconfig --help for further information.

If you are using one of the supported development boards, you can speed up your development by using Board Support
Package. See Additional Tips for more information.

Build the Project Build the project by running:

idf.py build

This command compiles the application and all ESP-IDF components, then it generates the bootloader, partition
table, and application binaries.

Espressif Systems 120 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

$ idf.py build
Running cmake in directory /path/to/hello_world/build
Executing "cmake -G Ninja --warn-uninitialized /path/to/hello_world"...
Warn about uninitialized values.
-- Found Git: /usr/bin/git (found version "2.17.0")
-- Building empty aws_iot component due to configuration
-- Component names: ...
-- Component paths: ...

... (more lines of build system output)

[527/527] Generating hello_world.bin


esptool.py v2.3.1

Project build complete. To flash, run this command:


../../../components/esptool_py/esptool/esptool.py -p (PORT) -b 921600 write_flash -
,→-flash_mode dio --flash_size detect --flash_freq 40m 0x10000 build/hello_world.

,→bin build 0x1000 build/bootloader/bootloader.bin 0x8000 build/partition_table/


,→partition-table.bin

or run 'idf.py -p PORT flash'

If there are no errors, the build finishes by generating the firmware binary .bin files.

Flash onto the Device To flash the binaries that you just built for the ESP32 in the previous step, you need to run
the following command:
idf.py -p PORT flash

Replace PORT with your ESP32 board’s USB port name. If the PORT is not defined, the idf.py will try to connect
automatically using the available USB ports.
For more information on idf.py arguments, see idf.py.

Note: The option flash automatically builds and flashes the project, so running idf.py build is not necessary.

Encountered Issues While Flashing? See this Flashing Troubleshooting page or Establish Serial Connection with ESP32
for more detailed information.

Normal Operation When flashing, you will see the output log similar to the following:
...
esptool.py --chip esp32 -p /dev/ttyUSB0 -b 460800 --before=default_reset --
,→after=hard_reset write_flash --flash_mode dio --flash_freq 40m --flash_size 2MB␣

,→0x8000 partition_table/partition-table.bin 0x1000 bootloader/bootloader.bin␣

,→0x10000 hello_world.bin

esptool.py v3.0-dev
Serial port /dev/ttyUSB0
Connecting........_
Chip is ESP32D0WDQ6 (revision 0)
Features: WiFi, BT, Dual Core, Coding Scheme None
Crystal is 40MHz
MAC: 24:0a:c4:05:b9:14
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Compressed 3072 bytes to 103...
(continues on next page)

Espressif Systems 121 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

(continued from previous page)


Writing at 0x00008000... (100 %)
Wrote 3072 bytes (103 compressed) at 0x00008000 in 0.0 seconds (effective 5962.8␣
,→kbit/s)...

Hash of data verified.


Compressed 26096 bytes to 15408...
Writing at 0x00001000... (100 %)
Wrote 26096 bytes (15408 compressed) at 0x00001000 in 0.4 seconds (effective 546.7␣
,→kbit/s)...

Hash of data verified.


Compressed 147104 bytes to 77364...
Writing at 0x00010000... (20 %)
Writing at 0x00014000... (40 %)
Writing at 0x00018000... (60 %)
Writing at 0x0001c000... (80 %)
Writing at 0x00020000... (100 %)
Wrote 147104 bytes (77364 compressed) at 0x00010000 in 1.9 seconds (effective 615.
,→5 kbit/s)...

Hash of data verified.

Leaving...
Hard resetting via RTS pin...
Done

If there are no issues by the end of the flash process, the board will reboot and start up the“hello_world”application.
If you would like to use the Eclipse or VS Code IDE instead of running idf.py, check out Eclipse Plugin, VSCode
Extension.

Monitor the Output To check if “hello_world”is indeed running, type idf.py -p PORT monitor (Do
not forget to replace PORT with your serial port name).
This command launches the IDF Monitor application:
$ idf.py -p <PORT> monitor
Running idf_monitor in directory [...]/esp/hello_world/build
Executing "python [...]/esp-idf/tools/idf_monitor.py -b 115200 [...]/esp/hello_
,→world/build/hello_world.elf"...

--- idf_monitor on <PORT> 115200 ---


--- Quit: Ctrl+] | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
ets Jun 8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)


ets Jun 8 2016 00:22:57
...

After startup and diagnostic logs scroll up, you should see “Hello world!”printed out by the application.
...
Hello world!
Restarting in 10 seconds...
This is esp32 chip with 2 CPU core(s), WiFi/BT/BLE, silicon revision 1, 2 MB␣
,→external flash

Minimum free heap size: 298968 bytes


Restarting in 9 seconds...
Restarting in 8 seconds...
Restarting in 7 seconds...

To exit IDF monitor use the shortcut Ctrl+].


If IDF monitor fails shortly after the upload, or, if instead of the messages above, you see random garbage similar to
what is given below, your board is likely using a 26 MHz crystal. Most development board designs use 40 MHz, so
ESP-IDF uses this frequency as a default value.

Espressif Systems 122 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

If you have such a problem, do the following:


1. Exit the monitor.
2. Go back to menuconfig.
3. Go to Component config –> Hardware Settings –> Main XTAL Config –> Main XTAL
frequency, then change CONFIG_XTAL_FREQ_SEL to 26 MHz.
4. After that, build and flash the application again.
In the current version of ESP-IDF, main XTAL frequencies supported by ESP32 are as follows:

• 26 MHz
• 40 MHz

Note: You can combine building, flashing and monitoring into one step by running:

idf.py -p PORT flash monitor

See also:
• IDF Monitor for handy shortcuts and more details on using IDF monitor.
• idf.py for a full reference of idf.py commands and options.
That is all that you need to get started with ESP32!
Now you are ready to try some other examples, or go straight to developing your own applications.

Important: Some of examples do not support ESP32 because required hardware is not included in ESP32 so it
cannot be supported.
If building an example, please check the README file for the Supported Targets table. If this is present
including ESP32 target, or the table does not exist at all, the example will work on ESP32.

Additional Tips

Permission Issues /dev/ttyUSB0 With some Linux distributions, you may get the Failed to open port
/dev/ttyUSB0 error message when flashing the ESP32. This can be solved by adding the current user to the dialout
group.

Python Compatibility ESP-IDF supports Python 3.8 or newer. It is recommended to upgrade your operating
system to a recent version satisfying this requirement. Other options include the installation of Python from sources
or the use of a Python version management system such as pyenv.

Start with Board Support Package To speed up prototyping on some development boards, you can use Board
Support Packages (BSPs), which makes initialization of a particular board as easy as few function calls.
A BSP typically supports all of the hardware components provided on development board. Apart from the pinout
definition and initialization functions, a BSP ships with drivers for the external components such as sensors, displays,
audio codecs etc.
The BSPs are distributed via IDF Component Manager, so they can be found in IDF Component Registry.

Espressif Systems 123 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 1. Get Started

Here is an example of how to add ESP-WROVER-KIT BSP to your project:

idf.py add-dependency esp_wrover_kit

More examples of BSP usage can be found in BSP examples folder.

Flash Erase Erasing the flash is also possible. To erase the entire flash memory you can run the following command:

idf.py -p PORT erase-flash

For erasing the OTA data, if present, you can run this command:

idf.py -p PORT erase-otadata

The flash erase command can take a while to be done. Do not disconnect your device while the flash erasing is in
progress.

Tip: Updating ESP-IDF It is recommended to update ESP-IDF from time to time, as newer versions fix bugs
and/or provide new features. Please note that each ESP-IDF major and minor release version has an associated
support period, and when one release branch is approaching end of life (EOL), all users are encouraged to upgrade
their projects to more recent ESP-IDF releases, to find out more about support periods, see ESP-IDF Versions.
The simplest way to do the update is to delete the existing esp-idf folder and clone it again, as if performing the
initial installation described in Step 2. Get ESP-IDF.
Another solution is to update only what has changed. The update procedure depends on the version of ESP-IDF you
are using.
After updating ESP-IDF, execute the Install script again, in case the new ESP-IDF version requires different versions
of tools. See instructions at Step 3. Set up the Tools.
Once the new tools are installed, update the environment using the Export script. See instructions at Step 4. Set up
the Environment Variables.

Related Documents
• Establish Serial Connection with ESP32
• Eclipse Plugin
• VSCode Extension
• IDF Monitor

1.4 Build Your First Project


If you already have the ESP-IDF installed and not using IDE, you can build your first project from the command line
following the Start a Project on Windows or Start a Project on Linux and macOS.

1.5 Uninstall ESP-IDF


If you want to remove ESP-IDF, please follow Uninstall ESP-IDF.

Espressif Systems 124 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2

API Reference

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

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

2.1.2 Configuration Structures

Important: Correct initialization of configuration structures is an important part of making the application com-
patible with future versions of ESP-IDF.

125
Chapter 2. API Reference

Most initialization, configuration, and installation functions in ESP-IDF (typically named ..._init(), ...
_config(), and ..._install()) take a configuration structure pointer as an argument. For example:
const esp_timer_create_args_t my_timer_args = {
.callback = &my_timer_callback,
.arg = callback_arg,
.name = "my_timer"
};
esp_timer_handle_t my_timer;
esp_err_t err = esp_timer_create(&my_timer_args, &my_timer);

These functions never store the pointer to the configuration structure, so it is safe to allocate the structure on the stack.
The application must initialize all fields of the structure. The following is incorrect:
esp_timer_create_args_t my_timer_args;
my_timer_args.callback = &my_timer_callback;
/* Incorrect! Fields .arg and .name are not initialized */
esp_timer_create(&my_timer_args, &my_timer);

Most ESP-IDF examples use C99 designated initializers for structure initialization since they provide a concise way
of setting a subset of fields, and zero-initializing the remaining fields:
const esp_timer_create_args_t my_timer_args = {
.callback = &my_timer_callback,
/* Correct, fields .arg and .name are zero-initialized */
};

The C++ language supports designated initializer syntax, too, but the initializers must be in the order of declaration.
When using ESP-IDF APIs in C++ code, you may consider using the following pattern:
/* Correct, fields .dispatch_method, .name and .skip_unhandled_events are zero-
,→initialized */

const esp_timer_create_args_t my_timer_args = {


.callback = &my_timer_callback,
.arg = &my_arg,
};

///* Incorrect, .arg is declared after .callback in esp_timer_create_args_t */


//const esp_timer_create_args_t my_timer_args = {
// .arg = &my_arg,
// .callback = &my_timer_callback,
//};

For more information on designated initializers, see Designated Initializers. Note that C++ language versions older
than C++20, which are not the default in the current version of ESP-IDF, do not support designated initializers. If
you have to compile code with an older C++ standard than C++20, you may use GCC extensions to produce the
following pattern:
esp_timer_create_args_t my_timer_args = {};
/* All the fields are zero-initialized */
my_timer_args.callback = &my_timer_callback;

Default Initializers

For some configuration structures, ESP-IDF provides macros for setting default values of fields:
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
/* HTTPD_DEFAULT_CONFIG expands to a designated initializer. Now all fields are␣
,→set to the default values, and any field can still be modified: */

config.server_port = 8081;
(continues on next page)

Espressif Systems 126 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

(continued from previous page)


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.

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

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

2.1.5 API Stability

ESP-IDF uses Semantic Versioning as explained in the Versioning Scheme.


Minor and bugfix releases of ESP-IDF guarantee compatibility with previous releases. The sections below explain
different aspects and limitations to compatibility.

Source-level Compatibility

ESP-IDF guarantees source-level compatibility of C functions, structures, enums, type definitions, and preprocessor
macros declared in public header files of ESP-IDF components. Source-level compatibility implies that the applica-
tion source code can be recompiled with the newer version of ESP-IDF without changes.
The following changes are allowed between minor versions and do not break source-level compatibility:
• Deprecating functions (using the deprecated attribute) and header files (using a preprocessor #warning).
Deprecations are listed in ESP-IDF release notes. It is recommended to update the source code to use the newer
functions or files that replace the deprecated ones, however, this is not mandatory. Deprecated functions and
files can be removed from major versions of ESP-IDF.
• Renaming components, moving source and header files between components —provided that the build system
ensures that correct files are still found.
• Renaming Kconfig options. Kconfig system’s backward compatibility ensures that the original Kconfig option
names can still be used by the application in sdkconfig file, CMake files, and source code.

Espressif Systems 127 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Lack of Binary Compatibility

ESP-IDF does not guarantee binary compatibility between releases. This means that if a precompiled library is built
with one ESP-IDF version, it is not guaranteed to work the same way with the next minor or bugfix release. The
following are the possible changes that keep source-level compatibility but not binary compatibility:
• Changing numerical values for C enum members.
• Adding new structure members or changing the order of members. See Configuration Structures for tips that
help ensure compatibility.
• Replacing an extern function with a static inline one with the same signature, or vice versa.
• Replacing a function-like macro with a compatible C function.

Other Exceptions from Compatibility

While we try to make upgrading to a new ESP-IDF version easy, there are parts of ESP-IDF that may change between
minor versions in an incompatible way. We appreciate issuing reports about any unintended breaking changes that
do not fall into the categories below.
• Private APIs.
• Components in Example Projects.
• Features clearly marked as “beta”, “preview”, or “experimental”.
• Changes made to mitigate security issues or to replace insecure default behaviors with secure ones.
• Features that were never functional. For example, if it was never possible to use a certain function or an
enumeration value, it may get renamed (as part of fixing it) or removed. This includes software features that
depend on non-functional chip hardware features.
• Unexpected or undefined behavior that is not documented explicitly may be fixed/changed, such as due to
missing validation of argument ranges.
• Location of Kconfig options in menuconfig.
• Location and names of example projects.

2.2 Application Protocols

2.2.1 ASIO Port

ASIO is a cross-platform C++ library, see https://think-async.com/Asio/. It provides a consistent asynchronous


model using a modern C++ approach.
The ESP-IDF component ASIO has been moved from ESP-IDF since version v5.0 to a separate repository:
• ASIO component on GitHub
To add ASIO component in your project, please run idf.py add-dependency espressif/asio.

Hosted Documentation

The documentation can be found on the link below:


• ASIO documentation (English)

Espressif Systems 128 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

2.2.2 ESP-Modbus

The Espressif ESP-Modbus Library (esp-modbus) supports Modbus communication in the networks based on RS485,
Wi-Fi, and Ethernet interfaces. Since ESP-IDF version v5.0, the component freemodbus has been moved from
ESP-IDF to a separate repository:
• ESP-Modbus component on GitHub

Hosted Documentation

The documentation can be found through the link below:


• ESP-Modbus documentation (English)

Application Example

The examples below demonstrate the ESP-Modbus library of serial and TCP ports for both slave and master imple-
mentations respectively.
• protocols/modbus/serial/mb_slave
• protocols/modbus/serial/mb_master
• protocols/modbus/tcp/mb_tcp_slave
• protocols/modbus/tcp/mb_tcp_master
Please refer to the README.md documents of each specific example for details.

Protocol References

• For the detailed protocol specifications, see The Modbus Organization.

2.2.3 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

Espressif Systems 129 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• protocols/mqtt/ssl_psk: MQTT over TLS using pre-shared keys for authentication, default port 8883
• protocols/mqtt/ws: MQTT over WebSocket, default port 80
• protocols/mqtt/wss: MQTT over WebSocket Secure, default port 443
• protocols/mqtt5: Uses ESP-MQTT library to connect to broker with MQTT v5.0

MQTT Message Retransmission

A new MQTT message is created by calling esp_mqtt_client_publish or its non blocking counterpart
esp_mqtt_client_enqueue.
Messages with QoS 0 is sent only once. QoS 1 and 2 have different behaviors since the protocol requires extra steps
to complete the process.
The ESP-MQTT library opts to always retransmit unacknowledged QoS 1 and 2 publish messages to avoid losses in
faulty connections, even though the MQTT specification requires the re-transmission only on reconnect with Clean
Session flag been set to 0 (set disable_clean_session to true for this behavior).
QoS 1 and 2 messages that may need retransmission are always enqueued, but first transmission try occurs immediately
if esp_mqtt_client_publish is used. A transmission retry for unacknowledged messages will occur after
message_retransmit_timeout. After CONFIG_MQTT_OUTBOX_EXPIRED_TIMEOUT_MS messages will
expire and be deleted. If CONFIG_MQTT_REPORT_DELETED_MESSAGES is set, an event will be sent to notify the
user.

Configuration

The configuration is made by setting fields in esp_mqtt_client_config_t struct. The configuration struct
has the following sub structs to configure different aspects of the client operation.
• esp_mqtt_client_config_t::broker_t - Allow to set address and security verification.
• esp_mqtt_client_config_t::credentials_t - Client credentials for authentication.
• esp_mqtt_client_config_t::session_t - Configuration for MQTT session aspects.
• esp_mqtt_client_config_t::network_t - Networking related configuration.
• esp_mqtt_client_config_t::task_t - Allow to configure FreeRTOS task.
• esp_mqtt_client_config_t::buffer_t - Buffer size for input and output.
In the following sections, the most common aspects are detailed.

Broker

Address Broker address can be set by usage of address struct. The configuration can be made by usage of uri
field or the combination of hostname, transport and port. Optionally, path could be set, this field is useful
in WebSocket connections.
The uri field is used in the format scheme://hostname:port/path.
• Curently support mqtt, mqtts, ws, wss schemes
• MQTT over TCP samples:
– mqtt://mqtt.eclipseprojects.io: MQTT over TCP, default port 1883
– mqtt://mqtt.eclipseprojects.io:1884: MQTT over TCP, port 1884
– mqtt://username:[email protected]:1884: MQTT over TCP,
port 1884, with username and password
• MQTT over SSL samples:
– mqtts://mqtt.eclipseprojects.io: MQTT over SSL, port 8883
– mqtts://mqtt.eclipseprojects.io:8884: MQTT over SSL, port 8884
• MQTT over WebSocket samples:
– ws://mqtt.eclipseprojects.io:80/mqtt
• MQTT over WebSocket Secure samples:
– wss://mqtt.eclipseprojects.io:443/mqtt
• Minimal configurations:

Espressif Systems 130 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

const esp_mqtt_client_config_t mqtt_cfg = {


.broker.address.uri = "mqtt://mqtt.eclipseprojects.io",
};
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler,␣
,→client);

esp_mqtt_client_start(client);

Note: By default MQTT client uses event loop library to post related MQTT events (connected, subscribed, pub-
lished, etc.).

Verification For secure connections with TLS used, and to guarantee Broker’s identity, the verification
struct must be set. The broker certificate may be set in PEM or DER format. To select DER, the equivalent cer-
tificate_len field must be set. Otherwise, a null-terminated string in PEM format should be provided to cer-
tificate field.
• Get certificate from server, example: mqtt.eclipseprojects.io

openssl s_client -showcerts -connect mqtt.eclipseprojects.io:8883 < /dev/


,→null \

2> /dev/null | openssl x509 -outform PEM > mqtt_eclipse_org.pem

• Check the sample application: protocols/mqtt/ssl


• Configuration:

const esp_mqtt_client_config_t mqtt_cfg = {


.broker = {
.address.uri = "mqtts://mqtt.eclipseprojects.io:8883",
.verification.certificate = (const char *)mqtt_eclipse_org_pem_start,
},
};

For details about other fields, please check the API Reference and TLS Server Verification.

Client Credentials All client related credentials are under the credentials field.
• username: pointer to the username used for connecting to the broker, can also be set by URI
• client_id: pointer to the client ID, defaults to ESP32_%CHIPID% where %CHIPID% are the last 3 bytes
of MAC address in hex format

Authentication It is possible to set authentication parameters through the authentication field. The client
supports the following authentication methods:
• password: use a password by setting
• certificate and key: mutual authentication with TLS, and both can be provided in PEM or DER format
• use_secure_element: use secure element available in ESP32-WROOM-32SE
• ds_data: use Digital Signature Peripheral available in some Espressif devices

Session For MQTT session related configurations, session fields should be used.

Last Will and Testament MQTT allows for a last will and testament (LWT) message to notify other clients when
a client ungracefully disconnects. This is configured by the following fields in the last_will struct.
• topic: pointer to the LWT message topic
• msg: pointer to the LWT message
• msg_len: length of the LWT message, required if msg is not null-terminated

Espressif Systems 131 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• qos: quality of service for the LWT message


• retain: specifies the retain flag of the LWT message

Change Settings in Project Configuration Menu The settings for MQTT can be found using idf.py menu-
config, under Component config > ESP-MQTT Configuration.
The following settings are available:
• CONFIG_MQTT_PROTOCOL_311: enable 3.1.1 version of MQTT protocol
• CONFIG_MQTT_TRANSPORT_SSL and CONFIG_MQTT_TRANSPORT_WEBSOCKET: enable specific
MQTT transport layer, such as SSL, WEBSOCKET, and WEBSOCKET_SECURE
• CONFIG_MQTT_CUSTOM_OUTBOX: disable default implementation of mqtt_outbox, so a specific imple-
mentation can be supplied

Events

The following events may be posted by the MQTT client:


• MQTT_EVENT_BEFORE_CONNECT: The client is initialized and about to start connecting to the broker.
• MQTT_EVENT_CONNECTED: The client has successfully established a connection to the broker. The client
is now ready to send and receive data.
• MQTT_EVENT_DISCONNECTED: The client has aborted the connection due to being unable to read or write
data, e.g., because the server is unavailable.
• MQTT_EVENT_SUBSCRIBED: The broker has acknowledged the client’s subscribe request. The event data
contains the message ID of the subscribe message.
• MQTT_EVENT_UNSUBSCRIBED: The broker has acknowledged the client’s unsubscribe request. The event
data contains the message ID of the unsubscribe message.
• MQTT_EVENT_PUBLISHED: The broker has acknowledged the client’s publish message. This is only posted
for QoS level 1 and 2, as level 0 does not use acknowledgements. The event data contains the message ID of
the publish message.
• MQTT_EVENT_DATA: The client has received a publish message. The event data contains: message ID,
name of the topic it was published to, received data and its length. For data that exceeds the internal buffer,
multiple MQTT_EVENT_DATA events are posted and current_data_offset and total_data_len
from event data updated to keep track of the fragmented message.
• MQTT_EVENT_ERROR: The client has encountered an error. The field error_handle in the event data
contains error_type that can be used to identify the error. The type of error determines which parts of the
error_handle struct is filled.

API Reference

Header File
• components/mqtt/esp-mqtt/include/mqtt_client.h

Functions
esp_mqtt_client_handle_t esp_mqtt_client_init(const esp_mqtt_client_config_t *config)
Creates MQTT client handle based on the configuration.
Parameters config –MQTT configuration structure
Returns mqtt_client_handle if successfully created, NULL on error
esp_err_t esp_mqtt_client_set_uri(esp_mqtt_client_handle_t client, const char *uri)
Sets MQTT connection URI. This API is usually used to overrides the URI configured in esp_mqtt_client_init.
Parameters
• client –MQTT client handle
• uri –
Returns ESP_FAIL if URI parse error, ESP_OK on success

Espressif Systems 132 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_mqtt_client_start(esp_mqtt_client_handle_t client)


Starts MQTT client with already created client handle.
Parameters client –MQTT client handle
Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization ESP_FAIL on
other error
esp_err_t esp_mqtt_client_reconnect(esp_mqtt_client_handle_t client)
This api is typically used to force reconnection upon a specific event.
Parameters client –MQTT client handle
Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization ESP_FAIL if
client is in invalid state
esp_err_t esp_mqtt_client_disconnect(esp_mqtt_client_handle_t client)
This api is typically used to force disconnection from the broker.
Parameters client –MQTT client handle
Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization
esp_err_t esp_mqtt_client_stop(esp_mqtt_client_handle_t client)
Stops MQTT client tasks.

• Notes:
• Cannot be called from the MQTT event handler

Parameters client –MQTT client handle


Returns ESP_OK on success ESP_ERR_INVALID_ARG on wrong initialization ESP_FAIL if
client is in invalid state

int esp_mqtt_client_subscribe_single(esp_mqtt_client_handle_t client, const char *topic, int qos)


Subscribe the client to defined topic with defined qos.
Notes:
• Client must be connected to send subscribe message
• This API is could be executed from a user task or from a MQTT event callback i.e. internal MQTT task
(API is protected by internal mutex, so it might block if a longer data receive operation is in progress.
• esp_mqtt_client_subscribe could be used to call this function.

Parameters
• client –MQTT client handle
• topic –topic filter to subscribe
• qos –Max qos level of the subscription
Returns message_id of the subscribe message on success -1 on failure -2 in case of full outbox.

int esp_mqtt_client_subscribe_multiple(esp_mqtt_client_handle_t client, const esp_mqtt_topic_t


*topic_list, int size)
Subscribe the client to a list of defined topics with defined qos.
Notes:
• Client must be connected to send subscribe message
• This API is could be executed from a user task or from a MQTT event callback i.e. internal MQTT task
(API is protected by internal mutex, so it might block if a longer data receive operation is in progress.
• esp_mqtt_client_subscribe could be used to call this function.

Parameters
• client –MQTT client handle
• topic_list –List of topics to subscribe
• size –size of topic_list

Espressif Systems 133 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Returns message_id of the subscribe message on success -1 on failure -2 in case of full outbox.

int esp_mqtt_client_unsubscribe(esp_mqtt_client_handle_t client, const char *topic)


Unsubscribe the client from defined topic.
Notes:
• Client must be connected to send unsubscribe message
• It is thread safe, please refer to esp_mqtt_client_subscribe_single for details

Parameters
• client –MQTT client handle
• topic –
Returns message_id of the subscribe message on success -1 on failure

int esp_mqtt_client_publish(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len,
int qos, int retain)
Client to send a publish message to the broker.
Notes:
• This API might block for several seconds, either due to network timeout (10s) or if publishing payloads
longer than internal buffer (due to message fragmentation)
• Client doesn’t have to be connected for this API to work, enqueueing the messages with qos>1 (returning
-1 for all the qos=0 messages if disconnected). If MQTT_SKIP_PUBLISH_IF_DISCONNECTED is
enabled, this API will not attempt to publish when the client is not connected and will always return -1.
• It is thread safe, please refer to esp_mqtt_client_subscribe for details

Parameters
• client –MQTT client handle
• topic –topic string
• data –payload string (set to NULL, sending empty payload message)
• len –data length, if set to 0, length is calculated from payload string
• qos –QoS of publish message
• retain –retain flag
Returns message_id of the publish message (for QoS 0 message_id will always be zero) on success.
-1 on failure, -2 in case of full outbox.

int esp_mqtt_client_enqueue(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len,
int qos, int retain, bool store)
Enqueue a message to the outbox, to be sent later. Typically used for messages with qos>0, but could be also
used for qos=0 messages if store=true.
This API generates and stores the publish message into the internal outbox and the actual sending to the net-
work is performed in the mqtt-task context (in contrast to the esp_mqtt_client_publish() which sends the pub-
lish message immediately in the user task’s context). Thus, it could be used as a non blocking version of
esp_mqtt_client_publish().
Parameters
• client –MQTT client handle
• topic –topic string
• data –payload string (set to NULL, sending empty payload message)
• len –data length, if set to 0, length is calculated from payload string
• qos –QoS of publish message
• retain –retain flag
• store –if true, all messages are enqueued; otherwise only QoS 1 and QoS 2 are enqueued
Returns message_id if queued successfully, -1 on failure, -2 in case of full outbox.

Espressif Systems 134 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_mqtt_client_destroy(esp_mqtt_client_handle_t client)


Destroys the client handle.
Notes:
• Cannot be called from the MQTT event handler

Parameters client –MQTT client handle


Returns ESP_OK ESP_ERR_INVALID_ARG on wrong initialization

esp_err_t esp_mqtt_set_config(esp_mqtt_client_handle_t client, const esp_mqtt_client_config_t *config)


Set configuration structure, typically used when updating the config (i.e. on “before_connect”event.
Parameters
• client –MQTT client handle
• config –MQTT configuration structure
Returns ESP_ERR_NO_MEM if failed to allocate ESP_ERR_INVALID_ARG if conflicts on
transport configuration. ESP_OK on success
esp_err_t esp_mqtt_client_register_event(esp_mqtt_client_handle_t client, esp_mqtt_event_id_t
event, esp_event_handler_t event_handler, void
*event_handler_arg)
Registers MQTT event.
Parameters
• client –MQTT client handle
• event –event type
• event_handler –handler callback
• event_handler_arg –handlers context
Returns ESP_ERR_NO_MEM if failed to allocate ESP_ERR_INVALID_ARG on wrong initial-
ization ESP_OK on success
esp_err_t esp_mqtt_client_unregister_event(esp_mqtt_client_handle_t client, esp_mqtt_event_id_t
event, esp_event_handler_t event_handler)
Unregisters mqtt event.
Parameters
• client –mqtt client handle
• event –event ID
• event_handler –handler to unregister
Returns ESP_ERR_NO_MEM if failed to allocate ESP_ERR_INVALID_ARG on invalid event
ID ESP_OK on success
int esp_mqtt_client_get_outbox_size(esp_mqtt_client_handle_t client)
Get outbox size.
Parameters client –MQTT client handle
Returns outbox size 0 on wrong initialization
esp_err_t esp_mqtt_dispatch_custom_event(esp_mqtt_client_handle_t client, esp_mqtt_event_t *event)
Dispatch user event to the mqtt internal event loop.
Parameters
• client –MQTT client handle
• event –MQTT event handle structure
Returns ESP_OK on success ESP_ERR_TIMEOUT if the event couldn’t be queued (ref also
CONFIG_MQTT_EVENT_QUEUE_SIZE)

Structures

Espressif Systems 135 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_mqtt_error_codes
MQTT error code structure to be passed as a contextual information into ERROR event
Important: This structure extends esp_tls_last_error error structure and is backward compatible with
it (so might be down-casted and treated as esp_tls_last_error error, but recommended to update
applications if used this way previously)
Use this structure directly checking error_type first and then appropriate error code depending on the source
of the error:
| error_type | related member variables | note | | MQTT_ERROR_TYPE_TCP_TRANSPORT |
esp_tls_last_esp_err, esp_tls_stack_err, esp_tls_cert_verify_flags, sock_errno | Error reported from
tcp_transport/esp-tls | | MQTT_ERROR_TYPE_CONNECTION_REFUSED | connect_return_code | Inter-
nal error reported from MQTT broker on connection |

Public Members

esp_err_t esp_tls_last_esp_err
last esp_err code reported from esp-tls component

int esp_tls_stack_err
tls specific error code reported from underlying tls stack

int esp_tls_cert_verify_flags
tls flags reported from underlying tls stack during certificate verification

esp_mqtt_error_type_t error_type
error type referring to the source of the error

esp_mqtt_connect_return_code_t connect_return_code
connection refused error code reported from MQTT* broker on connection

int esp_transport_sock_errno
errno from the underlying socket

struct esp_mqtt_event_t
MQTT event configuration structure

Public Members

esp_mqtt_event_id_t event_id
MQTT event type

esp_mqtt_client_handle_t client
MQTT client handle for this event

char *data
Data associated with this event

int data_len
Length of the data for this event

Espressif Systems 136 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

int total_data_len
Total length of the data (longer data are supplied with multiple events)

int current_data_offset
Actual offset for the data associated with this event

char *topic
Topic associated with this event

int topic_len
Length of the topic for this event associated with this event

int msg_id
MQTT messaged id of message

int session_present
MQTT session_present flag for connection event

esp_mqtt_error_codes_t *error_handle
esp-mqtt error handle including esp-tls errors as well as internal MQTT errors

bool retain
Retained flag of the message associated with this event

int qos
QoS of the messages associated with this event

bool dup
dup flag of the message associated with this event

esp_mqtt_protocol_ver_t protocol_ver
MQTT protocol version used for connection, defaults to value from menuconfig

struct esp_mqtt_client_config_t
MQTT client configuration structure

• Default values can be set via menuconfig


• All certificates and key data could be passed in PEM or DER format. PEM format must have a terminating
NULL character and the related len field set to 0. DER format requires a related len field set to the correct
length.

Public Members

struct esp_mqtt_client_config_t::broker_t broker


Broker address and security verification

struct esp_mqtt_client_config_t::credentials_t credentials


User credentials for broker

Espressif Systems 137 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_mqtt_client_config_t::session_t session


MQTT session configuration.

struct esp_mqtt_client_config_t::network_t network


Network configuration

struct esp_mqtt_client_config_t::task_t task


FreeRTOS task configuration.

struct esp_mqtt_client_config_t::buffer_t buffer


Buffer size configuration.

struct esp_mqtt_client_config_t::outbox_config_t outbox


Outbox configuration.

struct broker_t
Broker related configuration

Public Members

struct esp_mqtt_client_config_t::broker_t::address_t address


Broker address configuration

struct esp_mqtt_client_config_t::broker_t::verification_t verification


Security verification of the broker

struct address_t
Broker address

• uri have precedence over other fields


• If uri isn’t set at least hostname, transport and port should.

Public Members

const char *uri


Complete MQTT broker URI

const char *hostname


Hostname, to set ipv4 pass it as string)

esp_mqtt_transport_t transport
Selects transport

const char *path


Path in the URI

Espressif Systems 138 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint32_t port
MQTT server port

struct verification_t
Broker identity verification
If fields are not set broker’s identity isn’t verified. it’s recommended to set the options in this
struct for security reasons.

Public Members

bool use_global_ca_store
Use a global ca_store, look esp-tls documentation for details.

esp_err_t (*crt_bundle_attach)(void *conf)


Pointer to ESP x509 Certificate Bundle attach function for the usage of certificate bundles.

const char *certificate


Certificate data, default is NULL, not required to verify the server.

size_t certificate_len
Length of the buffer pointed to by certificate.

const struct psk_key_hint *psk_hint_key


Pointer to PSK struct defined in esp_tls.h to enable PSK authentication (as alternative to certifi-
cate verification). PSK is enabled only if there are no other ways to verify broker.

bool skip_cert_common_name_check
Skip any validation of server certificate CN field, this reduces the security of TLS and makes
the MQTT client susceptible to MITM attacks

const char **alpn_protos


NULL-terminated list of supported application protocols to be used for ALPN

const char *common_name


Pointer to the string containing server certificate common name. If non-NULL, server certificate
CN must match this name, If NULL, server certificate CN must match hostname. This is ignored
if skip_cert_common_name_check=true.

struct buffer_t
Client buffer size configuration
Client have two buffers for input and output respectivelly.

Public Members

int size
size of MQTT send/receive buffer

Espressif Systems 139 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

int out_size
size of MQTT output buffer. If not defined, defaults to the size defined by buffer_size

struct credentials_t
Client related credentials for authentication.

Public Members

const char *username


MQTT username

const char *client_id


Set MQTT client identifier. Ignored if set_null_client_id == true If NULL set the default client id.
Default client id is ESP32_CHIPID% where CHIPID% are last 3 bytes of MAC address in hex
format

bool set_null_client_id
Selects a NULL client id

struct esp_mqtt_client_config_t::credentials_t::authentication_t authentication


Client authentication

struct authentication_t
Client authentication
Fields related to client authentication by broker
For mutual authentication using TLS, user could select certificate and key, secure element or digital
signature peripheral if available.

Public Members

const char *password


MQTT password

const char *certificate


Certificate for ssl mutual authentication, not required if mutual authentication is not needed.
Must be provided with key.

size_t certificate_len
Length of the buffer pointed to by certificate.

const char *key


Private key for SSL mutual authentication, not required if mutual authentication is not needed.
If it is not NULL, also certificate has to be provided.

size_t key_len
Length of the buffer pointed to by key.

Espressif Systems 140 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

const char *key_password


Client key decryption password, not PEM nor DER, if provided key_password_len must
be correctly set.

int key_password_len
Length of the password pointed to by key_password

bool use_secure_element
Enable secure element, available in ESP32-ROOM-32SE, for SSL connection

void *ds_data
Carrier of handle for digital signature parameters, digital signature peripheral is available in
some Espressif devices.

struct network_t
Network related configuration

Public Members

int reconnect_timeout_ms
Reconnect to the broker after this value in miliseconds if auto reconnect is not disabled (defaults to
10s)

int timeout_ms
Abort network operation if it is not completed after this value, in milliseconds (defaults to 10s).

int refresh_connection_after_ms
Refresh connection after this value (in milliseconds)

bool disable_auto_reconnect
Client will reconnect to server (when errors/disconnect). Set dis-
able_auto_reconnect=true to disable

esp_transport_handle_t transport
Custom transport handle to use. Warning: The transport should be valid during the client lifetime
and is destroyed when esp_mqtt_client_destroy is called.

struct ifreq *if_name


The name of interface for data to go through. Use the default interface without setting

struct outbox_config_t
Client outbox configuration options.

Public Members

uint64_t limit
Size limit for the outbox in bytes.

Espressif Systems 141 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct session_t
MQTT Session related configuration

Public Members

struct esp_mqtt_client_config_t::session_t::last_will_t last_will


Last will configuration

bool disable_clean_session
MQTT clean session, default clean_session is true

int keepalive
MQTT keepalive, default is 120 seconds When configuring this value, keep in mind that the client
attempts to communicate with the broker at half the interval that is actually set. This conservative
approach allows for more attempts before the broker’s timeout occurs

bool disable_keepalive
Set disable_keepalive=true to turn off keep-alive mechanism, keepalive is active by de-
fault. Note: setting the config value keepalive to 0 doesn’t disable keepalive feature, but uses
a default keepalive period

esp_mqtt_protocol_ver_t protocol_ver
MQTT protocol version used for connection.

int message_retransmit_timeout
timeout for retransmitting of failed packet

struct last_will_t
Last Will and Testament message configuration.

Public Members

const char *topic


LWT (Last Will and Testament) message topic

const char *msg


LWT message, may be NULL terminated

int msg_len
LWT message length, if msg isn’t NULL terminated must have the correct length

int qos
LWT message QoS

int retain
LWT retained message flag

struct task_t
Client task configuration

Espressif Systems 142 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

int priority
MQTT task priority

int stack_size
MQTT task stack size

struct topic_t
Topic definition struct

Public Members

const char *filter


Topic filter to subscribe

int qos
Max QoS level of the subscription

Macros

MQTT_ERROR_TYPE_ESP_TLS
MQTT_ERROR_TYPE_TCP_TRANSPORT error type hold all sorts of transport layer errors, including ESP-
TLS error, but in the past only the errors from MQTT_ERROR_TYPE_ESP_TLS layer were reported, so the
ESP-TLS error type is re-defined here for backward compatibility
esp_mqtt_client_subscribe(client_handle, topic_type, qos_or_size)
Convenience macro to select subscribe function to use.
Notes:
• Usage of esp_mqtt_client_subscribe_single is the same as previous
esp_mqtt_client_subscribe, refer to it for details.

Parameters
• client_handle –MQTT client handle
• topic_type –Needs to be char* for single subscription or esp_mqtt_topic_t for
multiple topics
• qos_or_size –It’s either a qos when subscribing to a single topic or the size of the
subscription array when subscribing to multiple topics.
Returns message_id of the subscribe message on success -1 on failure -2 in case of full outbox.

Type Definitions

typedef struct esp_mqtt_client *esp_mqtt_client_handle_t

typedef enum esp_mqtt_event_id_t esp_mqtt_event_id_t


MQTT event types.
User event handler receives context data in esp_mqtt_event_t structure with
• client - MQTT client handle
• various other data depending on event type

Espressif Systems 143 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

typedef enum esp_mqtt_connect_return_code_t esp_mqtt_connect_return_code_t


MQTT connection error codes propagated via ERROR event

typedef enum esp_mqtt_error_type_t esp_mqtt_error_type_t


MQTT connection error codes propagated via ERROR event

typedef enum esp_mqtt_transport_t esp_mqtt_transport_t

typedef enum esp_mqtt_protocol_ver_t esp_mqtt_protocol_ver_t


MQTT protocol version used for connection

typedef struct esp_mqtt_error_codes esp_mqtt_error_codes_t


MQTT error code structure to be passed as a contextual information into ERROR event
Important: This structure extends esp_tls_last_error error structure and is backward compatible with
it (so might be down-casted and treated as esp_tls_last_error error, but recommended to update
applications if used this way previously)
Use this structure directly checking error_type first and then appropriate error code depending on the source
of the error:
| error_type | related member variables | note | | MQTT_ERROR_TYPE_TCP_TRANSPORT |
esp_tls_last_esp_err, esp_tls_stack_err, esp_tls_cert_verify_flags, sock_errno | Error reported from
tcp_transport/esp-tls | | MQTT_ERROR_TYPE_CONNECTION_REFUSED | connect_return_code | Inter-
nal error reported from MQTT broker on connection |

typedef struct esp_mqtt_event_t esp_mqtt_event_t


MQTT event configuration structure

typedef esp_mqtt_event_t *esp_mqtt_event_handle_t

typedef struct esp_mqtt_client_config_t esp_mqtt_client_config_t


MQTT client configuration structure

• Default values can be set via menuconfig


• All certificates and key data could be passed in PEM or DER format. PEM format must have a terminating
NULL character and the related len field set to 0. DER format requires a related len field set to the correct
length.

typedef struct topic_t esp_mqtt_topic_t


Topic definition struct

Enumerations

enum esp_mqtt_event_id_t
MQTT event types.
User event handler receives context data in esp_mqtt_event_t structure with
• client - MQTT client handle
• various other data depending on event type
Values:

Espressif Systems 144 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator MQTT_EVENT_ANY

enumerator MQTT_EVENT_ERROR
on error event, additional context: connection return code, error handle from esp_tls (if supported)

enumerator MQTT_EVENT_CONNECTED
connected event, additional context: session_present flag

enumerator MQTT_EVENT_DISCONNECTED
disconnected event

enumerator MQTT_EVENT_SUBSCRIBED
subscribed event, additional context:
• msg_id message id
• error_handle error_type in case subscribing failed
• data pointer to broker response, check for errors.
• data_len length of the data for this event

enumerator MQTT_EVENT_UNSUBSCRIBED
unsubscribed event, additional context: msg_id

enumerator MQTT_EVENT_PUBLISHED
published event, additional context: msg_id

enumerator MQTT_EVENT_DATA
data event, additional context:
• msg_id message id
• topic pointer to the received topic
• topic_len length of the topic
• data pointer to the received data
• data_len length of the data for this event
• current_data_offset offset of the current data for this event
• total_data_len total length of the data received
• retain retain flag of the message
• qos QoS level of the message
• dup dup flag of the message Note: Multiple MQTT_EVENT_DATA could be fired for one message,
if it is longer than internal buffer. In that case only first event contains topic pointer and length, other
contain data only with current data length and current data offset updating.

enumerator MQTT_EVENT_BEFORE_CONNECT
The event occurs before connecting

enumerator MQTT_EVENT_DELETED
Notification on delete of one message from the internal outbox, if the message couldn’t have been sent
and acknowledged before expiring defined in OUTBOX_EXPIRED_TIMEOUT_MS. (events are not
posted upon deletion of successfully acknowledged messages)
• This event id is posted only if MQTT_REPORT_DELETED_MESSAGES==1
• Additional context: msg_id (id of the deleted message).

Espressif Systems 145 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator MQTT_USER_EVENT
Custom event used to queue tasks into mqtt event handler All fields from the esp_mqtt_event_t type could
be used to pass an additional context data to the handler.

enum esp_mqtt_connect_return_code_t
MQTT connection error codes propagated via ERROR event
Values:

enumerator MQTT_CONNECTION_ACCEPTED
Connection accepted

enumerator MQTT_CONNECTION_REFUSE_PROTOCOL
MQTT connection refused reason: Wrong protocol

enumerator MQTT_CONNECTION_REFUSE_ID_REJECTED
MQTT connection refused reason: ID rejected

enumerator MQTT_CONNECTION_REFUSE_SERVER_UNAVAILABLE
MQTT connection refused reason: Server unavailable

enumerator MQTT_CONNECTION_REFUSE_BAD_USERNAME
MQTT connection refused reason: Wrong user

enumerator MQTT_CONNECTION_REFUSE_NOT_AUTHORIZED
MQTT connection refused reason: Wrong username or password

enum esp_mqtt_error_type_t
MQTT connection error codes propagated via ERROR event
Values:

enumerator MQTT_ERROR_TYPE_NONE

enumerator MQTT_ERROR_TYPE_TCP_TRANSPORT

enumerator MQTT_ERROR_TYPE_CONNECTION_REFUSED

enumerator MQTT_ERROR_TYPE_SUBSCRIBE_FAILED

enum esp_mqtt_transport_t
Values:

enumerator MQTT_TRANSPORT_UNKNOWN

enumerator MQTT_TRANSPORT_OVER_TCP
MQTT over TCP, using scheme: MQTT

enumerator MQTT_TRANSPORT_OVER_SSL
MQTT over SSL, using scheme: MQTTS

Espressif Systems 146 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator MQTT_TRANSPORT_OVER_WS
MQTT over Websocket, using scheme:: ws

enumerator MQTT_TRANSPORT_OVER_WSS
MQTT over Websocket Secure, using scheme: wss

enum esp_mqtt_protocol_ver_t
MQTT protocol version used for connection
Values:

enumerator MQTT_PROTOCOL_UNDEFINED

enumerator MQTT_PROTOCOL_V_3_1

enumerator MQTT_PROTOCOL_V_3_1_1

enumerator MQTT_PROTOCOL_V_5

2.2.4 ESP-TLS

Overview

The ESP-TLS component provides a simplified API interface for accessing the commonly used TLS functions. It
supports common scenarios like CA certification validation, SNI, ALPN negotiation, and non-blocking connection
among others. All the configurations can be specified in the esp_tls_cfg_t data structure. Once done, TLS
communication can be conducted using the following APIs:
• esp_tls_init(): for initializing the TLS connection handle.
• esp_tls_conn_new_sync(): for opening a new blocking TLS connection.
• esp_tls_conn_new_async(): for opening a new non-blocking TLS connection.
• esp_tls_conn_read(): for reading from the connection.
• esp_tls_conn_write(): for writing into the connection.
• esp_tls_conn_destroy(): for freeing up the connection.
Any application layer protocol like HTTP1, HTTP2, etc can be executed on top of this layer.

Application Example

Simple HTTPS example that uses ESP-TLS to establish a secure socket connection: protocols/https_request.

Tree Structure for ESP-TLS Component

├── esp_tls.c
├── esp_tls.h
├── esp_tls_mbedtls.c
├── esp_tls_wolfssl.c
└── private_include
├── esp_tls_mbedtls.h
└── esp_tls_wolfssl.h

Espressif Systems 147 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

The ESP-TLS component has a file esp-tls/esp_tls.h which contains the public API headers for the component. Inter-
nally, the ESP-TLS component operates using either MbedTLS or WolfSSL, which are SSL/TLS libraries. APIs spe-
cific to MbedTLS are present in esp-tls/private_include/esp_tls_mbedtls.h and APIs specific to WolfSSL are present
in esp-tls/private_include/esp_tls_wolfssl.h.

TLS Server Verification

ESP-TLS provides multiple options for TLS server verification on the client side. The ESP-TLS client can verify the
server by validating the peer’s server certificate or with the help of pre-shared keys. The user should select only one
of the following options in the esp_tls_cfg_t structure for TLS server verification. If no option is selected, the
client will return a fatal error by default during the TLS connection setup.
• cacert_buf and cacert_bytes: The CA certificate can be provided in a buffer to the
esp_tls_cfg_t structure. The ESP-TLS uses the CA certificate present in the buffer to verify
the server. The following variables in the esp_tls_cfg_t structure must be set.
– cacert_buf - pointer to the buffer which contains the CA certification.
– cacert_bytes - the size of the CA certificate in bytes.
• use_global_ca_store: The global_ca_store can be initialized and set at once. Then
it can be used to verify the server for all the ESP-TLS connections which have set
use_global_ca_store = true in their respective esp_tls_cfg_t structure. See
the API Reference section below for information regarding different APIs used for initializing
and setting up the global_ca_store.
• crt_bundle_attach: The ESP x509 Certificate Bundle API provides an easy way to include a
bundle of custom x509 root certificates for TLS server verification. More details can be found at
ESP x509 Certificate Bundle.
• psk_hint_key: To use pre-shared keys for server verification, CON-
FIG_ESP_TLS_PSK_VERIFICATION should be enabled in the ESP-TLS menuconfig. Then
the pointer to the PSK hint and key should be provided to the esp_tls_cfg_t structure. The
ESP-TLS will use the PSK for server verification only when no other option regarding server
verification is selected.
• skip server verification: This is an insecure option provided in the ESP-TLS for test-
ing purposes. The option can be set by enabling CONFIG_ESP_TLS_INSECURE and CON-
FIG_ESP_TLS_SKIP_SERVER_CERT_VERIFY in the ESP-TLS menuconfig. When this option
is enabled the ESP-TLS will skip server verification by default when no other options for server
verification are selected in the esp_tls_cfg_t structure.

Warning: Enabling this option comes with a potential risk of establishing a TLS connection with a
server that has a fake identity, provided that the server certificate is not provided either through API
or other mechanisms like ca_store etc.

ESP-TLS Server Cert Selection Hook

The ESP-TLS component provides an option to set the server certification selection hook when using the
MbedTLS stack. This provides an ability to configure and use a certificate selection callback during server
handshake. The callback helps to select a certificate to present to the client based on the TLS extensions
supplied in the client hello message, such as ALPN and SNI. To enable this feature, please enable CON-
FIG_ESP_TLS_SERVER_CERT_SELECT_HOOK in the ESP-TLS menuconfig.
The certificate selection callback can be configured in the esp_tls_cfg_t structure as follows:

int cert_selection_callback(mbedtls_ssl_context *ssl)


{
/* Code that the callback should execute */
return 0;
}

(continues on next page)

Espressif Systems 148 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

(continued from previous page)


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:


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

2) Add WolfSSL as an extra component in your project.


• Download WolfSSL with:

git clone --recursive https://github.com/espressif/esp-wolfssl.git

• Include ESP-WolfSSL in ESP-IDF with setting EXTRA_COMPONENT_DIRS in CMakeLists.txt of your


project as done in wolfssl/examples. For reference see Optional Project Variables in build-system..
After the above steps, you will have the option to choose WolfSSL as the underlying SSL/TLS library in the config-
uration 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 con-
figurations 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.

Espressif Systems 149 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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:
1) Add esp-cryptoauthlib in your project, for details please refer how to use esp-cryptoauthlib with ESP-IDF.
2) Enable the following menuconfig option:
menuconfig > Component config > ESP-TLS > Use Secure Element (ATECC608A) with␣
,→ESP-TLS

3) 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.
1) 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

Espressif Systems 150 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• components/esp-tls/esp_tls.h

Functions
esp_tls_t *esp_tls_init(void)
Create TLS connection.
This function allocates and initializes esp-tls structure handle.
Returns tls Pointer to esp-tls as esp-tls handle if successfully initialized, NULL if allocation error
esp_tls_t *esp_tls_conn_http_new(const char *url, const esp_tls_cfg_t *cfg)
Create a new blocking TLS/SSL connection with a given “HTTP”url.
Note: This API is present for backward compatibility reasons. Alternative function with
the same functionality is esp_tls_conn_http_new_sync (and its asynchronous version
esp_tls_conn_http_new_async)
Parameters
• url –[in] url of host.
• cfg –[in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection,
keep this NULL. For TLS connection, a pass pointer to‘esp_tls_cfg_t’. At a minimum,
this structure should be zero-initialized.
Returns pointer to esp_tls_t, or NULL if connection couldn’t be opened.
int esp_tls_conn_new_sync(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t
*tls)
Create a new blocking TLS/SSL connection.
This function establishes a TLS/SSL connection with the specified host in blocking manner.
Parameters
• hostname –[in] Hostname of the host.
• hostlen –[in] Length of hostname.
• port –[in] Port number of the host.
• cfg –[in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection,
keep this NULL. For TLS connection, a pass pointer to esp_tls_cfg_t. At a minimum, this
structure should be zero-initialized.
• tls –[in] Pointer to esp-tls as esp-tls handle.
Returns
• -1 If connection establishment fails.
• 1 If connection establishment is successful.
• 0 If connection state is in progress.
int esp_tls_conn_http_new_sync(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls)
Create a new blocking TLS/SSL connection with a given “HTTP”url.
The behaviour is same as esp_tls_conn_new_sync() API. However this API accepts host’s url.
Parameters
• url –[in] url of host.
• cfg –[in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection,
keep this NULL. For TLS connection, a pass pointer to‘esp_tls_cfg_t’. At a minimum,
this structure should be zero-initialized.
• tls –[in] Pointer to esp-tls as esp-tls handle.
Returns
• -1 If connection establishment fails.
• 1 If connection establishment is successful.
• 0 If connection state is in progress.
int esp_tls_conn_new_async(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t
*tls)
Create a new non-blocking TLS/SSL connection.

Espressif Systems 151 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

This function initiates a non-blocking TLS/SSL connection with the specified host, but due to its non-blocking
nature, it doesn’t wait for the connection to get established.
Parameters
• hostname –[in] Hostname of the host.
• hostlen –[in] Length of hostname.
• port –[in] Port number of the host.
• cfg –[in] TLS configuration as esp_tls_cfg_t. non_block member of this structure
should be set to be true.
• tls –[in] pointer to esp-tls as esp-tls handle.
Returns
• -1 If connection establishment fails.
• 0 If connection establishment is in progress.
• 1 If connection establishment is successful.
int esp_tls_conn_http_new_async(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls)
Create a new non-blocking TLS/SSL connection with a given “HTTP”url.
The behaviour is same as esp_tls_conn_new_async() API. However this API accepts host’s url.
Parameters
• url –[in] url of host.
• cfg –[in] TLS configuration as esp_tls_cfg_t.
• tls –[in] pointer to esp-tls as esp-tls handle.
Returns
• -1 If connection establishment fails.
• 0 If connection establishment is in progress.
• 1 If connection establishment is successful.
ssize_t esp_tls_conn_write(esp_tls_t *tls, const void *data, size_t datalen)
Write from buffer ‘data’into specified tls connection.
Parameters
• tls –[in] pointer to esp-tls as esp-tls handle.
• data –[in] Buffer from which data will be written.
• datalen –[in] Length of data buffer.
Returns
• >=0 if write operation was successful, the return value is the number of bytes actually
written to the TLS/SSL connection.
• <0 if write operation was not successful, because either an error occured or an action must
be taken by the calling process.
• ESP_TLS_ERR_SSL_WANT_READ/ ESP_TLS_ERR_SSL_WANT_WRITE. if the
handshake is incomplete and waiting for data to be available for reading. In this case this
functions needs to be called again when the underlying transport is ready for operation.
ssize_t esp_tls_conn_read(esp_tls_t *tls, void *data, size_t datalen)
Read from specified tls connection into the buffer ‘data’.
Parameters
• tls –[in] pointer to esp-tls as esp-tls handle.
• data –[in] Buffer to hold read data.
• datalen –[in] Length of data buffer.
Returns
• >0 if read operation was successful, the return value is the number of bytes actually read
from the TLS/SSL connection.
• 0 if read operation was not successful. The underlying connection was closed.
• <0 if read operation was not successful, because either an error occured or an action must
be taken by the calling process.
int esp_tls_conn_destroy(esp_tls_t *tls)
Close the TLS/SSL connection and free any allocated resources.

Espressif Systems 152 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

This function should be called to close each tls connection opened with esp_tls_conn_new_sync() (or
esp_tls_conn_http_new_sync()) and esp_tls_conn_new_async() (or esp_tls_conn_http_new_async()) APIs.
Parameters tls –[in] pointer to esp-tls as esp-tls handle.
Returns - 0 on success
• -1 if socket error or an invalid argument
ssize_t esp_tls_get_bytes_avail(esp_tls_t *tls)
Return the number of application data bytes remaining to be read from the current record.
This API is a wrapper over mbedtls’s mbedtls_ssl_get_bytes_avail() API.
Parameters tls –[in] pointer to esp-tls as esp-tls handle.
Returns
• -1 in case of invalid arg
• bytes available in the application data record read buffer
esp_err_t esp_tls_get_conn_sockfd(esp_tls_t *tls, int *sockfd)
Returns the connection socket file descriptor from esp_tls session.
Parameters
• tls –[in] handle to esp_tls context
• sockfd –[out] int pointer to sockfd value.
Returns - ESP_OK on success and value of sockfd will be updated with socket file descriptor for
connection
• ESP_ERR_INVALID_ARG if (tls == NULL || sockfd == NULL)
esp_err_t esp_tls_set_conn_sockfd(esp_tls_t *tls, int sockfd)
Sets the connection socket file descriptor for the esp_tls session.
Parameters
• tls –[in] handle to esp_tls context
• sockfd –[in] sockfd value to set.
Returns - ESP_OK on success and value of sockfd for the tls connection shall updated withthe
provided value
• ESP_ERR_INVALID_ARG if (tls == NULL || sockfd < 0)
esp_err_t esp_tls_get_conn_state(esp_tls_t *tls, esp_tls_conn_state_t *conn_state)
Gets the connection state for the esp_tls session.
Parameters
• tls –[in] handle to esp_tls context
• conn_state –[out] pointer to the connection state value.
Returns - ESP_OK on success and value of sockfd for the tls connection shall updated withthe
provided value
• ESP_ERR_INVALID_ARG (Invalid arguments)
esp_err_t esp_tls_set_conn_state(esp_tls_t *tls, esp_tls_conn_state_t conn_state)
Sets the connection state for the esp_tls session.
Parameters
• tls –[in] handle to esp_tls context
• conn_state –[in] connection state value to set.
Returns - ESP_OK on success and value of sockfd for the tls connection shall updated withthe
provided value
• ESP_ERR_INVALID_ARG (Invalid arguments)
void *esp_tls_get_ssl_context(esp_tls_t *tls)
Returns the ssl context.
Parameters tls –[in] handle to esp_tls context
Returns - ssl_ctx pointer to ssl context of underlying TLS layer on success
• NULL in case of error

Espressif Systems 153 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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 be-
fore calling esp_tls_conn_new().
Parameters
• cacert_pem_buf –[in] Buffer which has certificates in pem format. This buffer is
used for creating a global CA store, which can be used by other tls connections.
• cacert_pem_bytes –[in] Length of the buffer.
Returns
• ESP_OK if adding certificates was successful.
• Other if an error occured or an action must be taken by the calling process.
void esp_tls_free_global_ca_store(void)
Free the global CA store currently being used.
The memory being used by the global CA store to store all the parsed certificates is freed up. The application
can call this API if it no longer needs the global CA store.
esp_err_t esp_tls_get_and_clear_last_error(esp_tls_error_handle_t h, int *esp_tls_code, int
*esp_tls_flags)
Returns last error in esp_tls with detailed mbedtls related error codes. The error information is cleared internally
upon return.
Parameters
• h –[in] esp-tls error handle.
• esp_tls_code –[out] last error code returned from mbedtls api (set to zero if none)
This pointer could be NULL if caller does not care about esp_tls_code
• esp_tls_flags –[out] last certification verification flags (set to zero if none) This
pointer could be NULL if caller does not care about esp_tls_code
Returns
• ESP_ERR_INVALID_STATE if invalid parameters
• ESP_OK (0) if no error occurred
• specific error code (based on ESP_ERR_ESP_TLS_BASE) otherwise
esp_err_t esp_tls_get_and_clear_error_type(esp_tls_error_handle_t h, esp_tls_error_type_t
err_type, int *error_code)
Returns the last error captured in esp_tls of a specific type The error information is cleared internally upon
return.
Parameters
• h –[in] esp-tls error handle.
• err_type –[in] specific error type
• error_code –[out] last error code returned from mbedtls api (set to zero if none) This
pointer could be NULL if caller does not care about esp_tls_code
Returns
• ESP_ERR_INVALID_STATE if invalid parameters

Espressif Systems 154 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• ESP_OK if a valid error returned and was cleared


esp_err_t esp_tls_get_error_handle(esp_tls_t *tls, esp_tls_error_handle_t *error_handle)
Returns the ESP-TLS error_handle.
Parameters
• tls –[in] handle to esp_tls context
• error_handle –[out] pointer to the error handle.
Returns
• ESP_OK on success and error_handle will be updated with the ESP-TLS error handle.
• ESP_ERR_INVALID_ARG if (tls == NULL || error_handle == NULL)
mbedtls_x509_crt *esp_tls_get_global_ca_store(void)
Get the pointer to the global CA store currently being used.
The application must first call esp_tls_set_global_ca_store(). Then the same CA store could be used by the
application for APIs other than esp_tls.

Note: Modifying the pointer might cause a failure in verifying the certificates.

Returns
• Pointer to the global CA store currently being used if successful.
• NULL if there is no global CA store set.

const int *esp_tls_get_ciphersuites_list(void)


Get supported TLS ciphersuites list.
See https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4 for the list of ci-
phersuites
Returns Pointer to a zero-terminated array of IANA identifiers of TLS ciphersuites.
esp_err_t esp_tls_plain_tcp_connect(const char *host, int hostlen, int port, const esp_tls_cfg_t *cfg,
esp_tls_error_handle_t error_handle, int *sockfd)
Creates a plain TCP connection, returning a valid socket fd on success or an error handle.
Parameters
• host –[in] Hostname of the host.
• hostlen –[in] Length of hostname.
• port –[in] Port number of the host.
• cfg –[in] ESP-TLS configuration as esp_tls_cfg_t.
• error_handle –[out] ESP-TLS error handle holding potential errors occurred during
connection
• sockfd –[out] Socket descriptor if successfully connected on TCP layer
Returns ESP_OK on success ESP_ERR_INVALID_ARG if invalid output parameters ESP-TLS
based error codes on failure

Structures

struct psk_key_hint
ESP-TLS preshared key and hint structure.

Public Members

const uint8_t *key


key in PSK authentication mode in binary format

Espressif Systems 155 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

const size_t key_size


length of the key

const char *hint


hint in PSK authentication mode in string format

struct tls_keep_alive_cfg
esp-tls client session ticket ctx
Keep alive parameters structure

Public Members

bool keep_alive_enable
Enable keep-alive timeout

int keep_alive_idle
Keep-alive idle time (second)

int keep_alive_interval
Keep-alive interval time (second)

int keep_alive_count
Keep-alive packet retry send count

struct esp_tls_cfg
ESP-TLS configuration parameters.

Note: Note about format of certificates:


• This structure includes certificates of a Certificate Authority, of client or server as well as private keys,
which may be of PEM or DER format. In case of PEM format, the buffer must be NULL terminated
(with NULL character included in certificate size).
• Certificate Authority’s certificate may be a chain of certificates in case of PEM format, but could be
only one certificate in case of DER format
• Variables names of certificates and private key buffers and sizes are defined as unions providing backward
compatibility for legacy *_pem_buf and *_pem_bytes names which suggested only PEM format was
supported. It is encouraged to use generic names such as cacert_buf and cacert_bytes.

Public Members

const char **alpn_protos


Application protocols required for HTTP2. If HTTP2/ALPN support is required, a list of protocols that
should be negotiated. The format is length followed by protocol name. For the most common cases the
following is ok: const char **alpn_protos = { “h2”, NULL };
• where ‘h2’is the protocol name

const unsigned char *cacert_buf


Certificate Authority’s certificate in a buffer. Format may be PEM or DER, depending on mbedtls-
support This buffer should be NULL terminated in case of PEM

Espressif Systems 156 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

const unsigned char *cacert_pem_buf


CA certificate buffer legacy name

unsigned int cacert_bytes


Size of Certificate Authority certificate pointed to by cacert_buf (including NULL-terminator in case of
PEM format)

unsigned int cacert_pem_bytes


Size of Certificate Authority certificate legacy name

const unsigned char *clientcert_buf


Client certificate in a buffer Format may be PEM or DER, depending on mbedtls-support This buffer
should be NULL terminated in case of PEM

const unsigned char *clientcert_pem_buf


Client certificate legacy name

unsigned int clientcert_bytes


Size of client certificate pointed to by clientcert_pem_buf (including NULL-terminator in case of PEM
format)

unsigned int clientcert_pem_bytes


Size of client certificate legacy name

const unsigned char *clientkey_buf


Client key in a buffer Format may be PEM or DER, depending on mbedtls-support This buffer should be
NULL terminated in case of PEM

const unsigned char *clientkey_pem_buf


Client key legacy name

unsigned int clientkey_bytes


Size of client key pointed to by clientkey_pem_buf (including NULL-terminator in case of PEM format)

unsigned int clientkey_pem_bytes


Size of client key legacy name

const unsigned char *clientkey_password


Client key decryption password string

unsigned int clientkey_password_len


String length of the password pointed to by clientkey_password

bool use_ecdsa_peripheral
Use the ECDSA peripheral for the private key operations

uint8_t ecdsa_key_efuse_blk
The efuse block where the ECDSA key is stored

Espressif Systems 157 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

bool non_block
Configure non-blocking mode. If set to true the underneath socket will be configured in non blocking
mode after tls session is established

bool use_secure_element
Enable this option to use secure element or atecc608a chip ( Integrated with ESP32-WROOM-32SE )

int timeout_ms
Network timeout in milliseconds. Note: If this value is not set, by default the timeout is set to 10 seconds.
If you wish that the session should wait indefinitely then please use a larger value e.g., INT32_MAX

bool use_global_ca_store
Use a global ca_store for all the connections in which this bool is set.

const char *common_name


If non-NULL, server certificate CN must match this name. If NULL, server certificate CN must match
hostname.

bool skip_common_name
Skip any validation of server certificate CN field

tls_keep_alive_cfg_t *keep_alive_cfg
Enable TCP keep-alive timeout for SSL connection

const psk_hint_key_t *psk_hint_key


Pointer to PSK hint and key. if not NULL (and certificates are NULL) then PSK authentication is enabled
with configured setup. Important note: the pointer must be valid for connection

esp_err_t (*crt_bundle_attach)(void *conf)


Function pointer to esp_crt_bundle_attach. Enables the use of certification bundle for server verification,
must be enabled in menuconfig

void *ds_data
Pointer for digital signature peripheral context

bool is_plain_tcp
Use non-TLS connection: When set to true, the esp-tls uses plain TCP transport rather then
TLS/SSL connection. Note, that it is possible to connect using a plain tcp transport directly with
esp_tls_plain_tcp_connect() API

struct ifreq *if_name


The name of interface for data to go through. Use the default interface without setting

esp_tls_addr_family_t addr_family
The address family to use when connecting to a host.

const int *ciphersuites_list


Pointer to a zero-terminated array of IANA identifiers of TLS ciphersuites. Please check the list validity
by esp_tls_get_ciphersuites_list() API

Espressif Systems 158 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Type Definitions

typedef enum esp_tls_conn_state esp_tls_conn_state_t


ESP-TLS Connection State.

typedef enum esp_tls_role esp_tls_role_t

typedef struct psk_key_hint psk_hint_key_t


ESP-TLS preshared key and hint structure.

typedef struct tls_keep_alive_cfg tls_keep_alive_cfg_t


esp-tls client session ticket ctx
Keep alive parameters structure

typedef enum esp_tls_addr_family esp_tls_addr_family_t

typedef struct esp_tls_cfg esp_tls_cfg_t


ESP-TLS configuration parameters.

Note: Note about format of certificates:


• This structure includes certificates of a Certificate Authority, of client or server as well as private keys,
which may be of PEM or DER format. In case of PEM format, the buffer must be NULL terminated
(with NULL character included in certificate size).
• Certificate Authority’s certificate may be a chain of certificates in case of PEM format, but could be
only one certificate in case of DER format
• Variables names of certificates and private key buffers and sizes are defined as unions providing backward
compatibility for legacy *_pem_buf and *_pem_bytes names which suggested only PEM format was
supported. It is encouraged to use generic names such as cacert_buf and cacert_bytes.

typedef struct esp_tls esp_tls_t

Enumerations

enum esp_tls_conn_state
ESP-TLS Connection State.
Values:

enumerator ESP_TLS_INIT

enumerator ESP_TLS_CONNECTING

enumerator ESP_TLS_HANDSHAKE

enumerator ESP_TLS_FAIL

enumerator ESP_TLS_DONE

enum esp_tls_role
Values:

Espressif Systems 159 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_TLS_CLIENT

enumerator ESP_TLS_SERVER

enum esp_tls_addr_family
Values:

enumerator ESP_TLS_AF_UNSPEC
Unspecified address family.

enumerator ESP_TLS_AF_INET
IPv4 address family.

enumerator ESP_TLS_AF_INET6
IPv6 address family.

Header File
• components/esp-tls/esp_tls_errors.h

Structures

struct esp_tls_last_error
Error structure containing relevant errors in case tls error occurred.

Public Members

esp_err_t last_error
error code (based on ESP_ERR_ESP_TLS_BASE) of the last occurred error

int esp_tls_error_code
esp_tls error code from last esp_tls failed api

int esp_tls_flags
last certification verification flags

Macros

ESP_ERR_ESP_TLS_BASE
Starting number of ESP-TLS error codes

ESP_ERR_ESP_TLS_CANNOT_RESOLVE_HOSTNAME
Error if hostname couldn’t be resolved upon tls connection

ESP_ERR_ESP_TLS_CANNOT_CREATE_SOCKET
Failed to create socket

ESP_ERR_ESP_TLS_UNSUPPORTED_PROTOCOL_FAMILY
Unsupported protocol family

Espressif Systems 160 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_ERR_ESP_TLS_FAILED_CONNECT_TO_HOST
Failed to connect to host

ESP_ERR_ESP_TLS_SOCKET_SETOPT_FAILED
failed to set/get socket option

ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT
new connection in esp_tls_low_level_conn connection timeouted

ESP_ERR_ESP_TLS_SE_FAILED

ESP_ERR_ESP_TLS_TCP_CLOSED_FIN

ESP_ERR_MBEDTLS_CERT_PARTLY_OK
mbedtls parse certificates was partly successful

ESP_ERR_MBEDTLS_CTR_DRBG_SEED_FAILED
mbedtls api returned error

ESP_ERR_MBEDTLS_SSL_SET_HOSTNAME_FAILED
mbedtls api returned error

ESP_ERR_MBEDTLS_SSL_CONFIG_DEFAULTS_FAILED
mbedtls api returned error

ESP_ERR_MBEDTLS_SSL_CONF_ALPN_PROTOCOLS_FAILED
mbedtls api returned error

ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED
mbedtls api returned error

ESP_ERR_MBEDTLS_SSL_CONF_OWN_CERT_FAILED
mbedtls api returned error

ESP_ERR_MBEDTLS_SSL_SETUP_FAILED
mbedtls api returned error

ESP_ERR_MBEDTLS_SSL_WRITE_FAILED
mbedtls api returned error

ESP_ERR_MBEDTLS_PK_PARSE_KEY_FAILED
mbedtls api returned failed

ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED
mbedtls api returned failed

ESP_ERR_MBEDTLS_SSL_CONF_PSK_FAILED
mbedtls api returned failed

Espressif Systems 161 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_ERR_MBEDTLS_SSL_TICKET_SETUP_FAILED
mbedtls api returned failed

ESP_ERR_WOLFSSL_SSL_SET_HOSTNAME_FAILED
wolfSSL api returned error

ESP_ERR_WOLFSSL_SSL_CONF_ALPN_PROTOCOLS_FAILED
wolfSSL api returned error

ESP_ERR_WOLFSSL_CERT_VERIFY_SETUP_FAILED
wolfSSL api returned error

ESP_ERR_WOLFSSL_KEY_VERIFY_SETUP_FAILED
wolfSSL api returned error

ESP_ERR_WOLFSSL_SSL_HANDSHAKE_FAILED
wolfSSL api returned failed

ESP_ERR_WOLFSSL_CTX_SETUP_FAILED
wolfSSL api returned failed

ESP_ERR_WOLFSSL_SSL_SETUP_FAILED
wolfSSL api returned failed

ESP_ERR_WOLFSSL_SSL_WRITE_FAILED
wolfSSL api returned failed

ESP_TLS_ERR_SSL_WANT_READ
Definition of errors reported from IO API (potentially non-blocking) in case of error:
• esp_tls_conn_read()
• esp_tls_conn_write()

ESP_TLS_ERR_SSL_WANT_WRITE

ESP_TLS_ERR_SSL_TIMEOUT

Type Definitions

typedef struct esp_tls_last_error *esp_tls_error_handle_t

typedef struct esp_tls_last_error esp_tls_last_error_t


Error structure containing relevant errors in case tls error occurred.

Enumerations

enum esp_tls_error_type_t
Definition of different types/sources of error codes reported from different components
Values:

Espressif Systems 162 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_TLS_ERR_TYPE_UNKNOWN

enumerator ESP_TLS_ERR_TYPE_SYSTEM
System error &#8212; errno

enumerator ESP_TLS_ERR_TYPE_MBEDTLS
Error code from mbedTLS library

enumerator ESP_TLS_ERR_TYPE_MBEDTLS_CERT_FLAGS
Certificate flags defined in mbedTLS

enumerator ESP_TLS_ERR_TYPE_ESP
ESP-IDF error type &#8212; esp_err_t

enumerator ESP_TLS_ERR_TYPE_WOLFSSL
Error code from wolfSSL library

enumerator ESP_TLS_ERR_TYPE_WOLFSSL_CERT_FLAGS
Certificate flags defined in wolfSSL

enumerator ESP_TLS_ERR_TYPE_MAX
Last err type &#8212; invalid entry

2.2.5 ESP HTTP Client

Overview

esp_http_client component provides a set of APIs for making HTTP/S requests from ESP-IDF applications.
The steps to use these APIs are as follows:
• esp_http_client_init(): Creates an esp_http_client_handle_t instance, i.e., an HTTP
client handle based on the given esp_http_client_config_t configuration. This function must be the
first to be called; default values are assumed for the configuration values that are not explicitly defined by the
user.
• esp_http_client_perform(): Performs all operations of the esp_http_client - opening
the connection, exchanging data, and closing the connection (as required), while blocking the current
task before its completion. All related events are invoked through the event handler (as specified in
esp_http_client_config_t).
• esp_http_client_cleanup(): Closes the connection (if any) and frees up all the memory allocated
to the HTTP client instance. This must be the last function to be called after the completion of operations.

Application Example

Simple example that uses ESP HTTP Client to make HTTP/S requests can be found at protocols/esp_http_client.

Basic HTTP Request

Check out the example functions http_rest_with_url and http_rest_with_hostname_path in the


application example for implementation details.

Espressif Systems 163 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Persistent Connections

Persistent connection means that the HTTP client can re-use the same connection for several exchanges. If the server
does not request to close the connection with the Connection: close header, the connection is not dropped
but is instead kept open and used for further requests.
To allow ESP HTTP client to take full advantage of persistent connections, one should make as many requests
as possible using the same handle instance. Check out the example functions http_rest_with_url and
http_rest_with_hostname_path in the application example. Here, once the connection is created, multiple
requests (GET, POST, PUT, etc.) are made before the connection is closed.

Use Secure Element (ATECC608) for TLS A secure element (ATECC608) can be also used for the underlying
TLS connection in the HTTP client connection. Please refer to the ATECC608A (Secure Element) with ESP-
TLS section in the ESP-TLS documentation for more details. The secure element support has to be first enabled in
menuconfig through CONFIG_ESP_TLS_USE_SECURE_ELEMENT. Then the HTTP client can be configured to use
secure element as follows:
esp_http_client_config_t cfg = {
/* other configurations options */
.use_secure_element = true,
};

HTTPS Request

ESP HTTP client supports SSL connections using mbedTLS, with the url configuration starting with https
scheme or transport_type set to HTTP_TRANSPORT_OVER_SSL. HTTPS support can be configured via
CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS (enabled by default).

Note: While making HTTPS requests, if server verification is needed, an additional root certificate (in PEM format)
needs to be provided to the cert_pem member in the esp_http_client_config_t configuration. Users
can also use the ESP x509 Certificate Bundle for server verification using the crt_bundle_attach
member of the esp_http_client_config_t configuration.

Check out the example functions https_with_url and https_with_hostname_path in the application
example for implementation details of the above note.

HTTP Stream

Some applications need to open the connection and control the exchange of data actively (data streaming). In such
cases, the application flow is different from regular requests. Example flow is given below:
• esp_http_client_init(): Create a HTTP client handle.
• esp_http_client_set_* or esp_http_client_delete_*: Modify the HTTP connection pa-
rameters (optional).
• esp_http_client_open(): Open the HTTP connection with write_len parameter (content length
that needs to be written to server), set write_len=0 for read-only connection.
• esp_http_client_write(): Write data to server with a maximum length equal to write_len of
esp_http_client_open() function; no need to call this function for write_len=0.
• esp_http_client_fetch_headers(): Read the HTTP Server response headers, after sending the
request headers and server data (if any). Returns the content-length from the server and can be suc-
ceeded by esp_http_client_get_status_code() for getting the HTTP status of the connection.
• esp_http_client_read(): Read the HTTP stream.
• esp_http_client_close(): Close the connection.
• esp_http_client_cleanup(): Release allocated resources.
Check out the example function http_perform_as_stream_reader in the application example for imple-
mentation details.

Espressif Systems 164 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

HTTP Authentication

ESP HTTP client supports both Basic and Digest Authentication.


• Users can provide the username and password in the url or the username and pass-
word members of the esp_http_client_config_t configuration. For auth_type =
HTTP_AUTH_TYPE_BASIC, the HTTP client takes only one perform operation to pass the authen-
tication process.
• If auth_type = HTTP_AUTH_TYPE_NONE, but the username and password fields are present
in the configuration, the HTTP client takes two perform operations. The client will receive the 401
Unauthorized header in its first attempt to connect to the server. Based on this information, it decides
which authentication method to choose and performs it in the second operation.
• Check out the example functions http_auth_basic, http_auth_basic_redirect (for Basic
authentication) and http_auth_digest (for Digest authentication) in the application example for
implementation details.

Examples of Authentication Configuration


• Authentication with URI

esp_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 entry

esp_http_client_config_t config = {
.url = "http://httpbin.org/basic-auth/user/passwd",
.username = "user",
.password = "passwd",
.auth_type = HTTP_AUTH_TYPE_BASIC,
};

Event Handling

ESP HTTP Client supports event handling by triggering an event handler corresponding to the event which takes
place. esp_http_client_event_id_t contains all the events which could occur while performing an HTTP
request using the ESP HTTP Client.
To enable event handling, you just need to set a callback function using the
esp_http_client_config_t::event_handler member.

ESP HTTP Client Diagnostic Information

Diagnostic information could be helpful to gain insights into a problem. In the case of ESP HTTP Client, the di-
agnostic information can be collected by registering an event handler with the Event Loop library. This feature has
been added by keeping in mind the ESP Insights framework which collects the diagnostic information. However, this
feature can also be used without any dependency on the ESP Insights framework for the diagnostic purpose. Event
handler can be registered to the event loop using the esp_event_handler_register() function.
Expected data types for different HTTP Client events in the event loop are as follows:
• HTTP_EVENT_ERROR : esp_http_client_handle_t
• HTTP_EVENT_ON_CONNECTED : esp_http_client_handle_t
• HTTP_EVENT_HEADERS_SENT : esp_http_client_handle_t
• HTTP_EVENT_ON_HEADER : esp_http_client_handle_t
• HTTP_EVENT_ON_DATA : esp_http_client_on_data_t
• HTTP_EVENT_ON_FINISH : esp_http_client_handle_t
• HTTP_EVENT_DISCONNECTED : esp_http_client_handle_t

Espressif Systems 165 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• 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 be-
tween 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
• components/esp_http_client/include/esp_http_client.h

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_init and all the options calls are made, and will perform
the transfer as described in the options. It must be called with the same esp_http_client_handle_t as input as
the esp_http_client_init call returned. esp_http_client_perform performs the entire request in either blocking
or non-blocking manner. By default, the API performs request in a blocking manner and returns when done,
or if it failed, and in non-blocking manner, it returns if EAGAIN/EWOULDBLOCK or EINPROGRESS is
encountered, or if it failed. And in case of non-blocking request, the user may call this API multiple times
unless request & response is complete or there is a failure. To enable non-blocking esp_http_client_perform(),
is_async member of esp_http_client_config_t must be set while making a call to esp_http_client_init() API.
You can do any amount of calls to esp_http_client_perform while using the same esp_http_client_handle_t.
The underlying connection may be kept open if the server allows it. If you intend to transfer more than one
file, you are even encouraged to do so. esp_http_client will then attempt to re-use the same connection for
the following transfers, thus making the operations faster, less CPU intense and using less network resources.
Just note that you will have to use esp_http_client_set_** between the invokes to set options for the
following esp_http_client_perform.

Note: You must never call this function simultaneously from two places using the same client han-
dle. Let the function return first before invoking it another time. If you want parallel transfers,
you must use several esp_http_client_handle_t. This function include esp_http_client_open
-> esp_http_client_write -> esp_http_client_fetch_headers ->
esp_http_client_read (and option) esp_http_client_close.

Parameters client –The esp_http_client handle


Returns
• ESP_OK on successful
• ESP_FAIL on error

esp_err_t esp_http_client_cancel_request(esp_http_client_handle_t client)


Cancel an ongoing HTTP request. This API closes the current socket and opens a new socket with the same
esp_http_client context.
Parameters client –The esp_http_client handle
Returns

Espressif Systems 166 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• ESP_OK on successful
• ESP_FAIL on error
• ESP_ERR_INVALID_ARG
• ESP_ERR_INVALID_STATE
esp_err_t esp_http_client_set_url(esp_http_client_handle_t client, const char *url)
Set URL for client, when performing this behavior, the options in the URL will replace the old ones.
Parameters
• client –[in] The esp_http_client handle
• url –[in] The url
Returns
• ESP_OK
• ESP_FAIL
esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client, const char *data, int len)
Set post data, this function must be called before esp_http_client_perform. Note: The data param-
eter passed to this function is a pointer and this function will not copy the data.
Parameters
• client –[in] The esp_http_client handle
• data –[in] post data pointer
• len –[in] post length
Returns
• ESP_OK
• ESP_FAIL
int esp_http_client_get_post_field(esp_http_client_handle_t client, char **data)
Get current post field information.
Parameters
• client –[in] The client
• data –[out] Point to post data pointer
Returns Size of post data
esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char
*value)
Set http request header, this function must be called after esp_http_client_init and before any perform function.
Parameters
• client –[in] The esp_http_client handle
• key –[in] The header key
• value –[in] The header value
Returns
• ESP_OK
• ESP_FAIL
esp_err_t esp_http_client_get_header(esp_http_client_handle_t client, const char *key, char **value)
Get http request header. The value parameter will be set to NULL if there is no header which is same as the
key specified, otherwise the address of header value will be assigned to value parameter. This function must
be called after esp_http_client_init.
Parameters
• client –[in] The esp_http_client handle
• key –[in] The header key
• value –[out] The header value
Returns
• ESP_OK
• ESP_FAIL

Espressif Systems 167 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_http_client_get_username(esp_http_client_handle_t client, char **value)


Get http request username. The address of username buffer will be assigned to value parameter. This function
must be called after esp_http_client_init.
Parameters
• client –[in] The esp_http_client handle
• value –[out] The username value
Returns
• ESP_OK
• ESP_ERR_INVALID_ARG
esp_err_t esp_http_client_set_username(esp_http_client_handle_t client, const char *username)
Set http request username. The value of username parameter will be assigned to username buffer. If the
username parameter is NULL then username buffer will be freed.
Parameters
• client –[in] The esp_http_client handle
• username –[in] The username value
Returns
• ESP_OK
• ESP_ERR_INVALID_ARG
esp_err_t esp_http_client_get_password(esp_http_client_handle_t client, char **value)
Get http request password. The address of password buffer will be assigned to value parameter. This function
must be called after esp_http_client_init.
Parameters
• client –[in] The esp_http_client handle
• value –[out] The password value
Returns
• ESP_OK
• ESP_ERR_INVALID_ARG
esp_err_t esp_http_client_set_password(esp_http_client_handle_t client, const char *password)
Set http request password. The value of password parameter will be assigned to password buffer. If the
password parameter is NULL then password buffer will be freed.
Parameters
• client –[in] The esp_http_client handle
• password –[in] The password value
Returns
• ESP_OK
• ESP_ERR_INVALID_ARG
esp_err_t esp_http_client_set_authtype(esp_http_client_handle_t client, esp_http_client_auth_type_t
auth_type)
Set http request auth_type.
Parameters
• client –[in] The esp_http_client handle
• auth_type –[in] The esp_http_client auth type
Returns
• ESP_OK
• ESP_ERR_INVALID_ARG
esp_err_t esp_http_client_get_user_data(esp_http_client_handle_t client, void **data)
Get http request user_data. The value stored from the esp_http_client_config_t will be written to the address
passed into data.
Parameters
• client –[in] The esp_http_client handle
• data –[out] A pointer to the pointer that will be set to user_data.

Espressif Systems 168 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Returns
• ESP_OK
• ESP_ERR_INVALID_ARG
esp_err_t esp_http_client_set_user_data(esp_http_client_handle_t client, void *data)
Set http request user_data. The value passed in +data+ will be available during event callbacks. No memory
management will be performed on the user’s behalf.
Parameters
• client –[in] The esp_http_client handle
• data –[in] The pointer to the user data
Returns
• ESP_OK
• ESP_ERR_INVALID_ARG
int esp_http_client_get_errno(esp_http_client_handle_t client)
Get HTTP client session errno.
Parameters client –[in] The esp_http_client handle
Returns
• (-1) if invalid argument
• errno
esp_err_t esp_http_client_set_method(esp_http_client_handle_t client, esp_http_client_method_t
method)
Set http request method.
Parameters
• client –[in] The esp_http_client handle
• method –[in] The method
Returns
• ESP_OK
• ESP_ERR_INVALID_ARG
esp_err_t esp_http_client_set_timeout_ms(esp_http_client_handle_t client, int timeout_ms)
Set http request timeout.
Parameters
• client –[in] The esp_http_client handle
• timeout_ms –[in] The timeout value
Returns
• ESP_OK
• ESP_ERR_INVALID_ARG
esp_err_t esp_http_client_delete_header(esp_http_client_handle_t client, const char *key)
Delete http request header.
Parameters
• client –[in] The esp_http_client handle
• key –[in] The key
Returns
• ESP_OK
• ESP_FAIL
esp_err_t esp_http_client_open(esp_http_client_handle_t client, int write_len)
This function will be open the connection, write all header strings and return.
Parameters
• client –[in] The esp_http_client handle
• write_len –[in] HTTP Content length need to write to the server
Returns
• ESP_OK
• ESP_FAIL

Espressif Systems 169 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

int esp_http_client_write(esp_http_client_handle_t client, const char *buffer, int len)


This function will write data to the HTTP connection previously opened by esp_http_client_open()
Parameters
• client –[in] The esp_http_client handle
• buffer –The buffer
• len –[in] This value must not be larger than the write_len parameter provided to
esp_http_client_open()
Returns
• (-1) if any errors
• Length of data written
int64_t esp_http_client_fetch_headers(esp_http_client_handle_t client)
This function need to call after esp_http_client_open, it will read from http stream, process all receive headers.
Parameters client –[in] The esp_http_client handle
Returns
• (0) if stream doesn’t contain content-length header, or chunked encoding (checked by
esp_http_client_is_chunked response)
• (-1: ESP_FAIL) if any errors
• (-ESP_ERR_HTTP_EAGAIN = -0x7007) if call is timed-out before any data was ready
• Download data length defined by content-length header
bool esp_http_client_is_chunked_response(esp_http_client_handle_t client)
Check response data is chunked.
Parameters client –[in] The esp_http_client handle
Returns true or false
int esp_http_client_read(esp_http_client_handle_t client, char *buffer, int len)
Read data from http stream.

Note: (-ESP_ERR_HTTP_EAGAIN = -0x7007) is returned when call is timed-out before any data was ready

Parameters
• client –[in] The esp_http_client handle
• buffer –The buffer
• len –[in] The length
Returns
• (-1) if any errors
• Length of data was read

int esp_http_client_get_status_code(esp_http_client_handle_t client)


Get http response status code, the valid value if this function invoke after esp_http_client_perform
Parameters client –[in] The esp_http_client handle
Returns Status code
int64_t esp_http_client_get_content_length(esp_http_client_handle_t client)
Get http response content length (from header Content-Length) the valid value if this function invoke after
esp_http_client_perform
Parameters client –[in] The esp_http_client handle
Returns
• (-1) Chunked transfer
• Content-Length value as bytes
esp_err_t esp_http_client_close(esp_http_client_handle_t client)
Close http connection, still kept all http request resources.
Parameters client –[in] The esp_http_client handle

Espressif Systems 170 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Returns
• ESP_OK
• ESP_FAIL
esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client)
This function must be the last function to call for an session. It is the opposite of the esp_http_client_init
function and must be called with the same handle as input that a esp_http_client_init call returned. This might
close all connections this handle has used and possibly has kept open until now. Don’t call this function if
you intend to transfer more files, re-using handles is a key to good performance with esp_http_client.
Parameters client –[in] The esp_http_client handle
Returns
• ESP_OK
• ESP_FAIL
esp_http_client_transport_t esp_http_client_get_transport_type(esp_http_client_handle_t client)
Get transport type.
Parameters client –[in] The esp_http_client handle
Returns
• HTTP_TRANSPORT_UNKNOWN
• HTTP_TRANSPORT_OVER_TCP
• HTTP_TRANSPORT_OVER_SSL
esp_err_t esp_http_client_set_redirection(esp_http_client_handle_t client)
Set redirection URL. When received the 30x code from the server, the client stores the redirect URL pro-
vided by the server. This function will set the current URL to redirect to enable client to execute the redirec-
tion request. When disable_auto_redirect is set, the client will not call this function but the event
HTTP_EVENT_REDIRECT will be dispatched giving the user contol over the redirection event.
Parameters client –[in] The esp_http_client handle
Returns
• ESP_OK
• ESP_FAIL
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_read
multiple times till the end of data is reached or till the buffer gets full.
Parameters
• client –[in] The esp_http_client handle
• buffer –The buffer
• len –[in] The buffer length
Returns

Espressif Systems 171 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• Length of data was read


esp_err_t esp_http_client_flush_response(esp_http_client_handle_t client, int *len)
Process all remaining response data This uses an internal buffer to repeatedly receive, parse, and discard re-
sponse data until complete data is processed. As no additional user-supplied buffer is required, this may be
preferrable to esp_http_client_read_response in situations where the content of the response may
be ignored.
Parameters
• client –[in] The esp_http_client handle
• len –Length of data discarded
Returns
• ESP_OK If successful, len will have discarded length
• ESP_FAIL If failed to read response
• ESP_ERR_INVALID_ARG If the client is NULL
esp_err_t esp_http_client_get_url(esp_http_client_handle_t client, char *url, const int len)
Get URL from client.
Parameters
• client –[in] The esp_http_client handle
• url –[inout] The buffer to store URL
• len –[in] The buffer length
Returns
• ESP_OK
• ESP_FAIL
esp_err_t esp_http_client_get_chunk_length(esp_http_client_handle_t client, int *len)
Get Chunk-Length from client.
Parameters
• client –[in] The esp_http_client handle
• len –[out] Variable to store length
Returns
• ESP_OK If successful, len will have length of current chunk
• ESP_FAIL If the server is not a chunked server
• ESP_ERR_INVALID_ARG If the client or len are NULL

Structures

struct esp_http_client_event
HTTP Client events data.

Public Members

esp_http_client_event_id_t event_id
event_id, to know the cause of the event

esp_http_client_handle_t client
esp_http_client_handle_t context

void *data
data of the event

int data_len
data length of data

Espressif Systems 172 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

void *user_data
user_data context, from esp_http_client_config_t user_data

char *header_key
For HTTP_EVENT_ON_HEADER event_id, it’s store current http header key

char *header_value
For HTTP_EVENT_ON_HEADER event_id, it’s store current http header value

struct esp_http_client_on_data
Argument structure for HTTP_EVENT_ON_DATA event.

Public Members

esp_http_client_handle_t client
Client handle

int64_t data_process
Total data processed

struct esp_http_client_redirect_event_data
Argument structure for HTTP_EVENT_REDIRECT event.

Public Members

esp_http_client_handle_t client
Client handle

int status_code
Status Code

struct esp_http_client_config_t
HTTP configuration.

Public Members

const char *url


HTTP URL, the information on the URL is most important, it overrides the other fields below, if any

const char *host


Domain or IP as string

int port
Port to connect, default depend on esp_http_client_transport_t (80 or 443)

const char *username


Using for Http authentication

Espressif Systems 173 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

const char *password


Using for Http authentication

esp_http_client_auth_type_t auth_type
Http authentication type, see esp_http_client_auth_type_t

const char *path


HTTP Path, if not set, default is /

const char *query


HTTP query

const char *cert_pem


SSL server certification, PEM format as string, if the client requires to verify server

size_t cert_len
Length of the buffer pointed to by cert_pem. May be 0 for null-terminated pem

const char *client_cert_pem


SSL client certification, PEM format as string, if the server requires to verify client

size_t client_cert_len
Length of the buffer pointed to by client_cert_pem. May be 0 for null-terminated pem

const char *client_key_pem


SSL client key, PEM format as string, if the server requires to verify client

size_t client_key_len
Length of the buffer pointed to by client_key_pem. May be 0 for null-terminated pem

const char *client_key_password


Client key decryption password string

size_t client_key_password_len
String length of the password pointed to by client_key_password

const char *user_agent


The User Agent string to send with HTTP requests

esp_http_client_method_t method
HTTP Method

int timeout_ms
Network timeout in milliseconds

bool disable_auto_redirect
Disable HTTP automatic redirects

Espressif Systems 174 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

int max_redirection_count
Max number of redirections on receiving HTTP redirect status code, using default value if zero

int max_authorization_retries
Max connection retries on receiving HTTP unauthorized status code, using default value if zero. Disables
authorization retry if -1

http_event_handle_cb event_handler
HTTP Event Handle

esp_http_client_transport_t transport_type
HTTP transport type, see esp_http_client_transport_t

int buffer_size
HTTP receive buffer size

int buffer_size_tx
HTTP transmit buffer size

void *user_data
HTTP user_data context

bool is_async
Set asynchronous mode, only supported with HTTPS for now

bool use_global_ca_store
Use a global ca_store for all the connections in which this bool is set.

bool skip_cert_common_name_check
Skip any validation of server certificate CN field

const char *common_name


Pointer to the string containing server certificate common name. If non-NULL, server certificate CN
must match this name, If NULL, server certificate CN must match hostname.

esp_err_t (*crt_bundle_attach)(void *conf)


Function pointer to esp_crt_bundle_attach. Enables the use of certification bundle for server verification,
must be enabled in menuconfig

bool keep_alive_enable
Enable keep-alive timeout

int keep_alive_idle
Keep-alive idle time. Default is 5 (second)

int keep_alive_interval
Keep-alive interval time. Default is 5 (second)

Espressif Systems 175 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

int keep_alive_count
Keep-alive packet retry send count. Default is 3 counts

struct ifreq *if_name


The name of interface for data to go through. Use the default interface without setting

Macros

DEFAULT_HTTP_BUF_SIZE

ESP_ERR_HTTP_BASE
Starting number of HTTP error codes

ESP_ERR_HTTP_MAX_REDIRECT
The error exceeds the number of HTTP redirects

ESP_ERR_HTTP_CONNECT
Error open the HTTP connection

ESP_ERR_HTTP_WRITE_DATA
Error write HTTP data

ESP_ERR_HTTP_FETCH_HEADER
Error read HTTP header from server

ESP_ERR_HTTP_INVALID_TRANSPORT
There are no transport support for the input scheme

ESP_ERR_HTTP_CONNECTING
HTTP connection hasn’t been established yet

ESP_ERR_HTTP_EAGAIN
Mapping of errno EAGAIN to esp_err_t

ESP_ERR_HTTP_CONNECTION_CLOSED
Read FIN from peer and the connection closed

Type Definitions

typedef struct esp_http_client *esp_http_client_handle_t

typedef struct esp_http_client_event *esp_http_client_event_handle_t

typedef struct esp_http_client_event esp_http_client_event_t


HTTP Client events data.

typedef struct esp_http_client_on_data esp_http_client_on_data_t


Argument structure for HTTP_EVENT_ON_DATA event.

Espressif Systems 176 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

typedef struct esp_http_client_redirect_event_data esp_http_client_redirect_event_data_t


Argument structure for HTTP_EVENT_REDIRECT event.

typedef esp_err_t (*http_event_handle_cb)(esp_http_client_event_t *evt)

Enumerations

enum esp_http_client_event_id_t
HTTP Client events id.
Values:

enumerator HTTP_EVENT_ERROR
This event occurs when there are any errors during execution

enumerator HTTP_EVENT_ON_CONNECTED
Once the HTTP has been connected to the server, no data exchange has been performed

enumerator HTTP_EVENT_HEADERS_SENT
After sending all the headers to the server

enumerator HTTP_EVENT_HEADER_SENT
This header has been kept for backward compatability and will be deprecated in future versions esp-idf

enumerator HTTP_EVENT_ON_HEADER
Occurs when receiving each header sent from the server

enumerator HTTP_EVENT_ON_DATA
Occurs when receiving data from the server, possibly multiple portions of the packet

enumerator HTTP_EVENT_ON_FINISH
Occurs when finish a HTTP session

enumerator HTTP_EVENT_DISCONNECTED
The connection has been disconnected

enumerator HTTP_EVENT_REDIRECT
Intercepting HTTP redirects to handle them manually

enum esp_http_client_transport_t
HTTP Client transport.
Values:

enumerator HTTP_TRANSPORT_UNKNOWN
Unknown

enumerator HTTP_TRANSPORT_OVER_TCP
Transport over tcp

Espressif Systems 177 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator HTTP_TRANSPORT_OVER_SSL
Transport over ssl

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

Espressif Systems 178 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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

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

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_Unauthorized

Espressif Systems 179 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator HttpStatus_Forbidden

enumerator HttpStatus_NotFound

enumerator HttpStatus_InternalError

2.2.6 ESP Local Control

Overview

ESP Local Control (esp_local_ctrl) component in ESP-IDF provides capability to control an ESP device over HTTPS
or Bluetooth® Low Energy. It provides access to application defined properties that are available for reading/writing
via a set of configurable handlers.
Initialization of the esp_local_ctrl service over Bluetooth Low Energy transport is performed as follows:
esp_local_ctrl_config_t config = {
.transport = ESP_LOCAL_CTRL_TRANSPORT_BLE,
.transport_config = {
.ble = & (protocomm_ble_config_t) {
.device_name = SERVICE_NAME,
.service_uuid = {
/* LSB <---------------------------------------
* ---------------------------------------> MSB */
0x21, 0xd5, 0x3b, 0x8d, 0xbd, 0x75, 0x68, 0x8a,
0xb4, 0x42, 0xeb, 0x31, 0x4a, 0x1e, 0x98, 0x3d
}
}
},
.proto_sec = {
.version = PROTOCOM_SEC0,
.custom_handle = NULL,
.sec_params = NULL,
},
.handlers = {
/* User defined handler functions */
.get_prop_values = get_property_values,
.set_prop_values = set_property_values,
.usr_ctx = NULL,
.usr_ctx_free_fn = NULL
},
/* Maximum number of properties that may be set */
.max_properties = 10
};

/* Start esp_local_ctrl service */


ESP_ERROR_CHECK(esp_local_ctrl_start(&config));

Similarly for HTTPS transport:


/* Set the configuration */
httpd_ssl_config_t https_conf = HTTPD_SSL_CONFIG_DEFAULT();

/* Load server certificate */


extern const unsigned char servercert_start[] asm("_binary_servercert_pem_
,→start");

(continues on next page)

Espressif Systems 180 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

(continued from previous page)


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:
1. 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.
2. PROTOCOM_SEC1: specifies that Curve25519-based key exchange and end-to-end encryption based on AES-
CTR are used.
3. PROTOCOM_SEC0: specifies that data will be exchanged as a plain text (no security).
4. PROTOCOM_SEC_CUSTOM: you can define your own security requirement. Please note that you will also
have to provide custom_handle of type protocomm_security_t * in this context.

Note: The respective security schemes need to be enabled through the project configuration menu. Please refer to
the Enabling protocom security version section in Protocol Communication for more details.

Creating a Property

Now that we know how to start the esp_local_ctrl service, let’s add a property to it. Each property must have a
unique `name` (string), a type (e.g., enum), flags` (bit fields) and size`.
The size is to be kept 0, if we want our property value to be of variable length (e.g., if it is a string or bytestream).
For data types with fixed-length property value, like int, float, etc., setting the size field to the right value helps
esp_local_ctrl to perform internal checks on arguments received with write requests.

Espressif Systems 181 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

The interpretation of type and flags fields is totally upto the application, hence they may be used as enumerations,
bitfields, or even simple integers. One way is to use type values to classify properties, while flags to specify
characteristics of a property.
Here is an example property which is to function as a timestamp. It is assumed that the application defines
TYPE_TIMESTAMP and READONLY, which are used for setting the type and flags fields here.
/* Create a timestamp property */
esp_local_ctrl_prop_t timestamp = {
.name = "timestamp",
.type = TYPE_TIMESTAMP,
.size = sizeof(int32_t),
.flags = READONLY,
.ctx = func_get_time,
.ctx_free_fn = NULL
};

/* Now register the property */


esp_local_ctrl_add_property(&timestamp);

Also notice that there is a ctx field, which is set to point to some custom func_get_time(). This can be used inside the
property get/set handlers to retrieve timestamp.
Here is an example of get_prop_values() handler, which is used for retrieving the timestamp.
static esp_err_t get_property_values(size_t props_count,
const esp_local_ctrl_prop_t *props,
esp_local_ctrl_prop_val_t *prop_
,→values,

void *usr_ctx)
{
for (uint32_t i = 0; i < props_count; i++) {
ESP_LOGI(TAG, "Reading %s", props[i].name);
if (props[i].type == TYPE_TIMESTAMP) {
/* Obtain the timer function from ctx */
int32_t (*func_get_time)(void) = props[i].ctx;

/* Use static variable for saving the value. This is␣


,→essential because the value has to be valid even after this function␣
,→returns. Alternative is to use dynamic allocation and set the free_fn␣

,→field */

static int32_t ts = func_get_time();


prop_values[i].data = &ts;
}
}
return ESP_OK;
}

Here is an example of set_prop_values() handler. Notice how we restrict from writing to read-only properties.
static esp_err_t set_property_values(size_t props_count,
const esp_local_ctrl_prop_t *props,
const esp_local_ctrl_prop_val_t␣
,→*prop_values,

void *usr_ctx)
{
for (uint32_t i = 0; i < props_count; i++) {
if (props[i].flags & READONLY) {
ESP_LOGE(TAG, "Cannot write to read-only property %s",␣
,→props[i].name);

return ESP_ERR_INVALID_ARG;
} else {
ESP_LOGI(TAG, "Setting %s", props[i].name);
(continues on next page)

Espressif Systems 182 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

(continued from previous page)

/* 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 trans-
lates 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:
1. get_prop_count : This should simply return the total number of properties supported by the service.
2. get_prop_values : This accepts an array of indices and should return the information (name, type, flags)
and values of the properties corresponding to those indices.
3. set_prop_values : This accepts an array of indices and an array of new values, which are used for setting
the values of the properties corresponding to the indices.
Note that indices may or may not be the same for a property, across multiple sessions. Therefore, the client must
only use the names of the properties to uniquely identify them. So, every time a new session is established, the client
should first call get_prop_count and then get_prop_values, hence form an index-to-name mapping for
all properties. Now when calling set_prop_values for a set of properties, it must first convert the names to
indexes, using the created mapping. As emphasized earlier, the client must refresh the index-to-name mapping every
time a new session is established with the same device.
The various protocomm endpoints provided by esp_local_ctrl are listed below:

Table 1: Endpoints provided by ESP Local Control


Endpoint URI (HTTPS Server + Description
Name mDNS)
(Blue-
tooth
Low
Energy
+ GATT
Server)
esp_local_ctrl/version
https://<mdns- Endpoint used for retrieving version string
hostname>.local/esp_local_ctrl/version
esp_local_ctrl/control
https://<mdns- Endpoint used for sending or receiving control messages
hostname>.local/esp_local_ctrl/control

API Reference

Header File
• components/esp_local_ctrl/include/esp_local_ctrl.h

Functions

Espressif Systems 183 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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_stop(void)
Stop local control service.
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_t when its name
is known
Parameters name –[in] Name of the property to find
Returns
• Pointer to property
• NULL if not found
esp_err_t esp_local_ctrl_set_handler(const char *ep_name, protocomm_req_handler_t handler, void
*user_ctx)
Register protocomm handler for a custom endpoint.
This API can be called by the application to register a protocomm handler for an endpoint after the local control
service has started.

Note: In case of BLE transport the names and uuids of all custom endpoints must be provided beforehand as
a part of the protocomm_ble_config_t structure set in esp_local_ctrl_config_t, and passed
to esp_local_ctrl_start().

Parameters
• ep_name –[in] Name of the endpoint
• handler –[in] Endpoint handler function

Espressif Systems 184 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• user_ctx –[in] User data


Returns
• ESP_OK : Success
• ESP_FAIL : Failure

Unions

union esp_local_ctrl_transport_config_t
#include <esp_local_ctrl.h> Transport mode (BLE / HTTPD) configuration.

Public Members

esp_local_ctrl_transport_config_ble_t *ble
This is same as protocomm_ble_config_t. See protocomm_ble.h for available configuration
parameters.

esp_local_ctrl_transport_config_httpd_t *httpd
This is same as httpd_ssl_config_t. See esp_https_server.h for available configuration
parameters.

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_values and set_prop_values handlers as a part of this property structure. When

Espressif Systems 185 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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.

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_ctrl
to call this function on the data pointer above, for freeing its resources after sending the
get_prop_values response.

struct esp_local_ctrl_handlers
Handlers for receiving and responding to local control commands for getting and setting properties.

Public Members

esp_err_t (*get_prop_values)(size_t props_count, const esp_local_ctrl_prop_t props[],


esp_local_ctrl_prop_val_t prop_values[], void *usr_ctx)
Handler function to be implemented for retrieving current values of properties.

Note: If any of the properties have fixed sizes, the size field of corresponding element in prop_values
need to be set

Param props_count [in] Total elements in the props array


Param props [in] Array of properties, the current values for which have been requested by
the client
Param prop_values [out] Array of empty property values, the elements of which need to be
populated with the current values of those properties specified by props argument
Param usr_ctx [in] This provides value of the usr_ctx field of
esp_local_ctrl_handlers_t structure
Return Returning different error codes will convey the corresponding protocol level errors to
the client :
• ESP_OK : Success
• ESP_ERR_INVALID_ARG : InvalidArgument
• ESP_ERR_INVALID_STATE : InvalidProto
• All other error codes : InternalError

Espressif Systems 186 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t (*set_prop_values)(size_t props_count, const esp_local_ctrl_prop_t props[], const


esp_local_ctrl_prop_val_t prop_values[], void *usr_ctx)
Handler function to be implemented for changing values of properties.

Note: If any of the properties have variable sizes, the size field of the corresponding element in
prop_values must be checked explicitly before making any assumptions on the size.

Param props_count [in] Total elements in the props array


Param props [in] Array of properties, the values for which the client requests to change
Param prop_values [in] Array of property values, the elements of which need to be used for
updating those properties specified by props argument
Param usr_ctx [in] This provides value of the usr_ctx field of
esp_local_ctrl_handlers_t structure
Return Returning different error codes will convey the corresponding protocol level errors to
the client :
• ESP_OK : Success
• ESP_ERR_INVALID_ARG : InvalidArgument
• ESP_ERR_INVALID_STATE : InvalidProto
• All other error codes : InternalError

void *usr_ctx
Context pointer to be passed to above handler functions upon invocation. This is different from the
property level context, as this is valid throughout the lifetime of the esp_local_ctrl service, and
freed only when the service is stopped.

void (*usr_ctx_free_fn)(void *usr_ctx)


Pointer to function which will be internally invoked on usr_ctx for freeing the context resources when
esp_local_ctrl_stop() is called.

struct esp_local_ctrl_proto_sec_cfg
Protocom security configs

Public Members

esp_local_ctrl_proto_sec_t version
This sets protocom security version, sec0/sec1 or custom If custom, user must provide handle via
proto_sec_custom_handle below

void *custom_handle
Custom security handle if security is set custom via proto_sec above This handle must follow pro-
tocomm_security_t signature

const void *pop


Proof of possession to be used for local control. Could be NULL.

const void *sec_params


Pointer to security params (NULL if not needed). This is not needed for protocomm security 0 This
pointer should hold the struct of type esp_local_ctrl_security1_params_t for protocomm security 1 and
esp_local_ctrl_security2_params_t for protocomm security 2 respectively. Could be NULL.

Espressif Systems 187 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_local_ctrl_config
Configuration structure to pass to esp_local_ctrl_start()

Public Members

const esp_local_ctrl_transport_t *transport


Transport layer over which service will be provided

esp_local_ctrl_transport_config_t transport_config
Transport layer over which service will be provided

esp_local_ctrl_proto_sec_cfg_t proto_sec
Security version and POP

esp_local_ctrl_handlers_t handlers
Register handlers for responding to get/set requests on properties

size_t max_properties
This limits the number of properties that are available at a time

Macros

ESP_LOCAL_CTRL_TRANSPORT_BLE

ESP_LOCAL_CTRL_TRANSPORT_HTTPD

Type Definitions

typedef struct esp_local_ctrl_prop esp_local_ctrl_prop_t


Property description data structure, which is to be populated and passed to the
esp_local_ctrl_add_property() function.
Once a property is added, its structure is available for read-only access inside get_prop_values() and
set_prop_values() handlers.

typedef struct esp_local_ctrl_prop_val esp_local_ctrl_prop_val_t


Property value data structure. This gets passed to the get_prop_values() and set_prop_values()
handlers for the purpose of retrieving or setting the present value of a property.

typedef struct esp_local_ctrl_handlers esp_local_ctrl_handlers_t


Handlers for receiving and responding to local control commands for getting and setting properties.

typedef struct esp_local_ctrl_transport esp_local_ctrl_transport_t


Transport mode (BLE / HTTPD) over which the service will be provided.
This is forward declaration of a private structure, implemented internally by esp_local_ctrl.

typedef struct protocomm_ble_config esp_local_ctrl_transport_config_ble_t


Configuration for transport mode BLE.
This is a forward declaration for protocomm_ble_config_t. To use this, application must set CON-
FIG_BT_BLUEDROID_ENABLED and include protocomm_ble.h.

Espressif Systems 188 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

typedef struct httpd_config esp_local_ctrl_transport_config_httpd_t


Configuration for transport mode HTTPD.
This is a forward declaration for httpd_ssl_config_t (for HTTPS) or httpd_config_t (for HTTP)

typedef enum esp_local_ctrl_proto_sec esp_local_ctrl_proto_sec_t


Security types for esp_local_control.

typedef protocomm_security1_params_t esp_local_ctrl_security1_params_t

typedef protocomm_security2_params_t esp_local_ctrl_security2_params_t

typedef struct esp_local_ctrl_proto_sec_cfg esp_local_ctrl_proto_sec_cfg_t


Protocom security configs

typedef struct esp_local_ctrl_config esp_local_ctrl_config_t


Configuration structure to pass to esp_local_ctrl_start()

Enumerations

enum esp_local_ctrl_proto_sec
Security types for esp_local_control.
Values:

enumerator PROTOCOM_SEC0

enumerator PROTOCOM_SEC1

enumerator PROTOCOM_SEC2

enumerator PROTOCOM_SEC_CUSTOM

2.2.7 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:
• ESSL component on GitHub

Espressif Systems 189 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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.

Communication with ESP SDIO Slave


This document describes the process of initialization of an ESP SDIO Slave device and then provides details on the
ESP SDIO Slave protocol - a non-standard protocol that allows an SDIO Host to communicate with an ESP SDIO
slave.
The ESP SDIO Slave protocol was created to implement the communication between SDIO host and slave, because
the SDIO specification only shows how to access the custom region of a card (by sending CMD52 and CMD53 to
functions 1-7) without any details regarding the underlying hardware implementation.

SDIO Slave Capabilities of Espressif Chips The services provided by the SDIO Slave peripheral of the ESP32
chip are listed in the table below:

Services ESP32
SDIO slave Y
Tohost intr 8
Frhost intr 8
TX DMA Y
RX DMA Y
Shared registers 56*

* Not including the interrupt registers

ESP SDIO Slave Initialization The host should initialize the ESP32 SDIO slave according to the standard SDIO
initialization process (Section 3.1.2 of SDIO Simplified Specification). In this specification as well as below, the
SDIO slave is called an (SD)IO card. Here is a brief example of an ESP SDIO Slave initialization process:
1. SDIO reset
CMD52 (Write 0x6 = 0x8)
2. SD reset
CMD0
3. Check whether IO card (optional)
CMD8
4. Send SDIO op cond and wait for card ready
CMD5 arg = 0x00000000
CMD5 arg = 0x00ff8000 (according to the response above, poll until ready)
Example:
Arg of R4 after first CMD5 (arg = 0x00000000) is 0xXXFFFF00.
Keep sending CMD5 with arg = 0x00FFFF00 until the R4 shows card ready (arg bit 31
= 1).
5. Set address
CMD3
6. Select card
CMD7 (arg address according to CMD3 response)
Example:
Arg of R6 after CMD3 is 0x0001xxxx.
Arg of CMD7 should be 0x00010000.
7. Select 4-bit mode (optional)

Espressif Systems 190 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

CMD52 (Write 0x07 = 0x02)


8. Enable func1
CMD52 (Write 0x02 = 0x02)
9. Enable SDIO interrupt (required if interrupt line (DAT1) is used)
CMD52 (Write 0x04 = 0x03)
10. Set Func0 blocksize (optional, default value is 512 (0x200))
CMD52/53 (Read 0x10 ~ 0x11)
CMD52/53 (Write 0x10 = 0x00)
CMD52/53 (Write 0x11 = 0x02)
CMD52/53 (Read 0x10 ~ 0x11, read to check the final value)
11. Set Func1 blocksize (optional, default value is 512 (0x200))
CMD52/53 (Read 0x110 ~ 0x111)
CMD52/53 (Write 0x110 = 0x00)
CMD52/53 (Write 0x111 = 0x02)
CMD52/53 (Read 0x110 ~ 0x111, read to check the final value)

ESP SDIO Slave Protocol The ESP SDIO Slave protocol is based on the SDIO Specification’s I/O Read/Write
commands, i.e., CMD52 and CMD53. The protocol offers the following services:
• Sending FIFO and receiving FIFO
• 52 8-bit R/W registers shared by host and slave (For details, see ESP32 Technical Reference Manual > SDIO
Slave Controller > Register Summary > SDIO SLC Host registers [PDF])
• 16 general purpose interrupt sources, 8 from host to slave and 8 from slave to host
To begin communication, the host needs to enable the I/O Function 1 in the slave and access its registers as described
below.
Check the code example: peripherals/sdio
The ESP Serial Slave Link component implements the logic of this protocol for ESP32 SDIO Host when communi-
cating with an ESP32 SDIO slave.

Slave Register Table

32-bit
• 0x044 (TOKEN_RDATA): in which bit 27-16 holds the number of the receiving buffer.
• 0x058 (INT_ST): holds the interrupt source bits from slave to host.
• 0x060 (PKT_LEN): holds the accumulated data length (in bytes) already read by host plus the data copied to
the buffer but yet to be read.
• 0x0D4 (INT_CLR): write 1 to clear interrupt bits corresponding to INT_ST.
• 0x0DC (INT_ENA): mask bits for interrupts from slave to host.

8-bit Shared general purpose registers:


• 0x06C-0x077: R/W registers 0-11 shared by slave and host.
• 0x07A-0x07B: R/W registers 14-15 shared by slave and host.
• 0x07E-0x07F: R/W registers 18-19 shared by slave and host.
• 0x088-0x08B: R/W registers 24-27 shared by slave and host.
• 0x09C-0x0BB: R/W registers 32-63 shared by slave and host.
Interrupt Registers:
• 0x08D (SLAVE_INT): bits for host to interrupt slave. auto clear.

FIFO (Sending and Receiving) 0x090 - 0x1F7FF are reserved for FIFOs.
The address of CMD53 is related to the length requested to read from or write to the slave in a single transfer, as
demonstrated by the equation below:

Espressif Systems 191 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

requested length = 0x1F800 - address


The slave responds to data that has a length equal to the length field of CMD53. In cases where the data is longer
than the requested length, the data will be zero filled (when sending) or discarded (when receiving). This includes
both the block and the byte mode of CMD53.

Note: The function number should be set to 1, and OP Code should be set to 1 (for CMD53).
In order to achieve higher efficiency when accessing the FIFO by an arbitrary length, the block and byte modes of
CMD53 can be used in combination. For example, given that the block size is set to 512 by default, you can write or
get 1031 bytes of data from the FIFO by doing the following:
1. Send CMD53 in block mode, block count = 2 (1024 bytes) to address 0x1F3F9 = 0x1F800 - 1031.
2. Then send CMD53 in byte mode, byte count = 8 (or 7 if your controller supports that) to address 0x1F7F9 =
0x1F800 - 7.

Interrupts SDIO interrupts are “level sensitive”. For host interrupts, the slave sends an interrupt by pulling the
DAT1 line down at a proper time. The host detects when the interrupt line is pulled down and reads the INT_ST
register to determine the source of the interrupt. After that, the host can clear the interrupt bits by writing the
INT_CLR register and process the interrupt. The host can also mask unneeded sources by clearing the bits in the
INT_ENA register corresponding to the sources. If all the sources are cleared (or masked), the DAT1 line goes
inactive.
On ESP32, the corresponding host_int bits are: bit 0 to bit 7.
For slave interrupts, the host sends a transfer to write the SLAVE_INT register. Once a bit is set to 1, the slave
hardware and the driver will detect it and inform the application.

Receiving FIFO To write to the slave’s receiving FIFO, the host should complete the following steps:
1. Read the TOKEN1 field (bits 27-16) of the register TOKEN_RDATA (0x044). The buffer number re-
maining is TOKEN1 minus the number of buffers used by host.
2. Make sure the buffer number is sufficient (buffer_size x buffer_num is greater than the data to write,
buffer_size is pre-defined between the host and the slave before the communication starts). Otherwise, keep
returning to step 1 until the buffer size is sufficient.
3. Write to the FIFO address with CMD53. Note that the requested length should not exceed the length
calculated at step 2, and the FIFO address is related to requested length.
4. Calculate used buffers. Note that a partially-used buffer at the tail is counted as used.

Sending FIFO To read the slave’s sending FIFO, the host should complete the following steps:
1. Wait for the interrupt line to become active (optional, low by default).
2. Read (poll) the interrupt bits in the INT_ST register to monitor if new packets exist.
3. If new packets are ready, read the PKT_LEN register. Before reading the packets, determine the length
of data to be read. As the host keeps the length of data already read from the slave, subtract this value from
PKT_LEN, the result will be the maximum length of data available for reading. If no data has been added to
the sending FIFO yet, wait and poll until the slave is ready and update PKT_LEN.
4. Read from the FIFO using CMD53. Note that the requested length should not be greater than calculated
at Step 3, and the FIFO address is related to requested length.
5. Update the read length.

ESP SPI Slave HD (Half Duplex) Mode Protocol

Warning: ESP32 does not support this feature.

Espressif Systems 192 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

SPI Slave Capabilities of Espressif Chips

ESP32 ESP32-S2 ESP32-C3 ESP32-S3 ESP32-C2 ESP32-C6 ESP32-H2


SPI Slave HD N Y (v2) Y (v2) Y (v2) Y (v2) Y (v2) Y (v2)
Tohost intr N N N N N N
Frhost intr 2* 2* 2* 2* 2* 2*
TX DMA Y Y Y Y Y Y
RX DMA Y Y Y Y Y Y
Shared registers 72 64 64 64 64 64

Introduction In the half duplex mode, the master has to use the protocol defined by the slave to communicate with
the slave. Each transaction may consist of the following phases (listed by the order they should exist):
• Command: 8-bit, master to slave
This phase determines the rest phases of the transactions. See Supported Commands.
• Address: 8-bit, master to slave, optional
For some commands (WRBUF, RDBUF), this phase specifies the address of the shared register to
write to/read from. For other commands with this phase, they are meaningless but still have to exist
in the transaction.
• Dummy: 8-bit, floating, optional
This phase is the turnaround time between the master and the slave on the bus, and also provides
enough time for the slave to prepare the data to send to the master.
• Data: variable length, the direction is also determined by the command.
This may be a data OUT phase, in which the direction is slave to master, or a data IN phase, in
which the direction is master to slave.
The direction means which side (master or slave) controls the MOSI, MISO, WP, and HD pins.

Data IO Modes In some IO modes, more data wires can be used to send the data. As a result, the SPI clock cycles
required for the same amount of data will be less than in the 1-bit mode. For example, in QIO mode, address and
data (IN and OUT) should be sent on all 4 data wires (MOSI, MISO, WP, and HD). Here are the modes supported
by the ESP32-S2 SPI slave and the wire number (WN) used in corresponding modes.

Mode Command WN Address WN Dummy cycles Data WN


1-bit 1 1 1 1
DOUT 1 1 4 2
DIO 1 2 4 2
QOUT 1 1 4 4
QIO 1 4 4 4
QPI 4 4 4 4

Normally, which mode is used is determined by the command sent by the master (See Supported Commands), except
the QPI mode.

QPI Mode The QPI mode is a special state of the SPI Slave. The master can send the ENQPI command to put the
slave into the QPI mode state. In the QPI mode, the command is also sent in 4-bit, thus it is not compatible with the
normal modes. The master should only send QPI commands when the slave is in QPI mode. To exit from the QPI
mode, master can send the EXQPI command.

Supported Commands
Note: The command name is in a master-oriented direction. For example, WRBUF means master writes the buffer
of slave.

Espressif Systems 193 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Name Description Command Address Data


WRBUF Write buffer 0x01 Buf addr master to slave, no
longer than buffer
size
RDBUF Read buffer 0x02 Buf addr slave to master, no
longer than buffer
size
WRDMA Write DMA 0x03 8 bits master to slave, no
longer than length
provided by slave
RDDMA Read DMA 0x04 8 bits slave to master, no
longer than length
provided by slave
SEG_DONE Segments done 0x05 • •

ENQPI Enter QPI mode 0x06 • •

WR_DONE Write segments 0x07 • •


done
CMD8 Interrupt 0x08 • •

CMD9 Interrupt 0x09 • •

CMDA Interrupt 0x0A • •

EXQPI Exit QPI mode 0xDD • •

Moreover, WRBUF, RDBUF, WRDMA, and RDDMA commands have their 2-bit and 4-bit version. To do trans-
actions in 2-bit or 4-bit mode, send the original command ORed by the corresponding command mask below. For
example, command 0xA1 means WRBUF in QIO mode.

Mode Mask
1-bit 0x00
DOUT 0x10
DIO 0x50
QOUT 0x20
QIO 0xA0
QPI 0xA0

Segment Transaction Mode Segment transaction mode is the only mode supported by the SPI Slave HD driver
for now. In this mode, for a transaction the slave loads onto the DMA, the master is allowed to read or write in
segments. In this way, the master does not have to prepare a large buffer as the size of data provided by the slave.
After the master finishes reading/writing a buffer, it has to send the corresponding termination command to the slave
as a synchronization signal. The slave driver will update new data (if exist) onto the DMA upon seeing the termination
command.
The termination command is WR_DONE (0x07) for WRDMA and CMD8 (0x08) for RDDMA.
Here is an example for the flow the master read data from the slave DMA:
1. The slave loads 4092 bytes of data onto the RDDMA.
2. The master do seven RDDMA transactions, each of them is 512 bytes long, and reads the first 3584 bytes from
the slave.

Espressif Systems 194 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

3. The master do the last RDDMA transaction of 512 bytes (equal, longer, or shorter than the total length loaded
by the slave are all allowed). The first 508 bytes are valid data from the slave, while the last 4 bytes are
meaningless bytes.
4. The master sends CMD8 to the slave.
5. The slave loads another 4092 bytes of data onto the RDDMA.
6. The master can start new reading transactions after it sends the CMD8.

Terminology

• ESSL: Abbreviation for ESP Serial Slave Link, the component described by this document.
• Master: The device running the esp_serial_slave_link component.
• ESSL device: a virtual device on the master associated with an ESP slave device. The device context has the
knowledge of the slave protocol above the bus, relying on some bus drivers to communicate with the slave.
• ESSL device handle: a handle to ESSL device context containing the configuration, status and data required
by the ESSL component. The context stores the driver configurations, communication state, data shared by
master and slave, etc.
– The context should be initialized before it is used, and get deinitialized if not used any more. The master
application operates on the ESSL device through this handle.
• 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:


1. Tohost Interrupts: The slave can inform the master about certain events by the interrupt line. (optional)
2. Frhost Interrupts: The master can inform the slave about certain events.
3. 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.
4. RX FIFO (slave to master): The slave can send data in stream to the master. The SDIO slave can also indicate
it has new data to send to master by the interrupt line.
The slave updates the RX data size to inform the master how much data it has prepared to send, and then
the master read the data size, and take off the data length it has already received to know how many data is
remaining.
5. 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:
1. Initialize a SDMMC card (see :doc:` Document of SDMMC driver </api-reference/storage/sdmmc>`) struc-
ture.
2. Call sdmmc_card_init() to initialize the card.

Espressif Systems 195 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

3. Initialize the ESSL device with essl_sdio_config_t. The card member should be the sd-
mmc_card_t got in step 2, and the recv_buffer_size member should be filled correctly according
to pre-negotiated value.
4. Call essl_init() to do initialization of the SDIO part.
5. 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)


1. Call essl_get_intr_ena() to know which events trigger the interrupts to the master.
2. Call essl_set_intr_ena() to set the events that trigger interrupts to the master.
3. Call essl_wait_int() to wait until interrupt from the slave, or timeout.
4. When interrupt is triggered, call essl_get_intr() to know which events are active, and call
essl_clear_intr() to clear them.

Frhost Interrupts
1. Call essl_send_slave_intr() to trigger general purpose interrupt of the slave.

TX FIFO
1. Call essl_get_tx_buffer_num() to know how many buffers the slave has prepared to receive data
from the master. This is optional. The master will poll tx_buffer_num when it tries to send packets to the
slave, until the slave has enough buffer or timeout.
2. Call essl_send_packet() to send data to the slave.

RX FIFO
1. Call essl_get_rx_data_size() to know how many data the slave has prepared to send to the master.
This is optional. When the master tries to receive data from the slave, it updates the rx_data_size for
once, if the current rx_data_size is shorter than the buffer size the master prepared to receive. And it
may poll the rx_data_size if the rx_data_size keeps 0, until timeout.
2. 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:
peripherals/sdio
Please refer to the specific example README.md for details.

Espressif Systems 196 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

API Reference

Header File
• components/driver/test_apps/components/esp_serial_slave_link/include/esp_serial_slave_link/essl.h

Functions
esp_err_t essl_init(essl_handle_t handle, uint32_t wait_ms)
Initialize the slave.
Parameters
• handle –Handle of an ESSL device.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: If success
• ESP_ERR_NOT_SUPPORTED: Current device does not support this function.
• Other value returned from lower layer init.
esp_err_t essl_wait_for_ready(essl_handle_t handle, uint32_t wait_ms)
Wait for interrupt of an ESSL slave device.
Parameters
• handle –Handle of an ESSL device.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: If success
• ESP_ERR_NOT_SUPPORTED: Current device does not support this function.
• One of the error codes from SDMMC host controller
esp_err_t essl_get_tx_buffer_num(essl_handle_t handle, uint32_t *out_tx_num, uint32_t wait_ms)
Get buffer num for the host to send data to the slave. The buffers are size of buffer_size.
Parameters
• handle –Handle of a ESSL device.
• out_tx_num –Output of buffer num that host can send data to ESSL slave.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: Success
• ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode
• One of the error codes from SDMMC/SPI host controller
esp_err_t essl_get_rx_data_size(essl_handle_t handle, uint32_t *out_rx_size, uint32_t wait_ms)
Get the size, in bytes, of the data that the ESSL slave is ready to send
Parameters
• handle –Handle of an ESSL device.
• out_rx_size –Output of data size to read from slave, in bytes
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: Success
• ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode
• One of the error codes from SDMMC/SPI host controller
esp_err_t essl_reset_cnt(essl_handle_t handle)
Reset the counters of this component. Usually you don’t need to do this unless you know the slave is reset.
Parameters handle –Handle of an ESSL device.
Returns
• ESP_OK: Success
• ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode
• ESP_ERR_INVALID_ARG: Invalid argument, handle is not init.

Espressif Systems 197 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t essl_send_packet(essl_handle_t handle, const void *start, size_t length, uint32_t wait_ms)
Send a packet to the ESSL Slave. The Slave receives the packet into buffers whose size is buffer_size
(configured during initialization).
Parameters
• handle –Handle of an ESSL device.
• start –Start address of the packet to send
• length –Length of data to send, if the packet is over-size, the it will be divided into
blocks and hold into different buffers automatically.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK Success
• ESP_ERR_INVALID_ARG: Invalid argument, handle is not init or other argument is not
valid.
• ESP_ERR_TIMEOUT: No buffer to use, or error ftrom SDMMC host controller.
• ESP_ERR_NOT_FOUND: Slave is not ready for receiving.
• ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode
• One of the error codes from SDMMC/SPI host controller.
esp_err_t essl_get_packet(essl_handle_t handle, void *out_data, size_t size, size_t *out_length, uint32_t
wait_ms)
Get a packet from ESSL slave.
Parameters
• handle –Handle of an ESSL device.
• out_data –[out] Data output address
• size –The size of the output buffer, if the buffer is smaller than the size of data to receive
from slave, the driver returns ESP_ERR_NOT_FINISHED
• out_length –[out] Output of length the data actually received from slave.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK Success: All the data has been read from the slave.
• ESP_ERR_INVALID_ARG: Invalid argument, The handle is not initialized or the other
arguments are invalid.
• ESP_ERR_NOT_FINISHED: Read was successful, but there is still data remaining.
• ESP_ERR_NOT_FOUND: Slave is not ready to send data.
• ESP_ERR_NOT_SUPPORTED: This API is not supported in this mode
• One of the error codes from SDMMC/SPI host controller.
esp_err_t essl_write_reg(essl_handle_t handle, uint8_t addr, uint8_t value, uint8_t *value_o, uint32_t
wait_ms)
Write general purpose R/W registers (8-bit) of ESSL slave.

Note: sdio 28-31 are reserved, the lower API helps to skip.

Parameters
• handle –Handle of an ESSL device.
• addr –Address of register to write. For SDIO, valid address: 0-59. For SPI, see
essl_spi.h
• value –Value to write to the register.
• value_o –Output of the returned written value.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK Success
• One of the error codes from SDMMC/SPI host controller

esp_err_t essl_read_reg(essl_handle_t handle, uint8_t add, uint8_t *value_o, uint32_t wait_ms)


Read general purpose R/W registers (8-bit) of ESSL slave.

Espressif Systems 198 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters
• handle –Handle of a essl device.
• add –Address of register to read. For SDIO, Valid address: 0-27, 32-63 (28-31 reserved,
return interrupt bits on read). For SPI, see essl_spi.h
• value_o –Output value read from the register.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK Success
• One of the error codes from SDMMC/SPI host controller
esp_err_t essl_wait_int(essl_handle_t handle, uint32_t wait_ms)
wait for an interrupt of the slave
Parameters
• handle –Handle of an ESSL device.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: If interrupt is triggered.
• ESP_ERR_NOT_SUPPORTED: Current device does not support this function.
• ESP_ERR_TIMEOUT: No interrupts before timeout.
esp_err_t essl_clear_intr(essl_handle_t handle, uint32_t intr_mask, uint32_t wait_ms)
Clear interrupt bits of ESSL slave. All the bits set in the mask will be cleared, while other bits will stay the
same.
Parameters
• handle –Handle of an ESSL device.
• intr_mask –Mask of interrupt bits to clear.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: Success
• ESP_ERR_NOT_SUPPORTED: Current device does not support this function.
• One of the error codes from SDMMC host controller
esp_err_t essl_get_intr(essl_handle_t handle, uint32_t *intr_raw, uint32_t *intr_st, uint32_t wait_ms)
Get interrupt bits of ESSL slave.
Parameters
• handle –Handle of an ESSL device.
• intr_raw –Output of the raw interrupt bits. Set to NULL if only masked bits are read.
• intr_st –Output of the masked interrupt bits. set to NULL if only raw bits are read.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: Success
• ESP_INVALID_ARG: If both intr_raw and intr_st are NULL.
• ESP_ERR_NOT_SUPPORTED: Current device does not support this function.
• One of the error codes from SDMMC host controller
esp_err_t essl_set_intr_ena(essl_handle_t handle, uint32_t ena_mask, uint32_t wait_ms)
Set interrupt enable bits of ESSL slave. The slave only sends interrupt on the line when there is a bit both the
raw status and the enable are set.
Parameters
• handle –Handle of an ESSL device.
• ena_mask –Mask of the interrupt bits to enable.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: Success
• ESP_ERR_NOT_SUPPORTED: Current device does not support this function.
• One of the error codes from SDMMC host controller

Espressif Systems 199 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t essl_get_intr_ena(essl_handle_t handle, uint32_t *ena_mask_o, uint32_t wait_ms)


Get interrupt enable bits of ESSL slave.
Parameters
• handle –Handle of an ESSL device.
• ena_mask_o –Output of interrupt bit enable mask.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK Success
• One of the error codes from SDMMC host controller
esp_err_t essl_send_slave_intr(essl_handle_t handle, uint32_t intr_mask, uint32_t wait_ms)
Send interrupts to slave. Each bit of the interrupt will be triggered.
Parameters
• handle –Handle of an ESSL device.
• intr_mask –Mask of interrupt bits to send to slave.
• wait_ms –Millisecond to wait before timeout, will not wait at all if set to 0-9.
Returns
• ESP_OK: Success
• ESP_ERR_NOT_SUPPORTED: Current device does not support this function.
• One of the error codes from SDMMC host controller

Type Definitions

typedef struct essl_dev_t *essl_handle_t


Handle of an ESSL device.

Header File
• components/driver/test_apps/components/esp_serial_slave_link/include/esp_serial_slave_link/essl_sdio.h

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.

Espressif Systems 200 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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.

Header File
• components/driver/test_apps/components/esp_serial_slave_link/include/esp_serial_slave_link/essl_spi.h

Functions
esp_err_t essl_spi_init_dev(essl_handle_t *out_handle, const essl_spi_config_t *init_config)
Initialize the ESSL SPI device function list and get its handle.
Parameters
• out_handle –[out] Output of the handle
• init_config –Configuration for the ESSL SPI device
Returns
• ESP_OK: On success
• ESP_ERR_NO_MEM: Memory exhausted
• ESP_ERR_INVALID_STATE: SPI driver is not initialized
• ESP_ERR_INVALID_ARG: Wrong register ID
esp_err_t essl_spi_deinit_dev(essl_handle_t handle)
Deinitialize the ESSL SPI device and free the memory used by the device.
Parameters handle –Handle of the ESSL SPI device
Returns
• ESP_OK: On success
• ESP_ERR_INVALID_STATE: ESSL SPI is not in use
esp_err_t essl_spi_read_reg(void *arg, uint8_t addr, uint8_t *out_value, uint32_t wait_ms)
Read from the shared registers.

Note: The registers for Master/Slave synchronization are reserved. Do not use them. (see rx_sync_reg
in essl_spi_config_t)

Parameters
• arg –Context of the component. (Member arg from essl_handle_t)
• addr –Address of the shared registers. (Valid: 0 ~
SOC_SPI_MAXIMUM_BUFFER_SIZE, registers for M/S sync are reserved, see
note1).
• out_value –[out] Read buffer for the shared registers.
• wait_ms –Time to wait before timeout (reserved for future use, user should set this to
0).
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized.
• ESP_ERR_INVALID_ARG: The address argument is not valid. See note 1.
• or other return value from :cpp:func:spi_device_transmit.

esp_err_t essl_spi_get_packet(void *arg, void *out_data, size_t size, uint32_t wait_ms)


Get a packet from Slave.

Espressif Systems 201 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters
• arg –Context of the component. (Member arg from essl_handle_t)
• out_data –[out] Output data address
• size –The size of the output data.
• wait_ms –Time to wait before timeout (reserved for future use, user should set this to
0).
Returns
• ESP_OK: On Success
• ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized.
• ESP_ERR_INVALID_ARG: The output data address is neither DMA capable nor 4 byte-
aligned
• ESP_ERR_INVALID_SIZE: Master requires size bytes of data but Slave did not load
enough bytes.
esp_err_t essl_spi_write_reg(void *arg, uint8_t addr, uint8_t value, uint8_t *out_value, uint32_t
wait_ms)
Write to the shared registers.

Note: The registers for Master/Slave synchronization are reserved. Do not use them. (see tx_sync_reg
in essl_spi_config_t)

Note: Feature of checking the actual written value (out_value) is not supported.

Parameters
• arg –Context of the component. (Member arg from essl_handle_t)
• addr –Address of the shared registers. (Valid: 0 ~
SOC_SPI_MAXIMUM_BUFFER_SIZE, registers for M/S sync are reserved, see
note1)
• value –Buffer for data to send, should be align to 4.
• out_value –[out] Not supported, should be set to NULL.
• wait_ms –Time to wait before timeout (reserved for future use, user should set this to
0).
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized.
• ESP_ERR_INVALID_ARG: The address argument is not valid. See note 1.
• ESP_ERR_NOT_SUPPORTED: Should set out_value to NULL. See note 2.
• or other return value from :cpp:func:spi_device_transmit.

esp_err_t essl_spi_send_packet(void *arg, const void *data, size_t size, uint32_t wait_ms)
Send a packet to Slave.
Parameters
• arg –Context of the component. (Member arg from essl_handle_t)
• data –Address of the data to send
• size –Size of the data to send.
• wait_ms –Time to wait before timeout (reserved for future use, user should set this to
0).
Returns
• ESP_OK: On success
• ESP_ERR_INVALID_STATE: ESSL SPI has not been initialized.
• ESP_ERR_INVALID_ARG: The data address is not DMA capable
• ESP_ERR_INVALID_SIZE: Master will send size bytes of data but Slave did not load
enough RX buffer

Espressif Systems 202 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

void essl_spi_reset_cnt(void *arg)


Reset the counter in Master context.

Note: Shall only be called if the slave has reset its counter. Else, Slave and Master would be desynchronized

Parameters arg –Context of the component. (Member arg from essl_handle_t)

esp_err_t essl_spi_rdbuf(spi_device_handle_t spi, uint8_t *out_data, int addr, int len, uint32_t flags)
Read the shared buffer from the slave in ISR way.

Note: The slave’s HW doesn’t guarantee the data in one SPI transaction is consistent. It sends data in unit
of byte. In other words, if the slave SW attempts to update the shared register when a rdbuf SPI transaction is
in-flight, the data got by the master will be the combination of bytes of different writes of slave SW.

Note: out_data should be prepared in words and in the DRAM. The buffer may be written in words by the
DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the len is
shorter than a word.

Parameters
• spi –SPI device handle representing the slave
• out_data –[out] Buffer for read data, strongly suggested to be in the DRAM and aligned
to 4
• addr –Address of the slave shared buffer
• len –Length to read
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: on success
• or other return value from :cpp:func:spi_device_transmit.

esp_err_t essl_spi_rdbuf_polling(spi_device_handle_t spi, uint8_t *out_data, int addr, int len, uint32_t
flags)
Read the shared buffer from the slave in polling way.

Note: out_data should be prepared in words and in the DRAM. The buffer may be written in words by the
DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the len is
shorter than a word.

Parameters
• spi –SPI device handle representing the slave
• out_data –[out] Buffer for read data, strongly suggested to be in the DRAM and aligned
to 4
• addr –Address of the slave shared buffer
• len –Length to read
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: on success
• or other return value from :cpp:func:spi_device_transmit.

esp_err_t essl_spi_wrbuf(spi_device_handle_t spi, const uint8_t *data, int addr, int len, uint32_t flags)
Write the shared buffer of the slave in ISR way.

Espressif Systems 203 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Note: out_data should be prepared in words and in the DRAM. The buffer may be written in words by the
DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the len is
shorter than a word.

Parameters
• spi –SPI device handle representing the slave
• data –Buffer for data to send, strongly suggested to be in the DRAM
• addr –Address of the slave shared buffer,
• len –Length to write
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.

esp_err_t essl_spi_wrbuf_polling(spi_device_handle_t spi, const uint8_t *data, int addr, int len, uint32_t
flags)
Write the shared buffer of the slave in polling way.

Note: out_data should be prepared in words and in the DRAM. The buffer may be written in words by the
DMA. When a byte is written, the remaining bytes in the same word will also be overwritten, even the len is
shorter than a word.

Parameters
• spi –SPI device handle representing the slave
• data –Buffer for data to send, strongly suggested to be in the DRAM
• addr –Address of the slave shared buffer,
• len –Length to write
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_polling_transmit.

esp_err_t essl_spi_rddma(spi_device_handle_t spi, uint8_t *out_data, int len, int seg_len, uint32_t flags)
Receive long buffer in segments from the slave through its DMA.

Note: This function combines several :cpp:func:essl_spi_rddma_seg and one


:cpp:func:essl_spi_rddma_done at the end. Used when the slave is working in segment mode.

Parameters
• spi –SPI device handle representing the slave
• out_data –[out] Buffer to hold the received data, strongly suggested to be in the DRAM
and aligned to 4
• len –Total length of data to receive.
• seg_len –Length of each segment, which is not larger than the maximum transaction
length allowed for the spi device. Suggested to be multiples of 4. When set < 0, means
send all data in one segment (the rddma_done will still be sent.)
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.

Espressif Systems 204 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t essl_spi_rddma_seg(spi_device_handle_t spi, uint8_t *out_data, int seg_len, uint32_t flags)


Read one data segment from the slave through its DMA.

Note: To read long buffer, call :cpp:func:essl_spi_rddma instead.

Parameters
• spi –SPI device handle representing the slave
• out_data –[out] Buffer to hold the received data. strongly suggested to be in the DRAM
and aligned to 4
• seg_len –Length of this segment
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.

esp_err_t essl_spi_rddma_done(spi_device_handle_t spi, uint32_t flags)


Send the rddma_done command to the slave. Upon receiving this command, the slave will stop sending the
current buffer even there are data unsent, and maybe prepare the next buffer to send.

Note: This is required only when the slave is working in segment mode.

Parameters
• spi –SPI device handle representing the slave
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.

esp_err_t essl_spi_wrdma(spi_device_handle_t spi, const uint8_t *data, int len, int seg_len, uint32_t flags)
Send long buffer in segments to the slave through its DMA.

Note: This function combines several :cpp:func:essl_spi_wrdma_seg and one


:cpp:func:essl_spi_wrdma_done at the end. Used when the slave is working in segment mode.

Parameters
• spi –SPI device handle representing the slave
• data –Buffer for data to send, strongly suggested to be in the DRAM
• len –Total length of data to send.
• seg_len –Length of each segment, which is not larger than the maximum transaction
length allowed for the spi device. Suggested to be multiples of 4. When set < 0, means
send all data in one segment (the wrdma_done will still be sent.)
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.

esp_err_t essl_spi_wrdma_seg(spi_device_handle_t spi, const uint8_t *data, int seg_len, uint32_t flags)
Send one data segment to the slave through its DMA.

Note: To send long buffer, call :cpp:func:essl_spi_wrdma instead.

Espressif Systems 205 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters
• spi –SPI device handle representing the slave
• data –Buffer for data to send, strongly suggested to be in the DRAM
• seg_len –Length of this segment
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.

esp_err_t essl_spi_wrdma_done(spi_device_handle_t spi, uint32_t flags)


Send the wrdma_done command to the slave. Upon receiving this command, the slave will stop receiving,
process the received data, and maybe prepare the next buffer to receive.

Note: This is required only when the slave is working in segment mode.

Parameters
• spi –SPI device handle representing the slave
• flags –SPI_TRANS_* flags to control the transaction mode of the transaction to send.
Returns
• ESP_OK: success
• or other return value from :cpp:func:spi_device_transmit.

Structures

struct essl_spi_config_t
Configuration of ESSL SPI device.

Public Members

spi_device_handle_t *spi
Pointer to SPI device handle.

uint32_t tx_buf_size
The pre-negotiated Master TX buffer size used by both the host and the slave.

uint8_t tx_sync_reg
The pre-negotiated register ID for Master-TX-SLAVE-RX synchronization. 1 word (4 Bytes) will be
reserved for the synchronization.

uint8_t rx_sync_reg
The pre-negotiated register ID for Master-RX-Slave-TX synchronization. 1 word (4 Bytes) will be re-
served for the synchronization.

2.2.8 ESP x509 Certificate Bundle

Espressif Systems 206 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Overview

The ESP x509 Certificate Bundle API provides an easy way to include a bundle of custom x509 root certificates for
TLS server verification.

Note: The bundle is currently not available when using WolfSSL.

The bundle comes with the complete list of root certificates from Mozilla’s NSS root certificate store. Using the
gen_crt_bundle.py python utility, the certificates’subject name and public key are stored in a file and embedded in
the ESP32 binary.
When generating the bundle you may choose between:
• The full root certificate bundle from Mozilla, containing more than 130 certificates. The current bundle was
updated Tue Jan 10 04:12:06 2023 GMT.
• A pre-selected filter list of the name of the most commonly used root certificates, reducing the amount of
certificates to around 41 while still having around 90% absolute usage coverage and 99% market share coverage
according to SSL certificate authorities statistics.
In addition, it is possible to specify a path to a certificate file or a directory containing certificates which then will be
added to the generated bundle.

Note: Trusting all root certificates means the list will have to be updated if any of the certificates are retracted. This
includes removing them from cacrt_all.pem.

Configuration

Most configuration is done through menuconfig. CMake generates the bundle according to the configuration and
embed it.
• CONFIG_MBEDTLS_CERTIFICATE_BUNDLE: automatically build and attach the bundle.
• CONFIG_MBEDTLS_DEFAULT_CERTIFICATE_BUNDLE: decide which certificates to include from the com-
plete root certificate list.
• CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH: specify the path of any additional certifi-
cates to embed in the bundle.
To enable the bundle when using ESP-TLS simply pass the function pointer to the bundle attach function:

esp_tls_cfg_t cfg = {
.crt_bundle_attach = esp_crt_bundle_attach,
};

This is done to avoid embedding the certificate bundle unless activated by the user.
If using mbedTLS directly then the bundle may be activated by directly calling the attach function during the setup
process:

mbedtls_ssl_config conf;
mbedtls_ssl_config_init(&conf);

esp_crt_bundle_attach(&conf);

Generating the List of Root Certificates

The list of root certificates comes from Mozilla’s NSS root certificate store, which can be found here
The list can be downloaded and created by running the script mk-ca-bundle.pl that is distributed as a part of
curl.

Espressif Systems 207 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Another alternative would be to download the finished list directly from the curl website: CA certificates extracted
from Mozilla
The common certificates bundle were made by selecting the authorities with a market share of more than 1% from
w3tech’s SSL Survey.
These authorities were then used to pick the names of the certificates for the filter list, cmn_crt_authorities.
csv, from this list provided by Mozilla.

Updating the Certificate Bundle

The bundle is embedded into the app and can be updated along with the app by an OTA update. If you want to include
a more up-to-date bundle than the bundle currently included in ESP-IDF, then the certificate list can be downloaded
from Mozilla as described in Generating the List of Root Certificates.

Application Examples

Simple HTTPS example that uses ESP-TLS to establish a secure socket connection using the certificate bundle with
two custom certificates added for verification: protocols/https_x509_bundle.
HTTPS example that uses ESP-TLS and the default bundle: protocols/https_request.
HTTPS example that uses mbedTLS and the default bundle: protocols/https_mbedtls.

API Reference

Header File
• components/mbedtls/esp_crt_bundle/include/esp_crt_bundle.h

Functions
esp_err_t esp_crt_bundle_attach(void *conf)
Attach and enable use of a bundle for certificate verification.
Attach and enable use of a bundle for certificate verification through a verification callback. If no specific bundle
has been set through esp_crt_bundle_set() it will default to the bundle defined in menuconfig and embedded in
the binary.
Parameters conf –[in] The config struct for the SSL connection.
Returns
• ESP_OK if adding certificates was successful.
• Other if an error occured or an action must be taken by the calling process.
void esp_crt_bundle_detach(mbedtls_ssl_config *conf)
Disable and dealloc the certification bundle.
Removes the certificate verification callback and deallocates used resources
Parameters conf –[in] The config struct for the SSL connection.
esp_err_t esp_crt_bundle_set(const uint8_t *x509_bundle, size_t bundle_size)
Set the default certificate bundle used for verification.
Overrides the default certificate bundle only in case of successful initialization. In most use cases the bundle
should be set through menuconfig. The bundle needs to be sorted by subject name since binary search is used
to find certificates.
Parameters
• x509_bundle –[in] A pointer to the certificate bundle.
• bundle_size –[in] Size of the certificate bundle in bytes.
Returns

Espressif Systems 208 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• ESP_OK if adding certificates was successful.


• Other if an error occured or an action must be taken by the calling process.

2.2.9 HTTP Server

Overview

The HTTP Server component provides an ability for running a lightweight web server on ESP32. Following are
detailed steps to use the API exposed by HTTP Server:
• httpd_start(): Creates an instance of HTTP server, allocate memory/resources for it depending upon
the specified configuration and outputs a handle to the server instance. The server has both, a listening socket
(TCP) for HTTP traffic, and a control socket (UDP) for control signals, which are selected in a round robin
fashion in the server task loop. The task priority and stack size are configurable during server instance creation
by passing httpd_config_t structure to httpd_start(). TCP traffic is parsed as HTTP requests and,
depending on the requested URI, user registered handlers are invoked which are supposed to send back HTTP
response packets.
• httpd_stop(): This stops the server with the provided handle and frees up any associated mem-
ory/resources. This is a blocking function that first signals a halt to the server task and then waits for the
task to terminate. While stopping, the task closes all open connections, removes registered URI handlers and
resets all session context data to empty.
• httpd_register_uri_handler(): A URI handler is registered by passing object of type
httpd_uri_t structure which has members including uri name, method type (eg. HTTPD_GET/
HTTPD_POST/HTTPD_PUT etc.), function pointer of type esp_err_t *handler (httpd_req_t
*req) and user_ctx pointer to user context data.

Application Example

/* Our URI handler function to be called during GET /uri request */


esp_err_t get_handler(httpd_req_t *req)
{
/* Send a simple response */
const char resp[] = "URI GET Response";
httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}

/* Our URI handler function to be called during POST /uri request */


esp_err_t post_handler(httpd_req_t *req)
{
/* Destination buffer for content of HTTP POST request.
* httpd_req_recv() accepts char* only, but content could
* as well be any binary data (needs type casting).
* In case of string data, null termination will be absent, and
* content length would give length of string */
char content[100];

/* Truncate if content length larger than the buffer */


size_t recv_size = MIN(req->content_len, sizeof(content));

int ret = httpd_req_recv(req, content, recv_size);


if (ret <= 0) { /* 0 return value indicates connection closed */
/* Check if timeout occurred */
if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
/* In case of timeout one can choose to retry calling
(continues on next page)

Espressif Systems 209 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

(continued from previous page)


* httpd_req_recv(), but to keep it simple, here we
* respond with an HTTP 408 (Request Timeout) error */
httpd_resp_send_408(req);
}
/* In case of error, returning ESP_FAIL will
* ensure that the underlying socket is closed */
return ESP_FAIL;
}

/* Send a simple response */


const char resp[] = "URI POST Response";
httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}

/* URI handler structure for GET /uri */


httpd_uri_t uri_get = {
.uri = "/uri",
.method = HTTP_GET,
.handler = get_handler,
.user_ctx = NULL
};

/* URI handler structure for POST /uri */


httpd_uri_t uri_post = {
.uri = "/uri",
.method = HTTP_POST,
.handler = post_handler,
.user_ctx = NULL
};

/* Function for starting the webserver */


httpd_handle_t start_webserver(void)
{
/* Generate default configuration */
httpd_config_t config = HTTPD_DEFAULT_CONFIG();

/* Empty handle to esp_http_server */


httpd_handle_t server = NULL;

/* Start the httpd server */


if (httpd_start(&server, &config) == ESP_OK) {
/* Register URI handlers */
httpd_register_uri_handler(server, &uri_get);
httpd_register_uri_handler(server, &uri_post);
}
/* If server failed to start, handle will be NULL */
return server;
}

/* Function for stopping the webserver */


void stop_webserver(httpd_handle_t server)
{
if (server) {
/* Stop the httpd server */
httpd_stop(server);
}
}

Espressif Systems 210 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Simple HTTP Server Example Check HTTP server example under protocols/http_server/simple where handling
of arbitrary content lengths, reading request headers and URL query parameters, and setting response headers is
demonstrated.

Persistent Connections

HTTP server features persistent connections, allowing for the re-use of the same connection (session) for several
transfers, all the while maintaining context specific data for the session. Context data may be allocated dynamically by
the handler in which case a custom function may need to be specified for freeing this data when the connection/session
is closed.

Persistent Connections Example


/* Custom function to free context */
void free_ctx_func(void *ctx)
{
/* Could be something other than free */
free(ctx);
}

esp_err_t adder_post_handler(httpd_req_t *req)


{
/* Create session's context if not already available */
if (! req->sess_ctx) {
req->sess_ctx = malloc(sizeof(ANY_DATA_TYPE)); /*!< Pointer to context␣
,→data */

req->free_ctx = free_ctx_func; /*!< Function to free␣


,→context data */

/* Access context data */


ANY_DATA_TYPE *ctx_data = (ANY_DATA_TYPE *)req->sess_ctx;

/* Respond */
...............
...............
...............

return ESP_OK;
}

Check the example under protocols/http_server/persistent_sockets.

Websocket Server

The HTTP server component provides websocket support. The websocket feature can be enabled in menuconfig us-
ing 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

Espressif Systems 211 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• 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
• components/esp_http_server/include/esp_http_server.h

Functions
esp_err_t httpd_register_uri_handler(httpd_handle_t handle, const httpd_uri_t *uri_handler)
Registers a URI handler.

Example usage:

esp_err_t my_uri_handler(httpd_req_t* req)


{
// Recv , Process and Send
....
....
....

// Fail condition
if (....) {
// Return fail to close session //
return ESP_FAIL;
}

// On success
return ESP_OK;
}

// URI handler structure


httpd_uri_t my_uri {
.uri = "/my_uri/path/xyz",
.method = HTTPD_GET,
.handler = my_uri_handler,
.user_ctx = NULL
};

// Register handler
if (httpd_register_uri_handler(server_handle, &my_uri) != ESP_OK) {
// If failed to register handler
....
}

Note: URI handlers can be registered in real time as long as the server handle is valid.

Parameters
• handle –[in] handle to HTTPD server instance
• uri_handler –[in] pointer to handler that needs to be registered

Espressif Systems 212 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Returns
• ESP_OK : On successfully registering the handler
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_HANDLERS_FULL : If no slots left for new handler
• ESP_ERR_HTTPD_HANDLER_EXISTS : If handler with same URI and method is al-
ready registered
esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle, const char *uri, httpd_method_t
method)
Unregister a URI handler.
Parameters
• handle –[in] handle to HTTPD server instance
• uri –[in] URI string
• method –[in] HTTP method
Returns
• ESP_OK : On successfully deregistering the handler
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_NOT_FOUND : Handler with specified URI and method not found
esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char *uri)
Unregister all URI handlers with the specified uri string.
Parameters
• handle –[in] handle to HTTPD server instance
• uri –[in] uri string specifying all handlers that need to be deregisterd
Returns
• ESP_OK : On successfully deregistering all such handlers
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_NOT_FOUND : No handler registered with specified uri string
esp_err_t httpd_sess_set_recv_override(httpd_handle_t hd, int sockfd, httpd_recv_func_t recv_func)
Override web server’s receive function (by session FD)
This function overrides the web server’s receive function. This same function is used to read HTTP request
packets.

Note: This API is supposed to be called either from the context of


• an http session APIs where sockfd is a valid parameter
• a URI handler where sockfd is obtained using httpd_req_to_sockfd()

Parameters
• hd –[in] HTTPD instance handle
• sockfd –[in] Session socket FD
• recv_func –[in] The receive function to be set for this session
Returns
• ESP_OK : On successfully registering override
• ESP_ERR_INVALID_ARG : Null arguments

esp_err_t httpd_sess_set_send_override(httpd_handle_t hd, int sockfd, httpd_send_func_t send_func)


Override web server’s send function (by session FD)
This function overrides the web server’s send function. This same function is used to send out any response
to any HTTP request.

Note: This API is supposed to be called either from the context of


• an http session APIs where sockfd is a valid parameter
• a URI handler where sockfd is obtained using httpd_req_to_sockfd()

Espressif Systems 213 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters
• hd –[in] HTTPD instance handle
• sockfd –[in] Session socket FD
• send_func –[in] The send function to be set for this session
Returns
• ESP_OK : On successfully registering override
• ESP_ERR_INVALID_ARG : Null arguments

esp_err_t httpd_sess_set_pending_override(httpd_handle_t hd, int sockfd, httpd_pending_func_t


pending_func)
Override web server’s pending function (by session FD)
This function overrides the web server’s pending function. This function is used to test for pending bytes in
a socket.

Note: This API is supposed to be called either from the context of


• an http session APIs where sockfd is a valid parameter
• a URI handler where sockfd is obtained using httpd_req_to_sockfd()

Parameters
• hd –[in] HTTPD instance handle
• sockfd –[in] Session socket FD
• pending_func –[in] The receive function to be set for this session
Returns
• ESP_OK : On successfully registering override
• ESP_ERR_INVALID_ARG : Null arguments

esp_err_t httpd_req_async_handler_begin(httpd_req_t *r, httpd_req_t **out)


Start an asynchronous request. This function can be called in a request handler to get a request copy that can
be used on a async thread.

Note:
• This function is necessary in order to handle multiple requests simultaneously. See exam-
ples/async_requests for example usage.
• You must call httpd_req_async_handler_complete() when you are done with the request.

Parameters
• r –[in] The request to create an async copy of
• out –[out] A newly allocated request which can be used on an async thread
Returns
• ESP_OK : async request object created

esp_err_t httpd_req_async_handler_complete(httpd_req_t *r)


Mark an asynchronous request as completed. This will.

• free the request memory


• relinquish ownership of the underlying socket, so it can be reused.
• allow the http server to close our socket if needed (lru_purge_enable)

Espressif Systems 214 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Note: If async requests are not marked completed, eventually the server will no longer accept incoming
connections. The server will log a “httpd_accept_conn: error in accept (23)”message if this happens.

Parameters r –[in] The request to mark async work as completed


Returns
• ESP_OK : async request was marked completed

int httpd_req_to_sockfd(httpd_req_t *r)


Get the Socket Descriptor from the HTTP request.
This API will return the socket descriptor of the session for which URI handler was executed on reception of
HTTP request. This is useful when user wants to call functions that require session socket fd, from within a
URI handler, ie. : httpd_sess_get_ctx(), httpd_sess_trigger_close(), httpd_sess_update_lru_counter().

Note: This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.

Parameters r –[in] The request whose socket descriptor should be found


Returns
• Socket descriptor : The socket descriptor for this request
• -1 : Invalid/NULL request pointer

int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len)


API to read content data from the HTTP request.
This API will read HTTP content data from the HTTP request into provided buffer. Use content_len provided
in httpd_req_t structure to know the length of data to be fetched. If content_len is too large for the buffer then
user may have to make multiple calls to this function, each time fetching ‘buf_len’number of bytes, while
the pointer to content data is incremented internally by the same number.

Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• If an error is returned, the URI handler must further return an error. This will ensure that the erroneous
socket is closed and cleaned up by the web server.
• Presently Chunked Encoding is not supported

Parameters
• r –[in] The request being responded to
• buf –[in] Pointer to a buffer that the data will be read into
• buf_len –[in] Length of the buffer
Returns
• Bytes : Number of bytes read into the buffer successfully
• 0 : Buffer length parameter is zero / connection closed by peer
• HTTPD_SOCK_ERR_INVALID : Invalid arguments
• HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
• HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()

size_t httpd_req_get_hdr_value_len(httpd_req_t *r, const char *field)


Search for a field in request headers and return the string length of it’s value.

Note:

Espressif Systems 215 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once httpd_resp_send() API is called all request headers are purged, so request headers need be copied
into separate buffers if they are required later.

Parameters
• r –[in] The request being responded to
• field –[in] The header field to be searched in the request
Returns
• Length : If field is found in the request URL
• Zero : Field not found / Invalid request / Null arguments

esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size)
Get the value string of a field from the request headers.

Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once httpd_resp_send() API is called all request headers are purged, so request headers need be copied
into separate buffers if they are required later.
• If output size is greater than input, then the value is truncated, accompanied by truncation error as return
value.
• Use httpd_req_get_hdr_value_len() to know the right buffer length

Parameters
• r –[in] The request being responded to
• field –[in] The field to be searched in the header
• val –[out] Pointer to the buffer into which the value will be copied if the field is found
• val_size –[in] Size of the user buffer “val”
Returns
• ESP_OK : Field found in the request header and value string copied
• ESP_ERR_NOT_FOUND : Key not found
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer
• ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated

size_t httpd_req_get_url_query_len(httpd_req_t *r)


Get Query string length from the request URL.

Note: This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid

Parameters r –[in] The request being responded to


Returns
• Length : Query is found in the request URL
• Zero : Query not found / Null arguments / Invalid request

esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len)


Get Query string from the request URL.

Note:

Espressif Systems 216 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• 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&param2=val2.

Note:
• The components of URL query string (keys and values) are not URLdecoded. The user must check for
‘Content-Type’field in the request headers and then depending upon the specified encoding (URLen-
coded 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

esp_err_t httpd_req_get_cookie_val(httpd_req_t *req, const char *cookie_name, char *val, size_t


*val_size)
Get the value string of a cookie value from the “Cookie”request headers by cookie name.
Parameters
• req –[in] Pointer to the HTTP request
• cookie_name –[in] The cookie name to be searched in the request
• val –[out] Pointer to the buffer into which the value of cookie will be copied if the cookie
is found

Espressif Systems 217 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• val_size –[inout] Pointer to size of the user buffer “val”. This variable
will contain cookie length if ESP_OK is returned and required buffer length incase
ESP_ERR_HTTPD_RESULT_TRUNC is returned.
Returns
• ESP_OK : Key is found in the cookie string and copied to buffer
• ESP_ERR_NOT_FOUND : Key not found
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated
• ESP_ERR_NO_MEM : Memory allocation failure
bool httpd_uri_match_wildcard(const char *uri_template, const char *uri_to_match, size_t
match_upto)
Test if a URI matches the given wildcard template.
Template may end with “?”to make the previous character optional (typically a slash), “*”for a wildcard
match, and “?*”to make the previous character optional, and if present, allow anything to follow.
Example:
• * matches everything
• /foo/? matches /foo and /foo/
• /foo/* (sans the backslash) matches /foo/ and /foo/bar, but not /foo or /fo
• /foo/?* or /foo/*? (sans the backslash) matches /foo/, /foo/bar, and also /foo, but not /foox or /fo
The special characters “?”and “*”anywhere else in the template will be taken literally.
Parameters
• uri_template –[in] URI template (pattern)
• uri_to_match –[in] URI to be matched
• match_upto –[in] how many characters of the URI buffer to test (there may be trailing
query string etc.)
Returns true if a match was found
esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len)
API to send a complete HTTP response.
This API will send the data as an HTTP response to the request. This assumes that you have the entire response
ready in a single buffer. If you wish to send response in incremental chunks use httpd_resp_send_chunk()
instead.
If no status code and content-type were set, by default this will send 200 OK status code and content type
as text/html. You may call the following functions before this API to configure the response headers :
httpd_resp_set_status() - for setting the HTTP status string, httpd_resp_set_type() - for setting the Content
Type, httpd_resp_set_hdr() - for appending any additional field value entries in the response header

Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once this API is called, the request has been responded to.
• No additional data can then be sent for the request.
• Once this API is called, all request headers are purged, so request headers need be copied into separate
buffers if they are required later.

Parameters
• r –[in] The request being responded to
• buf –[in] Buffer from where the content is to be fetched
• buf_len –[in] Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
Returns
• ESP_OK : On successfully sending the response packet
• ESP_ERR_INVALID_ARG : Null request pointer

Espressif Systems 218 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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

Espressif Systems 219 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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:

Espressif Systems 220 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• The header isn’t sent out until any of the send APIs is executed.
• The maximum allowed number of additional headers is limited to value of max_resp_headers in config
structure.
• Make sure that the lifetime of the field value strings are valid till send function is called.

Parameters
• r –[in] The request being responded to
• field –[in] The field name of the HTTP header
• value –[in] The value of this HTTP header
Returns
• ESP_OK : On successfully appending new header
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed
• ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer

esp_err_t httpd_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *msg)


For sending out error code in response to HTTP request.

Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once this API is called, all request headers are purged, so request headers need be copied into separate
buffers if they are required later.
• If you wish to send additional data in the body of the response, please use the lower-level functions
directly.

Parameters
• req –[in] Pointer to the HTTP request for which the response needs to be sent
• error –[in] Error type to send
• msg –[in] Error message string (pass NULL for default message)
Returns
• ESP_OK : On successfully sending the response packet
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_RESP_SEND : Error in raw send
• ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer

static inline esp_err_t httpd_resp_send_404(httpd_req_t *r)


Helper function for HTTP 404.
Send HTTP 404 message. If you wish to send additional data in the body of the response, please use the
lower-level functions directly.

Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once this API is called, all request headers are purged, so request headers need be copied into separate
buffers if they are required later.

Parameters r –[in] The request being responded to


Returns
• ESP_OK : On successfully sending the response packet

Espressif Systems 221 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• ESP_ERR_INVALID_ARG : Null arguments


• ESP_ERR_HTTPD_RESP_SEND : Error in raw send
• ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer

static inline esp_err_t httpd_resp_send_408(httpd_req_t *r)


Helper function for HTTP 408.
Send HTTP 408 message. If you wish to send additional data in the body of the response, please use the
lower-level functions directly.

Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once this API is called, all request headers are purged, so request headers need be copied into separate
buffers if they are required later.

Parameters r –[in] The request being responded to


Returns
• ESP_OK : On successfully sending the response packet
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_RESP_SEND : Error in raw send
• ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer

static inline esp_err_t httpd_resp_send_500(httpd_req_t *r)


Helper function for HTTP 500.
Send HTTP 500 message. If you wish to send additional data in the body of the response, please use the
lower-level functions directly.

Note:
• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Once this API is called, all request headers are purged, so request headers need be copied into separate
buffers if they are required later.

Parameters r –[in] The request being responded to


Returns
• ESP_OK : On successfully sending the response packet
• ESP_ERR_INVALID_ARG : Null arguments
• ESP_ERR_HTTPD_RESP_SEND : Error in raw send
• ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer

int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len)


Raw HTTP send.
Call this API if you wish to construct your custom response packet. When using this, all essential header, eg.
HTTP version, Status Code, Content Type and Length, Encoding, etc. will have to be constructed manually,
and HTTP delimeters (CRLF) will need to be placed correctly for separating sub-sections of the HTTP response
packet.
If the send override function is set, this API will end up calling that function eventually to send data out.

Note:

Espressif Systems 222 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• This API is supposed to be called only from the context of a URI handler where httpd_req_t* request
pointer is valid.
• Unless the response has the correct HTTP structure (which the user must now ensure) it is not guaranteed
that it will be recognized by the client. For most cases, you wouldn’t have to call this API, but you would
rather use either of : httpd_resp_send(), httpd_resp_send_chunk()

Parameters
• r –[in] The request being responded to
• buf –[in] Buffer from where the fully constructed packet is to be read
• buf_len –[in] Length of the buffer
Returns
• Bytes : Number of bytes that were sent successfully
• HTTPD_SOCK_ERR_INVALID : Invalid arguments
• HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
• HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()

int httpd_socket_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags)
A low level API to send data on a given socket

This internally calls the default send function, or the function registered by httpd_sess_set_send_override().

Note: This API is not recommended to be used in any request handler. Use this only for advanced use cases,
wherein some asynchronous data is to be sent over a socket.

Parameters
• hd –[in] server instance
• sockfd –[in] session socket file descriptor
• buf –[in] buffer with bytes to send
• buf_len –[in] data size
• flags –[in] flags for the send() function
Returns
• Bytes : The number of bytes sent successfully
• HTTPD_SOCK_ERR_INVALID : Invalid arguments
• HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
• HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()

int httpd_socket_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags)
A low level API to receive data from a given socket

This internally calls the default recv function, or the function registered by httpd_sess_set_recv_override().

Note: This API is not recommended to be used in any request handler. Use this only for advanced use cases,
wherein some asynchronous communication is required.

Parameters
• hd –[in] server instance
• sockfd –[in] session socket file descriptor
• buf –[in] buffer with bytes to send
• buf_len –[in] data size
• flags –[in] flags for the send() function
Returns
• Bytes : The number of bytes received successfully

Espressif Systems 223 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• 0 : Buffer length parameter is zero / connection closed by peer


• HTTPD_SOCK_ERR_INVALID : Invalid arguments
• HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
• HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()

esp_err_t httpd_register_err_handler(httpd_handle_t handle, httpd_err_code_t error,


httpd_err_handler_func_t handler_fn)
Function for registering HTTP error handlers.
This function maps a handler function to any supported error code given by httpd_err_code_t. See
prototype httpd_err_handler_func_t above for details.
Parameters
• handle –[in] HTTP server handle
• error –[in] Error type
• handler_fn –[in] User implemented handler function (Pass NULL to unset any pre-
viously 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 config-
uration.
Example usage:
//Function for starting the webserver
httpd_handle_t start_webserver(void)
{
// Generate default configuration
httpd_config_t config = HTTPD_DEFAULT_CONFIG();

// Empty handle to http_server


httpd_handle_t server = NULL;

// Start the httpd server


if (httpd_start(&server, &config) == ESP_OK) {
// Register URI handlers
httpd_register_uri_handler(server, &uri_get);
httpd_register_uri_handler(server, &uri_post);
}
// If server failed to start, handle will be NULL
return server;
}

Parameters
• config –[in] Configuration for new instance of the server
• handle –[out] Handle to newly created instance of the server. NULL on error
Returns
• ESP_OK : Instance created successfully
• ESP_ERR_INVALID_ARG : Null argument(s)
• ESP_ERR_HTTPD_ALLOC_MEM : Failed to allocate memory for instance
• ESP_ERR_HTTPD_TASK : Failed to launch server task

esp_err_t httpd_stop(httpd_handle_t handle)


Stops the web server.
Deallocates memory/resources used by an HTTP server instance and deletes it. Once deleted the handle can
no longer be used for accessing the instance.

Espressif Systems 224 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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 persis-
tently opened connection. This facility is for use by such protocols.

Parameters
• handle –[in] Handle to server returned by httpd_start
• work –[in] Pointer to the function to be executed in the HTTPD’s context
• arg –[in] Pointer to the arguments that should be passed to this function
Returns
• ESP_OK : On successfully queueing the work
• ESP_FAIL : Failure in ctrl socket
• ESP_ERR_INVALID_ARG : Null arguments

void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd)


Get session context from socket descriptor.
Typically if a session context is created, it is available to URI handlers through the httpd_req_t structure.
But, there are cases where the web server’s send/receive functions may require the context (for example,
for accessing keying information etc). Since the send/receive function only have the socket descriptor at their
disposal, this API provides them with a way to retrieve the session context.
Parameters
• handle –[in] Handle to server returned by httpd_start
• sockfd –[in] The socket descriptor for which the context should be extracted.
Returns
• void* : Pointer to the context associated with this session
• NULL : Empty context / Invalid handle / Invalid socket fd
void httpd_sess_set_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn)
Set session context by socket descriptor.
Parameters
• handle –[in] Handle to server returned by httpd_start
• sockfd –[in] The socket descriptor for which the context should be extracted.
• ctx –[in] Context object to assign to the session
• free_fn –[in] Function that should be called to free the context

Espressif Systems 225 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

void *httpd_sess_get_transport_ctx(httpd_handle_t handle, int sockfd)


Get session ‘transport’context by socket descriptor.

This context is used by the send/receive functions, for example to manage SSL context.
See also:
httpd_sess_get_ctx()

Parameters
• handle –[in] Handle to server returned by httpd_start
• sockfd –[in] The socket descriptor for which the context should be extracted.
Returns
• void* : Pointer to the transport context associated with this session
• NULL : Empty context / Invalid handle / Invalid socket fd

void httpd_sess_set_transport_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t


free_fn)
Set session ‘transport’context by socket descriptor.

See also:
httpd_sess_set_ctx()

Parameters
• handle –[in] Handle to server returned by httpd_start
• sockfd –[in] The socket descriptor for which the context should be extracted.
• ctx –[in] Transport context object to assign to the session
• free_fn –[in] Function that should be called to free the transport context

void *httpd_get_global_user_ctx(httpd_handle_t handle)


Get HTTPD global user context (it was set in the server config struct)
Parameters handle –[in] Handle to server returned by httpd_start
Returns global user context
void *httpd_get_global_transport_ctx(httpd_handle_t handle)
Get HTTPD global transport context (it was set in the server config struct)
Parameters handle –[in] Handle to server returned by httpd_start
Returns global transport context
esp_err_t httpd_sess_trigger_close(httpd_handle_t handle, int sockfd)
Trigger an httpd session close externally.

Note: Calling this API is only required in special circumstances wherein some application requires to close
an httpd client session asynchronously.

Parameters
• handle –[in] Handle to server returned by httpd_start
• sockfd –[in] The socket descriptor of the session to be closed
Returns
• ESP_OK : On successfully initiating closure
• ESP_FAIL : Failure to queue work
• ESP_ERR_NOT_FOUND : Socket fd not found
• ESP_ERR_INVALID_ARG : Null arguments

Espressif Systems 226 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t httpd_sess_update_lru_counter(httpd_handle_t handle, int sockfd)


Update LRU counter for a given socket.
LRU Counters are internally associated with each session to monitor how recently a session exchanged traffic.
When LRU purge is enabled, if a client is requesting for connection but maximum number of sockets/sessions
is reached, then the session having the earliest LRU counter is closed automatically.
Updating the LRU counter manually prevents the socket from being purged due to the Least Recently Used
(LRU) logic, even though it might not have received traffic for some time. This is useful when all open sock-
ets/session are frequently exchanging traffic but the user specifically wants one of the sessions to be kept open,
irrespective of when it last exchanged a packet.

Note: Calling this API is only necessary if the LRU Purge Enable option is enabled.

Parameters
• handle –[in] Handle to server returned by httpd_start
• sockfd –[in] The socket descriptor of the session for which LRU counter is to be updated
Returns
• ESP_OK : Socket found and LRU counter updated
• ESP_ERR_NOT_FOUND : Socket not found
• ESP_ERR_INVALID_ARG : Null arguments

esp_err_t httpd_get_client_list(httpd_handle_t handle, size_t *fds, int *client_fds)


Returns list of current socket descriptors of active sessions.

Note: Size of provided array has to be equal or greater then maximum number of opened sockets, configured
upon initialization with max_open_sockets field in httpd_config_t structure.

Parameters
• handle –[in] Handle to server returned by httpd_start
• fds –[inout] In: Size of provided client_fds array Out: Number of valid client fds re-
turned in client_fds,
• client_fds –[out] Array of client fds
Returns
• ESP_OK : Successfully retrieved session list
• ESP_ERR_INVALID_ARG : Wrong arguments or list is longer than provided array

Structures

struct esp_http_server_event_data
Argument structure for HTTP_SERVER_EVENT_ON_DATA and HTTP_SERVER_EVENT_SENT_DATA
event

Public Members

int fd
Session socket file descriptor

int data_len
Data length

Espressif Systems 227 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct httpd_config
HTTP Server Configuration Structure.

Note: Use HTTPD_DEFAULT_CONFIG() to initialize the configuration to a default value and then modify
only those fields that are specifically determined by the use case.

Public Members

unsigned task_priority
Priority of FreeRTOS task which runs the server

size_t stack_size
The maximum stack size allowed for the server task

BaseType_t core_id
The core the HTTP server task will run on

uint16_t server_port
TCP Port number for receiving and transmitting HTTP traffic

uint16_t ctrl_port
UDP Port number for asynchronously exchanging control signals between various components of the
server

uint16_t max_open_sockets
Max number of sockets/clients connected at any time (3 sockets are reserved for internal working of the
HTTP server)

uint16_t max_uri_handlers
Maximum allowed uri handlers

uint16_t max_resp_headers
Maximum allowed additional headers in HTTP response

uint16_t backlog_conn
Number of backlog connections

bool lru_purge_enable
Purge “Least Recently Used”connection

uint16_t recv_wait_timeout
Timeout for recv function (in seconds)

uint16_t send_wait_timeout
Timeout for send function (in seconds)

Espressif Systems 228 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

void *global_user_ctx
Global user context.
This field can be used to store arbitrary user data within the server context. The value can be retrieved
using the server handle, available e.g. in the httpd_req_t struct.
When shutting down, the server frees up the user context by calling free() on the global_user_ctx field.
If you wish to use a custom function for freeing the global user context, please specify that here.

httpd_free_ctx_fn_t global_user_ctx_free_fn
Free function for global user context

void *global_transport_ctx
Global transport context.
Similar to global_user_ctx, but used for session encoding or encryption (e.g. to hold the SSL context). It
will be freed using free(), unless global_transport_ctx_free_fn is specified.

httpd_free_ctx_fn_t global_transport_ctx_free_fn
Free function for global transport context

bool enable_so_linger
bool to enable/disable linger

int linger_timeout
linger timeout (in seconds)

bool keep_alive_enable
Enable keep-alive timeout

int keep_alive_idle
Keep-alive idle time. Default is 5 (second)

int keep_alive_interval
Keep-alive interval time. Default is 5 (second)

int keep_alive_count
Keep-alive packet retry send count. Default is 3 counts

httpd_open_func_t open_fn
Custom session opening callback.
Called on a new session socket just after accept(), but before reading any data.
This is an opportunity to set up e.g. SSL encryption using global_transport_ctx and the send/recv/pending
session overrides.
If a context needs to be maintained between these functions, store it in the session using
httpd_sess_set_transport_ctx() and retrieve it later with httpd_sess_get_transport_ctx()
Returning a value other than ESP_OK will immediately close the new socket.

httpd_close_func_t close_fn
Custom session closing callback.

Espressif Systems 229 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Called when a session is deleted, before freeing user and transport contexts and before closing the socket.
This is a place for custom de-init code common to all sockets.
The server will only close the socket if no custom session closing callback is set. If a custom callback is
used, close(sockfd) should be called in here for most cases.
Set the user or transport context to NULL if it was freed here, so the server does not try to free it again.
This function is run for all terminated sessions, including sessions where the socket was closed by the
network stack - that is, the file descriptor may not be valid anymore.

httpd_uri_match_func_t uri_match_fn
URI matcher function.
Called when searching for a matching URI: 1) whose request handler is to be executed right after an HTTP
request is successfully parsed 2) in order to prevent duplication while registering a new URI handler using
httpd_register_uri_handler()
Available options are: 1) NULL : Internally do basic matching using strncmp() 2)
httpd_uri_match_wildcard() : URI wildcard matcher
Users can implement their own matching functions (See description of the
httpd_uri_match_func_t function prototype)

struct httpd_req
HTTP Request Data Structure.

Public Members

httpd_handle_t handle
Handle to server instance

int method
The type of HTTP request, -1 if unsupported method

const char uri[HTTPD_MAX_URI_LEN + 1]


The URI of this request (1 byte extra for null termination)

size_t content_len
Length of the request body

void *aux
Internally used members

void *user_ctx
User context pointer passed during URI registration.

void *sess_ctx
Session Context Pointer
A session context. Contexts are maintained across ‘sessions’for a given open TCP connection. One
session could have multiple request responses. The web server will ensure that the context persists across
all these request and responses.
By default, this is NULL. URI Handlers can set this to any meaningful value.

Espressif Systems 230 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

If the underlying socket gets closed, and this pointer is non-NULL, the web server will free up the context
by calling free(), unless free_ctx function is set.

httpd_free_ctx_fn_t free_ctx
Pointer to free context hook
Function to free session context
If the web server’s socket closes, it frees up the session context by calling free() on the sess_ctx member.
If you wish to use a custom function for freeing the session context, please specify that here.

bool ignore_sess_ctx_changes
Flag indicating if Session Context changes should be ignored
By default, if you change the sess_ctx in some URI handler, the http server will internally free the
earlier context (if non NULL), after the URI handler returns. If you want to manage the alloca-
tion/reallocation/freeing of sess_ctx yourself, set this flag to true, so that the server will not perform
any checks on it. The context will be cleared by the server (by calling free_ctx or free()) only if the
socket gets closed.

struct httpd_uri
Structure for URI handler.

Public Members

const char *uri


The URI to handle

httpd_method_t method
Method supported by the URI

esp_err_t (*handler)(httpd_req_t *r)


Handler to call for supported request method. This must return ESP_OK, or else the underlying socket
will be closed.

void *user_ctx
Pointer to user context data which will be available to handler

Macros

HTTPD_MAX_REQ_HDR_LEN

HTTPD_MAX_URI_LEN

HTTPD_SOCK_ERR_FAIL

HTTPD_SOCK_ERR_INVALID

HTTPD_SOCK_ERR_TIMEOUT

HTTPD_200
HTTP Response 200

Espressif Systems 231 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

HTTPD_204
HTTP Response 204

HTTPD_207
HTTP Response 207

HTTPD_400
HTTP Response 400

HTTPD_404
HTTP Response 404

HTTPD_408
HTTP Response 408

HTTPD_500
HTTP Response 500

HTTPD_TYPE_JSON
HTTP Content type JSON

HTTPD_TYPE_TEXT
HTTP Content type text/HTML

HTTPD_TYPE_OCTET
HTTP Content type octext-stream

ESP_HTTPD_DEF_CTRL_PORT
HTTP Server control socket port
HTTPD_DEFAULT_CONFIG()

ESP_ERR_HTTPD_BASE
Starting number of HTTPD error codes

ESP_ERR_HTTPD_HANDLERS_FULL
All slots for registering URI handlers have been consumed

ESP_ERR_HTTPD_HANDLER_EXISTS
URI handler with same method and target URI already registered

ESP_ERR_HTTPD_INVALID_REQ
Invalid request pointer

ESP_ERR_HTTPD_RESULT_TRUNC
Result string truncated

ESP_ERR_HTTPD_RESP_HDR
Response header field larger than supported

Espressif Systems 232 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_ERR_HTTPD_RESP_SEND
Error occured while sending response packet

ESP_ERR_HTTPD_ALLOC_MEM
Failed to dynamically allocate memory for resource

ESP_ERR_HTTPD_TASK
Failed to launch server task/thread

HTTPD_RESP_USE_STRLEN

Type Definitions

typedef struct httpd_req httpd_req_t


HTTP Request Data Structure.

typedef struct httpd_uri httpd_uri_t


Structure for URI handler.

typedef int (*httpd_send_func_t)(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags)
Prototype for HTTPDs low-level send function.

Note: User specified send function must handle errors internally, depending upon the set value of errno, and
return specific HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as return value of httpd_send()
function

Param hd [in] server instance


Param sockfd [in] session socket file descriptor
Param buf [in] buffer with bytes to send
Param buf_len [in] data size
Param flags [in] flags for the send() function
Return
• Bytes : The number of bytes sent successfully
• HTTPD_SOCK_ERR_INVALID : Invalid arguments
• HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send()
• HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send()

typedef int (*httpd_recv_func_t)(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags)
Prototype for HTTPDs low-level recv function.

Note: User specified recv function must handle errors internally, depending upon the set value of er-
rno, 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

Espressif Systems 233 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• Bytes : The number of bytes received successfully


• 0 : Buffer length parameter is zero / connection closed by peer
• HTTPD_SOCK_ERR_INVALID : Invalid arguments
• HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv()
• HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv()

typedef int (*httpd_pending_func_t)(httpd_handle_t hd, int sockfd)


Prototype for HTTPDs low-level “get pending bytes”function.

Note: User specified pending function must handle errors internally, depending upon the set value of errno,
and return specific HTTPD_SOCK_ERR_ codes, which will be handled accordingly in the server task.

Param hd [in] server instance


Param sockfd [in] session socket file descriptor
Return
• Bytes : The number of bytes waiting to be received
• HTTPD_SOCK_ERR_INVALID : Invalid arguments
• HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket pending()
• HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket pending()

typedef esp_err_t (*httpd_err_handler_func_t)(httpd_req_t *req, httpd_err_code_t error)


Function prototype for HTTP error handling.
This function is executed upon HTTP errors generated during internal processing of an HTTP request. This is
used to override the default behavior on error, which is to send HTTP error response and close the underlying
socket.

Note:
• If implemented, the server will not automatically send out HTTP error response codes, therefore,
httpd_resp_send_err() must be invoked inside this function if user wishes to generate HTTP error re-
sponses.
• When invoked, the validity of uri, method, content_len and user_ctx fields of the httpd_req_t
parameter is not guaranteed as the HTTP request may be partially received/parsed.
• The function must return ESP_OK if underlying socket needs to be kept open. Any other
value will ensure that the socket is closed. The return value is ignored when error is of type
HTTPD_500_INTERNAL_SERVER_ERROR and the socket closed anyway.

Param req [in] HTTP request for which the error needs to be handled
Param error [in] Error type
Return
• ESP_OK : error handled successful
• ESP_FAIL : failure indicates that the underlying socket needs to be closed

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.

Espressif Systems 234 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

typedef void (*httpd_free_ctx_fn_t)(void *ctx)


Prototype for freeing context data (if any)
Param ctx [in] object to free

typedef esp_err_t (*httpd_open_func_t)(httpd_handle_t hd, int sockfd)


Function prototype for opening a session.
Called immediately after the socket was opened to set up the send/recv functions and other parameters of the
socket.
Param hd [in] server instance
Param sockfd [in] session socket file descriptor
Return
• ESP_OK : On success
• Any value other than ESP_OK will signal the server to close the socket immediately

typedef void (*httpd_close_func_t)(httpd_handle_t hd, int sockfd)


Function prototype for closing a session.

Note: It’s possible that the socket descriptor is invalid at this point, the function is called for all terminated
sessions. Ensure proper handling of return codes.

Param hd [in] server instance


Param sockfd [in] session socket file descriptor

typedef bool (*httpd_uri_match_func_t)(const char *reference_uri, const char *uri_to_match, size_t


match_upto)
Function prototype for URI matching.
Param reference_uri [in] URI/template with respect to which the other URI is matched
Param uri_to_match [in] URI/template being matched to the reference URI/template
Param match_upto [in] For specifying the actual length of uri_to_match up to which the
matching algorithm is to be applied (The maximum value is strlen(uri_to_match),
independent of the length of reference_uri)
Return true on match

typedef struct httpd_config httpd_config_t


HTTP Server Configuration Structure.

Note: Use HTTPD_DEFAULT_CONFIG() to initialize the configuration to a default value and then modify
only those fields that are specifically determined by the use case.

typedef void (*httpd_work_fn_t)(void *arg)


Prototype of the HTTPD work function Please refer to httpd_queue_work() for more details.
Param arg [in] The arguments for this work function

Enumerations

enum httpd_err_code_t
Error codes sent as HTTP response in case of errors encountered during processing of an HTTP request.
Values:

Espressif Systems 235 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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

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

Espressif Systems 236 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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

2.2.10 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
– httpd_sess_set_send_override()
– httpd_sess_set_recv_override()
– httpd_sess_set_pending_override()
• “transport context”- both global and session
– httpd_sess_get_transport_ctx() - returns SSL used for the session
– httpd_sess_set_transport_ctx()
– httpd_get_global_transport_ctx() - returns the shared SSL context
– httpd_config::global_transport_ctx
– httpd_config::global_transport_ctx_free_fn
– 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 environ-
ments 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).

Espressif Systems 237 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

API Reference

Header File
• components/esp_https_server/include/esp_https_server.h

Functions
esp_err_t httpd_ssl_start(httpd_handle_t *handle, httpd_ssl_config_t *config)
Create a SSL capable HTTP server (secure mode may be disabled in config)
Parameters
• config –[inout] - server config, must not be const. Does not have to stay valid after
calling this function.
• handle –[out] - storage for the server handle, must be a valid pointer
Returns success
esp_err_t httpd_ssl_stop(httpd_handle_t handle)
Stop the server. Blocks until the server is shut down.
Parameters handle –[in]
Returns
• ESP_OK: Server stopped successfully
• ESP_ERR_INVALID_ARG: Invalid argument
• ESP_FAIL: Failure to shut down server

Structures

struct esp_https_server_user_cb_arg
Callback data struct, contains the ESP-TLS connection handle and the connection state at which the callback
is executed.

Public Members

httpd_ssl_user_cb_state_t user_cb_state
State of user callback

esp_tls_t *tls
ESP-TLS connection handle

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

Espressif Systems 238 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

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!

Espressif Systems 239 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Macros
HTTPD_SSL_CONFIG_DEFAULT()
Default config struct init
(http_server default config had to be copied for customization)
Notes:
• port is set when starting the server, according to ‘transport_mode’
• one socket uses ~ 40kB RAM with SSL, we reduce the default socket count to 4
• SSL sockets are usually long-lived, closing LRU prevents pool exhaustion DOS
• Stack size may need adjustments depending on the user application

Type Definitions

typedef struct esp_https_server_user_cb_arg esp_https_server_user_cb_arg_t


Callback data struct, contains the ESP-TLS connection handle and the connection state at which the callback
is executed.
typedef void esp_https_server_user_cb(esp_https_server_user_cb_arg_t *user_cb)
Callback function prototype Can be used to get connection or client information (SSL context) E.g. Client
certificate, Socket FD, Connection state, etc.
Param user_cb Callback data struct

typedef struct httpd_ssl_config httpd_ssl_config_t

Enumerations

enum httpd_ssl_transport_mode_t
Values:

enumerator HTTPD_SSL_TRANSPORT_SECURE

enumerator HTTPD_SSL_TRANSPORT_INSECURE

enum httpd_ssl_user_cb_state_t
Indicates the state at which the user callback is executed, i.e at session creation or session close.
Values:

enumerator HTTPD_SSL_USER_CB_SESS_CREATE

enumerator HTTPD_SSL_USER_CB_SESS_CLOSE

2.2.11 ICMP Echo

Overview

ICMP (Internet Control Message Protocol) is used for diagnostic or control purposes or generated in response to
errors in IP operations. The common network util ping is implemented based on the ICMP packets with the type
field value of 0, also called Echo Reply.

Espressif Systems 240 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

During a ping session, the source host firstly sends out an ICMP echo request packet and wait for an ICMP echo reply
with specific times. In this way, it also measures the round-trip time for the messages. After receiving a valid ICMP
echo reply, the source host will generate statistics about the IP link layer (e.g., packet loss, elapsed time, etc).
It is common that IoT device needs to check whether a remote server is alive or not. The device should show the
warnings to users when it got offline. It can be achieved by creating a ping session and sending or parsing ICMP echo
packets periodically.
To make this internal procedure much easier for users, ESP-IDF provides some out-of-box APIs.

Create a New Ping Session To create a ping session, you need to fill in the esp_ping_config_t configuration
structure firstly, specifying target IP address, interval times, and etc. Optionally, you can also register some callback
functions with the esp_ping_callbacks_t structure.
Example method to create a new ping session and register callbacks:

static void test_on_ping_success(esp_ping_handle_t hdl, void *args)


{
// optionally, get callback arguments
// const char* str = (const char*) args;
// printf("%s\r\n", str); // "foo"
uint8_t ttl;
uint16_t seqno;
uint32_t elapsed_time, recv_len;
ip_addr_t target_addr;
esp_ping_get_profile(hdl, ESP_PING_PROF_SEQNO, &seqno, sizeof(seqno));
esp_ping_get_profile(hdl, ESP_PING_PROF_TTL, &ttl, sizeof(ttl));
esp_ping_get_profile(hdl, ESP_PING_PROF_IPADDR, &target_addr, sizeof(target_
,→addr));

esp_ping_get_profile(hdl, ESP_PING_PROF_SIZE, &recv_len, sizeof(recv_len));


esp_ping_get_profile(hdl, ESP_PING_PROF_TIMEGAP, &elapsed_time, sizeof(elapsed_
,→time));

printf("%d bytes from %s icmp_seq=%d ttl=%d time=%d ms\n",


recv_len, inet_ntoa(target_addr.u_addr.ip4), seqno, ttl, elapsed_time);
}

static void test_on_ping_timeout(esp_ping_handle_t hdl, void *args)


{
uint16_t seqno;
ip_addr_t target_addr;
esp_ping_get_profile(hdl, ESP_PING_PROF_SEQNO, &seqno, sizeof(seqno));
esp_ping_get_profile(hdl, ESP_PING_PROF_IPADDR, &target_addr, sizeof(target_
,→addr));

printf("From %s icmp_seq=%d timeout\n", inet_ntoa(target_addr.u_addr.ip4),␣


,→seqno);

static void test_on_ping_end(esp_ping_handle_t hdl, void *args)


{
uint32_t transmitted;
uint32_t received;
uint32_t total_time_ms;

esp_ping_get_profile(hdl, ESP_PING_PROF_REQUEST, &transmitted,␣


,→ sizeof(transmitted));
esp_ping_get_profile(hdl, ESP_PING_PROF_REPLY, &received, sizeof(received));
esp_ping_get_profile(hdl, ESP_PING_PROF_DURATION, &total_time_ms, sizeof(total_
,→time_ms));

printf("%d packets transmitted, %d received, time %dms\n", transmitted,␣


,→received, total_time_ms);

(continues on next page)

Espressif Systems 241 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

(continued from previous page)


void initialize_ping()
{
/* convert URL to IP address */
ip_addr_t target_addr;
struct addrinfo hint;
struct addrinfo *res = NULL;
memset(&hint, 0, sizeof(hint));
memset(&target_addr, 0, sizeof(target_addr));
getaddrinfo("www.espressif.com", NULL, &hint, &res);
struct in_addr addr4 = ((struct sockaddr_in *) (res->ai_addr))->sin_addr;
inet_addr_to_ip4addr(ip_2_ip4(&target_addr), &addr4);
freeaddrinfo(res);

esp_ping_config_t ping_config = ESP_PING_DEFAULT_CONFIG();


ping_config.target_addr = target_addr; // target IP address
ping_config.count = ESP_PING_COUNT_INFINITE; // ping in infinite mode, esp_
,→ping_stop can stop it

/* set callback functions */


esp_ping_callbacks_t cbs;
cbs.on_ping_success = test_on_ping_success;
cbs.on_ping_timeout = test_on_ping_timeout;
cbs.on_ping_end = test_on_ping_end;
cbs.cb_args = "foo"; // arguments that feeds to all callback functions, can␣
,→be NULL

cbs.cb_args = eth_event_group;

esp_ping_handle_t ping;
esp_ping_new_session(&ping_config, &cbs, &ping);
}

Start and Stop Ping Session You can start and stop ping session with the handle returned by
esp_ping_new_session. Note that, the ping session does not start automatically after creation. If the ping
session is stopped, and restart again, the sequence number in ICMP packets will recount from zero again.

Delete a Ping Session If a ping session will not be used any more, you can delete it with
esp_ping_delete_session. Please make sure the ping session is in stop state (i.e., you have called
esp_ping_stop before or the ping session has finished all the procedures) when you call this function.

Get Runtime Statistics As the example code above, you can call esp_ping_get_profile to get different
runtime statistics of ping session in the callback function.

Application Example

ICMP echo example: protocols/icmp_echo

API Reference

Header File
• components/lwip/include/apps/ping/ping_sock.h

Functions

Espressif Systems 242 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_ping_new_session(const esp_ping_config_t *config, const esp_ping_callbacks_t *cbs,


esp_ping_handle_t *hdl_out)
Create a ping session.
Parameters
• config –ping configuration
• cbs –a bunch of callback functions invoked by internal ping task
• hdl_out –handle of ping session
Returns
• ESP_ERR_INVALID_ARG: invalid parameters (e.g. configuration is null, etc)
• ESP_ERR_NO_MEM: out of memory
• ESP_FAIL: other internal error (e.g. socket error)
• ESP_OK: create ping session successfully, user can take the ping handle to do follow-on
jobs
esp_err_t esp_ping_delete_session(esp_ping_handle_t hdl)
Delete a ping session.
Parameters hdl –handle of ping session
Returns
• ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc)
• ESP_OK: delete ping session successfully
esp_err_t esp_ping_start(esp_ping_handle_t hdl)
Start the ping session.
Parameters hdl –handle of ping session
Returns
• ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc)
• ESP_OK: start ping session successfully
esp_err_t esp_ping_stop(esp_ping_handle_t hdl)
Stop the ping session.
Parameters hdl –handle of ping session
Returns
• ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc)
• ESP_OK: stop ping session successfully
esp_err_t esp_ping_get_profile(esp_ping_handle_t hdl, esp_ping_profile_t profile, void *data, uint32_t
size)
Get runtime profile of ping session.
Parameters
• hdl –handle of ping session
• profile –type of profile
• data –profile data
• size –profile data size
Returns
• ESP_ERR_INVALID_ARG: invalid parameters (e.g. ping handle is null, etc)
• ESP_ERR_INVALID_SIZE: the actual profile data size doesn’t match the “size”pa-
rameter
• ESP_OK: get profile successfully

Structures

struct esp_ping_callbacks_t
Type of “ping”callback functions.

Public Members

Espressif Systems 243 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

void *cb_args
arguments for callback functions

void (*on_ping_success)(esp_ping_handle_t hdl, void *args)


Invoked by internal ping thread when received ICMP echo reply packet.

void (*on_ping_timeout)(esp_ping_handle_t hdl, void *args)


Invoked by internal ping thread when receive ICMP echo reply packet timeout.

void (*on_ping_end)(esp_ping_handle_t hdl, void *args)


Invoked by internal ping thread when a ping session is finished.

struct esp_ping_config_t
Type of “ping”configuration.

Public Members

uint32_t count
A “ping”session contains count procedures

uint32_t interval_ms
Milliseconds between each ping procedure

uint32_t timeout_ms
Timeout value (in milliseconds) of each ping procedure

uint32_t data_size
Size of the data next to ICMP packet header

int tos
Type of Service, a field specified in the IP header

int ttl
Time to Live,a field specified in the IP header

ip_addr_t target_addr
Target IP address, either IPv4 or IPv6

uint32_t task_stack_size
Stack size of internal ping task

uint32_t task_prio
Priority of internal ping task

uint32_t interface
Netif index, interface=0 means NETIF_NO_INDEX

Espressif Systems 244 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Macros
ESP_PING_DEFAULT_CONFIG()
Default ping configuration.

ESP_PING_COUNT_INFINITE
Set ping count to zero will ping target infinitely

Type Definitions

typedef void *esp_ping_handle_t


Type of “ping”session handle.

Enumerations

enum esp_ping_profile_t
Profile of ping session.
Values:

enumerator ESP_PING_PROF_SEQNO
Sequence number of a ping procedure

enumerator ESP_PING_PROF_TOS
Type of service of a ping procedure

enumerator ESP_PING_PROF_TTL
Time to live of a ping procedure

enumerator ESP_PING_PROF_REQUEST
Number of request packets sent out

enumerator ESP_PING_PROF_REPLY
Number of reply packets received

enumerator ESP_PING_PROF_IPADDR
IP address of replied target

enumerator ESP_PING_PROF_SIZE
Size of received packet

enumerator ESP_PING_PROF_TIMEGAP
Elapsed time between request and reply packet

enumerator ESP_PING_PROF_DURATION
Elapsed time of the whole ping session

2.2.12 mDNS Service

mDNS is a multicast UDP service that is used to provide local network service and host discovery.
The ESP-IDF component mDNS has been moved from ESP-IDF since version v5.0 to a separate repository:

Espressif Systems 245 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• mDNS component on GitHub


To add mDNS component in your project, please run idf.py add-dependency espressif/mdns.

Hosted Documentation

The documentation can be found on the link below:


• mDNS documentation

2.2.13 Mbed TLS

Mbed TLS is a C library that implements cryptographic primitives, X.509 certificate manipulation and the SSL/TLS
and DTLS protocols. Its small code footprint makes it suitable for embedded systems.

Note: ESP-IDF uses a fork of Mbed TLS which includes a few patches (related to hardware routines of certain
modules like bignum (MPI) and ECC) over vanilla Mbed TLS.

Mbed TLS supports SSL 3.0 up to TLS 1.3 and DTLS 1.0 to 1.2 communication by providing the following:
• TCP/IP communication functions: listen, connect, accept, read/write.
• SSL/TLS communication functions: init, handshake, read/write.
• X.509 functions: CRT, CRL and key handling
• Random number generation
• Hashing
• Encryption/decryption
Supported TLS versions include SSL 3.0, TLS 1.0, TLS 1.1, TLS 1.2, and TLS 1.3, but on the latest ESP-IDF, SSL
3.0, TLS 1.0, and TLS 1.1 have been removed from Mbed TLS. Supported DTLS versions include DTLS 1.0, DTLS
1.1, and DTLS 1.2, but on the latest ESP-IDF, DTLS 1.0 has been removed from Mbed TLS.

Mbed TLS Documentation

For Mbed TLS documentation please refer to the following (upstream) pointers:
• API Reference
• Knowledge Base

Mbed TLS Support in ESP-IDF

Please find the information about the Mbed TLS versions presented in different branches of ESP-IDF here.

Note: Please refer the Mbed TLS to migrate from Mbed TLS version 2.x to version 3.0 or greater.

Application Examples

Examples in ESP-IDF use ESP-TLS which provides a simplified API interface for accessing the commonly used TLS
functionality.
Refer to the examples protocols/https_server/simple (Simple HTTPS server) and protocols/https_request (Make
HTTPS requests) for more information.
If the Mbed TLS API is to be used directly, refer to the example protocols/https_mbedtls.

Espressif Systems 246 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Alternatives

ESP-TLS acts as an abstraction layer over the underlying SSL/TLS library and thus has an option to use Mbed TLS
or wolfSSL as the underlying library. By default, only Mbed TLS is available and used in ESP-IDF whereas wolfSSL
is available publicly at <https://github.com/espressif/esp-wolfSSL> with the upstream submodule pointer.
Please refer to ESP-TLS: Underlying SSL/TLS Library Options docs for more information on this and comparison of
Mbed TLS and wolfSSL.

Important Config Options

Following is a brief list of important config options accessible at Component Config -> mbedTLS. The full
list of config options can be found here.

• CONFIG_MBEDTLS_SSL_PROTO_TLS1_2: Support for TLS 1.2


• CONFIG_MBEDTLS_SSL_PROTO_TLS1_3: Support for TLS 1.3
• CONFIG_MBEDTLS_CERTIFICATE_BUNDLE: Support for trusted root certificate bundle (more about this:
ESP x509 Certificate Bundle)
• CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS: Support for TLS Session Resumption: Client session
tickets
• CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS: Support for TLS Session Resumption: Server session
tickets
• CONFIG_MBEDTLS_HARDWARE_SHA: Support for hardware SHA acceleration
• CONFIG_MBEDTLS_HARDWARE_AES: Support for hardware AES acceleration
• CONFIG_MBEDTLS_HARDWARE_MPI: Support for hardware MPI (bignum) acceleration

Note: Mbed TLS v3.0.0 and later support only TLS 1.2 and TLS 1.3 (SSL 3.0, TLS 1.0, TLS 1.1, and DTLS 1.0
are not supported). The support for TLS 1.3 is experimental and only supports the client-side. More information
about this can be found out here.

Performance and Memory Tweaks

Reducing Heap Usage The following table shows typical memory usage with different configs when the proto-
cols/https_request example (with Server Validation enabled) was run with Mbed TLS as the SSL/TLS library.

Mbed TLS Test Related Configs Heap Usage (approx.)


Default NA 42196 B
Enable SSL Variable CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH 42120 B
Length
Disable Keep Peer CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE 38533 B
Certificate
Enable Dynamic CONFIG_MBEDTLS_DYNAMIC_BUFFER CON- 22013 B
TX/RX Buffer FIG_MBEDTLS_DYNAMIC_FREE_CONFIG_DATA
CONFIG_MBEDTLS_DYNAMIC_FREE_CA_CERT

Note: These values are subject to change with change in configuration options and versions of Mbed TLS.

Reducing Binary Size Under Component Config -> mbedTLS, there are multiple Mbed TLS features
which are enabled by default but can be disabled if not needed to save code size. More information can be about this
can be found in Minimizing Binary Size docs.
Code examples for this API section are provided in the protocols directory of ESP-IDF examples.

Espressif Systems 247 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

2.2.14 IP Network Layer

Documentation for IP Network Layer protocols (below the Application Protocol layer) are provided in Networking
APIs.

2.3 Bluetooth® API

2.3.1 Bluetooth® Common

Bluetooth® Generic Defines

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_bt_defs.h

Structures

struct esp_bt_uuid_t
UUID type.

Public Members

uint16_t len
UUID length, 16bit, 32bit or 128bit

uint16_t uuid16
16bit UUID

uint32_t uuid32
32bit UUID

uint8_t uuid128[ESP_UUID_LEN_128]
128bit UUID

union esp_bt_uuid_t::[anonymous] uuid


UUID

Macros
ESP_BLUEDROID_STATUS_CHECK(status)

ESP_BT_STATUS_BASE_FOR_HCI_ERR

ESP_BT_OCTET16_LEN

Espressif Systems 248 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BT_OCTET8_LEN

ESP_DEFAULT_GATT_IF
Default GATT interface id.

ESP_BLE_PRIM_ADV_INT_MIN
Minimum advertising interval for undirected and low duty cycle directed advertising

ESP_BLE_PRIM_ADV_INT_MAX
Maximum advertising interval for undirected and low duty cycle directed advertising

ESP_BLE_CONN_INT_MIN
relate to BTM_BLE_CONN_INT_MIN in stack/btm_ble_api.h

ESP_BLE_CONN_INT_MAX
relate to BTM_BLE_CONN_INT_MAX in stack/btm_ble_api.h

ESP_BLE_CONN_LATENCY_MAX
relate to ESP_BLE_CONN_LATENCY_MAX in stack/btm_ble_api.h

ESP_BLE_CONN_SUP_TOUT_MIN
relate to BTM_BLE_CONN_SUP_TOUT_MIN in stack/btm_ble_api.h

ESP_BLE_CONN_SUP_TOUT_MAX
relate to ESP_BLE_CONN_SUP_TOUT_MAX in stack/btm_ble_api.h
ESP_BLE_IS_VALID_PARAM(x, min, max)
Check the param is valid or not.

ESP_UUID_LEN_16

ESP_UUID_LEN_32

ESP_UUID_LEN_128

ESP_BD_ADDR_LEN
Bluetooth address length.

ESP_BLE_ENC_KEY_MASK
Used to exchange the encryption key in the init key & response key.

ESP_BLE_ID_KEY_MASK
Used to exchange the IRK key in the init key & response key.

ESP_BLE_CSR_KEY_MASK
Used to exchange the CSRK key in the init key & response key.

Espressif Systems 249 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BLE_LINK_KEY_MASK
Used to exchange the link key(this key just used in the BLE & BR/EDR coexist mode) in the init key &
response key.

ESP_APP_ID_MIN
Minimum of the application id.

ESP_APP_ID_MAX
Maximum of the application id.

ESP_BD_ADDR_STR

ESP_BD_ADDR_HEX(addr)

Type Definitions

typedef uint8_t esp_bt_octet16_t[ESP_BT_OCTET16_LEN]

typedef uint8_t esp_bt_octet8_t[ESP_BT_OCTET8_LEN]

typedef uint8_t esp_link_key[ESP_BT_OCTET16_LEN]

typedef uint8_t esp_bd_addr_t[ESP_BD_ADDR_LEN]


Bluetooth device address.

typedef uint8_t esp_ble_key_mask_t

Enumerations

enum esp_bt_status_t
Status Return Value.
Values:

enumerator ESP_BT_STATUS_SUCCESS

enumerator ESP_BT_STATUS_FAIL

enumerator ESP_BT_STATUS_NOT_READY

enumerator ESP_BT_STATUS_NOMEM

enumerator ESP_BT_STATUS_BUSY

enumerator ESP_BT_STATUS_DONE

enumerator ESP_BT_STATUS_UNSUPPORTED

enumerator ESP_BT_STATUS_PARM_INVALID

Espressif Systems 250 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BT_STATUS_UNHANDLED

enumerator ESP_BT_STATUS_AUTH_FAILURE

enumerator ESP_BT_STATUS_RMT_DEV_DOWN

enumerator ESP_BT_STATUS_AUTH_REJECTED

enumerator ESP_BT_STATUS_INVALID_STATIC_RAND_ADDR

enumerator ESP_BT_STATUS_PENDING

enumerator ESP_BT_STATUS_UNACCEPT_CONN_INTERVAL

enumerator ESP_BT_STATUS_PARAM_OUT_OF_RANGE

enumerator ESP_BT_STATUS_TIMEOUT

enumerator ESP_BT_STATUS_PEER_LE_DATA_LEN_UNSUPPORTED

enumerator ESP_BT_STATUS_CONTROL_LE_DATA_LEN_UNSUPPORTED

enumerator ESP_BT_STATUS_ERR_ILLEGAL_PARAMETER_FMT

enumerator ESP_BT_STATUS_MEMORY_FULL

enumerator ESP_BT_STATUS_EIR_TOO_LARGE

enumerator ESP_BT_STATUS_HCI_SUCCESS

enumerator ESP_BT_STATUS_HCI_ILLEGAL_COMMAND

enumerator ESP_BT_STATUS_HCI_NO_CONNECTION

enumerator ESP_BT_STATUS_HCI_HW_FAILURE

enumerator ESP_BT_STATUS_HCI_PAGE_TIMEOUT

enumerator ESP_BT_STATUS_HCI_AUTH_FAILURE

enumerator ESP_BT_STATUS_HCI_KEY_MISSING

enumerator ESP_BT_STATUS_HCI_MEMORY_FULL

enumerator ESP_BT_STATUS_HCI_CONNECTION_TOUT

Espressif Systems 251 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BT_STATUS_HCI_MAX_NUM_OF_CONNECTIONS

enumerator ESP_BT_STATUS_HCI_MAX_NUM_OF_SCOS

enumerator ESP_BT_STATUS_HCI_CONNECTION_EXISTS

enumerator ESP_BT_STATUS_HCI_COMMAND_DISALLOWED

enumerator ESP_BT_STATUS_HCI_HOST_REJECT_RESOURCES

enumerator ESP_BT_STATUS_HCI_HOST_REJECT_SECURITY

enumerator ESP_BT_STATUS_HCI_HOST_REJECT_DEVICE

enumerator ESP_BT_STATUS_HCI_HOST_TIMEOUT

enumerator ESP_BT_STATUS_HCI_UNSUPPORTED_VALUE

enumerator ESP_BT_STATUS_HCI_ILLEGAL_PARAMETER_FMT

enumerator ESP_BT_STATUS_HCI_PEER_USER

enumerator ESP_BT_STATUS_HCI_PEER_LOW_RESOURCES

enumerator ESP_BT_STATUS_HCI_PEER_POWER_OFF

enumerator ESP_BT_STATUS_HCI_CONN_CAUSE_LOCAL_HOST

enumerator ESP_BT_STATUS_HCI_REPEATED_ATTEMPTS

enumerator ESP_BT_STATUS_HCI_PAIRING_NOT_ALLOWED

enumerator ESP_BT_STATUS_HCI_UNKNOWN_LMP_PDU

enumerator ESP_BT_STATUS_HCI_UNSUPPORTED_REM_FEATURE

enumerator ESP_BT_STATUS_HCI_SCO_OFFSET_REJECTED

enumerator ESP_BT_STATUS_HCI_SCO_INTERVAL_REJECTED

enumerator ESP_BT_STATUS_HCI_SCO_AIR_MODE

enumerator ESP_BT_STATUS_HCI_INVALID_LMP_PARAM

enumerator ESP_BT_STATUS_HCI_UNSPECIFIED

Espressif Systems 252 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BT_STATUS_HCI_UNSUPPORTED_LMP_PARAMETERS

enumerator ESP_BT_STATUS_HCI_ROLE_CHANGE_NOT_ALLOWED

enumerator ESP_BT_STATUS_HCI_LMP_RESPONSE_TIMEOUT

enumerator ESP_BT_STATUS_HCI_LMP_ERR_TRANS_COLLISION

enumerator ESP_BT_STATUS_HCI_LMP_PDU_NOT_ALLOWED

enumerator ESP_BT_STATUS_HCI_ENCRY_MODE_NOT_ACCEPTABLE

enumerator ESP_BT_STATUS_HCI_UNIT_KEY_USED

enumerator ESP_BT_STATUS_HCI_QOS_NOT_SUPPORTED

enumerator ESP_BT_STATUS_HCI_INSTANT_PASSED

enumerator ESP_BT_STATUS_HCI_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED

enumerator ESP_BT_STATUS_HCI_DIFF_TRANSACTION_COLLISION

enumerator ESP_BT_STATUS_HCI_UNDEFINED_0x2B

enumerator ESP_BT_STATUS_HCI_QOS_UNACCEPTABLE_PARAM

enumerator ESP_BT_STATUS_HCI_QOS_REJECTED

enumerator ESP_BT_STATUS_HCI_CHAN_CLASSIF_NOT_SUPPORTED

enumerator ESP_BT_STATUS_HCI_INSUFFCIENT_SECURITY

enumerator ESP_BT_STATUS_HCI_PARAM_OUT_OF_RANGE

enumerator ESP_BT_STATUS_HCI_UNDEFINED_0x31

enumerator ESP_BT_STATUS_HCI_ROLE_SWITCH_PENDING

enumerator ESP_BT_STATUS_HCI_UNDEFINED_0x33

enumerator ESP_BT_STATUS_HCI_RESERVED_SLOT_VIOLATION

enumerator ESP_BT_STATUS_HCI_ROLE_SWITCH_FAILED

enumerator ESP_BT_STATUS_HCI_INQ_RSP_DATA_TOO_LARGE

Espressif Systems 253 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BT_STATUS_HCI_SIMPLE_PAIRING_NOT_SUPPORTED

enumerator ESP_BT_STATUS_HCI_HOST_BUSY_PAIRING

enumerator ESP_BT_STATUS_HCI_REJ_NO_SUITABLE_CHANNEL

enumerator ESP_BT_STATUS_HCI_CONTROLLER_BUSY

enumerator ESP_BT_STATUS_HCI_UNACCEPT_CONN_INTERVAL

enumerator ESP_BT_STATUS_HCI_DIRECTED_ADVERTISING_TIMEOUT

enumerator ESP_BT_STATUS_HCI_CONN_TOUT_DUE_TO_MIC_FAILURE

enumerator ESP_BT_STATUS_HCI_CONN_FAILED_ESTABLISHMENT

enumerator ESP_BT_STATUS_HCI_MAC_CONNECTION_FAILED

enum esp_bt_dev_type_t
Bluetooth device type.
Values:

enumerator ESP_BT_DEVICE_TYPE_BREDR

enumerator ESP_BT_DEVICE_TYPE_BLE

enumerator ESP_BT_DEVICE_TYPE_DUMO

enum esp_ble_addr_type_t
BLE device address type.
Values:

enumerator BLE_ADDR_TYPE_PUBLIC
Public Device Address

enumerator BLE_ADDR_TYPE_RANDOM
Random Device Address. To set this address, use the function
esp_ble_gap_set_rand_addr(esp_bd_addr_t rand_addr)

enumerator BLE_ADDR_TYPE_RPA_PUBLIC
Resolvable Private Address (RPA) with public identity address

enumerator BLE_ADDR_TYPE_RPA_RANDOM
Resolvable Private Address (RPA) with random identity address. To set this address, use the function
esp_ble_gap_set_rand_addr(esp_bd_addr_t rand_addr)

Espressif Systems 254 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enum esp_ble_wl_addr_type_t
white list address type
Values:

enumerator BLE_WL_ADDR_TYPE_PUBLIC

enumerator BLE_WL_ADDR_TYPE_RANDOM

Bluetooth® Main API

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_bt_main.h

Functions
esp_bluedroid_status_t esp_bluedroid_get_status(void)
Get bluetooth stack status.
Returns Bluetooth stack status
esp_err_t esp_bluedroid_enable(void)
Enable bluetooth, must after esp_bluedroid_init()/esp_bluedroid_init_with_cfg().
Returns
• ESP_OK : Succeed
• Other : Failed
esp_err_t esp_bluedroid_disable(void)
Disable bluetooth, must prior to esp_bluedroid_deinit().
Returns
• ESP_OK : Succeed
• Other : Failed
esp_err_t esp_bluedroid_init(void)
Init and alloc the resource for bluetooth, must be prior to every bluetooth stuff.
Returns
• ESP_OK : Succeed
• Other : Failed
esp_err_t esp_bluedroid_init_with_cfg(esp_bluedroid_config_t *cfg)
Init and alloc the resource for bluetooth, must be prior to every bluetooth stuff.
Parameters cfg –Initial configuration of ESP Bluedroid stack.
Returns
• ESP_OK : Succeed
• Other : Failed
esp_err_t esp_bluedroid_deinit(void)
Deinit and free the resource for bluetooth, must be after every bluetooth stuff.
Returns
• ESP_OK : Succeed
• Other : Failed

Espressif Systems 255 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Structures

struct esp_bluedroid_config_t
Bluetooth stack configuration.

Public Members

bool ssp_en
Whether SSP(secure simple pairing) or legacy pairing is used for Classic Bluetooth

Macros
BT_BLUEDROID_INIT_CONFIG_DEFAULT()

Enumerations

enum esp_bluedroid_status_t
Bluetooth stack status type, to indicate whether the bluetooth stack is ready.
Values:

enumerator ESP_BLUEDROID_STATUS_UNINITIALIZED
Bluetooth not initialized

enumerator ESP_BLUEDROID_STATUS_INITIALIZED
Bluetooth initialized but not enabled

enumerator ESP_BLUEDROID_STATUS_ENABLED
Bluetooth initialized and enabled

Bluetooth® Device APIs

Overview Bluetooth device reference APIs.

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_bt_device.h

Functions
const uint8_t *esp_bt_dev_get_address(void)
Get bluetooth device address. Must use after “esp_bluedroid_enable”.
Returns bluetooth device address (six bytes), or NULL if bluetooth stack is not enabled
esp_err_t esp_bt_dev_set_device_name(const char *name)
Set bluetooth device name. This function should be called after esp_bluedroid_enable() completes successfully.
A BR/EDR/LE device type shall have a single Bluetooth device name which shall be identical irrespective of
the physical channel used to perform the name discovery procedure.
Parameters name –[in] : device name to be set
Returns

Espressif Systems 256 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• ESP_OK : Succeed
• ESP_ERR_INVALID_ARG : if name is NULL pointer or empty, or string length out of
limit
• ESP_ERR_INVALID_STATE : if bluetooth stack is not yet enabled
• ESP_FAIL : others
esp_err_t esp_bt_dev_coex_status_config(esp_bt_dev_coex_type_t type, esp_bt_dev_coex_op_t op,
uint8_t status)
Config bluetooth device coexis status. This function should be called after esp_bluedroid_enable() completes
successfully.
Parameters
• type –[in] : coexist type to operate on
• op –[in] : clear or set coexist status
• status –[in] : coexist status to be configured
Returns
• ESP_OK : Succeed
• ESP_ERR_INVALID_ARG : if name is NULL pointer or empty, or string length out of
limit
• ESP_ERR_INVALID_STATE : if bluetooth stack is not yet enabled
• ESP_FAIL : others

Macros

ESP_BT_DEV_COEX_BLE_ST_MESH_CONFIG

ESP_BT_DEV_COEX_BLE_ST_MESH_TRAFFIC

ESP_BT_DEV_COEX_BLE_ST_MESH_STANDBY

ESP_BT_DEV_COEX_BT_ST_A2DP_STREAMING

ESP_BT_DEV_COEX_BT_ST_A2DP_PAUSED

ESP_BT_DEV_COEX_OP_CLEAR

ESP_BT_DEV_COEX_OP_SET

Type Definitions

typedef uint8_t esp_bt_dev_coex_op_t

Enumerations

enum esp_bt_dev_coex_type_t
Bluetooth device coex type.
Values:

enumerator ESP_BT_DEV_COEX_TYPE_BLE

enumerator ESP_BT_DEV_COEX_TYPE_BT

Espressif Systems 257 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

2.3.2 Bluetooth® Low Energy (Bluetooth LE)

GAP API

Application Example Check the bluetooth/bluedroid/ble folder in ESP-IDF examples, which contains the follow-
ing demos and their tutorials:
• The following shows an SMP security client demo with its tutorial. This demo initiates its security parameters
and acts as a GATT client, which can send a security request to the peer device and then complete the encryption
procedure.
– bluetooth/bluedroid/ble/gatt_security_client
– GATT Security Client Example Walkthrough
• The following shows an SMP security server demo with its tutorial. This demo initiates its security parameters
and acts as a GATT server, which can send a pair request to the peer device and then complete the encryption
procedure.
– bluetooth/bluedroid/ble/gatt_security_server
– GATT Security Server Example Walkthrough

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_gap_ble_api.h

Functions
esp_err_t esp_ble_gap_register_callback(esp_gap_ble_cb_t callback)
This function is called to occur gap event, such as scan result.
Parameters callback –[in] callback function
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_config_adv_data(esp_ble_adv_data_t *adv_data)
This function is called to override the BTA default ADV parameters.
Parameters adv_data –[in] Pointer to User defined ADV data structure. This memory space
can not be freed until callback of config_adv_data is received.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_set_scan_params(esp_ble_scan_params_t *scan_params)
This function is called to set scan parameters.
Parameters scan_params –[in] Pointer to User defined scan_params data structure. This
memory space can not be freed until callback of set_scan_params
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_start_scanning(uint32_t duration)
This procedure keep the device scanning the peer device which advertising on the air.
Parameters duration –[in] Keeping the scanning time, the unit is second.
Returns
• ESP_OK : success

Espressif Systems 258 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• other : failed
esp_err_t esp_ble_gap_stop_scanning(void)
This function call to stop the device scanning the peer device which advertising on the air.
Returns
• ESP_OK : success
– other : failed
esp_err_t esp_ble_gap_start_advertising(esp_ble_adv_params_t *adv_params)
This function is called to start advertising.
Parameters adv_params –[in] pointer to User defined adv_params data structure.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_stop_advertising(void)
This function is called to stop advertising.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_update_conn_params(esp_ble_conn_update_params_t *params)
Update connection parameters, can only be used when connection is up.
Parameters params –[in] - connection update parameters
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_set_pkt_data_len(esp_bd_addr_t remote_device, uint16_t tx_data_length)
This function is to set maximum LE data packet size.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_set_rand_addr(esp_bd_addr_t rand_addr)
This function allows configuring either a Non-Resolvable Private Address or a Static Random Address.
Parameters rand_addr –[in] The address to be configured. Refer to the table below for possible
address subtypes:

| address [47:46] | Address Type |


|-----------------|--------------------------|
| 0b00 | Non-Resolvable Private |
| | Address |
|-----------------|--------------------------|
| 0b11 | Static Random Address |
|-----------------|--------------------------|

Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_clear_rand_addr(void)
This function clears the random address for the application.
Returns
• ESP_OK : success
• other : failed

Espressif Systems 259 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_ble_gap_config_local_privacy(bool privacy_enable)


Enable/disable privacy (including address resolution) on the local device.
Parameters privacy_enable –[in] - enable/disable privacy on remote device.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_config_local_icon(uint16_t icon)
set local gap appearance icon
Parameters icon –[in] - External appearance value, these values are defined by the Bluetooth
SIG, please refer to https://www.bluetooth.com/specifications/assigned-numbers/
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_update_whitelist(bool add_remove, esp_bd_addr_t remote_bda,
esp_ble_wl_addr_type_t wl_addr_type)
Add or remove device from white list.
Parameters
• add_remove –[in] the value is true if added the ble device to the white list, and false
remove to the white list.
• remote_bda –[in] the remote device address add/remove from the white list.
• wl_addr_type –[in] whitelist address type
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_clear_whitelist(void)
Clear all white list.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_get_whitelist_size(uint16_t *length)
Get the whitelist size in the controller.
Parameters length –[out] the white list length.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_set_prefer_conn_params(esp_bd_addr_t bd_addr, uint16_t min_conn_int,
uint16_t max_conn_int, uint16_t slave_latency,
uint16_t supervision_tout)
This function is called to set the preferred connection parameters when default connection parameter is not
desired before connecting. This API can only be used in the master role.
Parameters
• bd_addr –[in] BD address of the peripheral
• min_conn_int –[in] minimum preferred connection interval
• max_conn_int –[in] maximum preferred connection interval
• slave_latency –[in] preferred slave latency
• supervision_tout –[in] preferred supervision timeout
Returns
• ESP_OK : success
• other : failed

Espressif Systems 260 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_ble_gap_set_device_name(const char *name)


Set device name to the local device Note: This API don’t affect the advertising data.
Parameters name –[in] - device name.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_get_device_name(void)
Get device name of the local device.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_get_local_used_addr(esp_bd_addr_t local_used_addr, uint8_t *addr_type)
This function is called to get local used address and address type. uint8_t *esp_bt_dev_get_address(void) get
the public address.
Parameters
• local_used_addr –[in] - current local used ble address (six bytes)
• addr_type –[in] - ble address type
Returns - ESP_OK : success
• other : failed
uint8_t *esp_ble_resolve_adv_data(uint8_t *adv_data, uint8_t type, uint8_t *length)
This function is called to get ADV data for a specific type.
Parameters
• adv_data –[in] - pointer of ADV data which to be resolved
• type –[in] - finding ADV data type
• length –[out] - return the length of ADV data not including type
Returns pointer of ADV data
esp_err_t esp_ble_gap_config_adv_data_raw(uint8_t *raw_data, uint32_t raw_data_len)
This function is called to set raw advertising data. User need to fill ADV data by self.
Parameters
• raw_data –[in] : raw advertising data with the format: [Length 1][Data Type 1][Data
1][Length 2][Data Type 2][Data 2] …
• raw_data_len –[in] : raw advertising data length , less than 31 bytes
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_config_scan_rsp_data_raw(uint8_t *raw_data, uint32_t raw_data_len)
This function is called to set raw scan response data. User need to fill scan response data by self.
Parameters
• raw_data –[in] : raw scan response data
• raw_data_len –[in] : raw scan response data length , less than 31 bytes
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_read_rssi(esp_bd_addr_t remote_addr)
This function is called to read the RSSI of remote device. The address of link policy results are returned in the
gap callback function with ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT event.
Parameters remote_addr –[in] : The remote connection device address.
Returns
• ESP_OK : success
• other : failed

Espressif Systems 261 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_ble_gap_add_duplicate_scan_exceptional_device(esp_ble_duplicate_exceptional_info_type_t
type, esp_duplicate_info_t
device_info)
This function is called to add a device info into the duplicate scan exceptional list.
Parameters
• type –[in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t
when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or
MESH_PROXY_SRV_ADV , device_info is invalid.
• device_info –[in] the device information.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_remove_duplicate_scan_exceptional_device(esp_ble_duplicate_exceptional_info_type_t
type,
esp_duplicate_info_t
device_info)
This function is called to remove a device info from the duplicate scan exceptional list.
Parameters
• type –[in] device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t
when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or
MESH_PROXY_SRV_ADV , device_info is invalid.
• device_info –[in] the device information.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_clean_duplicate_scan_exceptional_list(esp_duplicate_scan_exceptional_list_type_t
list_type)
This function is called to clean the duplicate scan exceptional list. This API will delete all device information
in the duplicate scan exceptional list.
Parameters list_type –[in] duplicate scan exceptional list type, the value can be one or more
of esp_duplicate_scan_exceptional_list_type_t.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_set_security_param(esp_ble_sm_param_t param_type, void *value, uint8_t
len)
Set a GAP security parameter value. Overrides the default value.

Secure connection is highly recommended to avoid some major


vulnerabilities like 'Impersonation in the Pin Pairing Protocol'
(CVE-2020-26555) and 'Authentication of the LE Legacy Pairing
Protocol'.

To accept only `secure connection mode`, it is necessary do as␣


,→following:

1. Set bit `ESP_LE_AUTH_REQ_SC_ONLY` (`param_type` is


`ESP_BLE_SM_AUTHEN_REQ_MODE`), bit `ESP_LE_AUTH_BOND` and bit
`ESP_LE_AUTH_REQ_MITM` is optional as required.

2. Set to `ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_ENABLE` (`param_


,→type` is
`ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH`).

Espressif Systems 262 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters
• param_type –[in] : the type of the param which to be set
• value –[in] : the param value
• len –[in] : the length of the param value
Returns - ESP_OK : success
• other : failed

esp_err_t esp_ble_gap_security_rsp(esp_bd_addr_t bd_addr, bool accept)


Grant security request access.
Parameters
• bd_addr –[in] : BD address of the peer
• accept –[in] : accept the security request or not
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_set_encryption(esp_bd_addr_t bd_addr, esp_ble_sec_act_t sec_act)
Set a gap parameter value. Use this function to change the default GAP parameter values.
Parameters
• bd_addr –[in] : the address of the peer device need to encryption
• sec_act –[in] : This is the security action to indicate what kind of BLE security level
is required for the BLE link if the BLE is supported
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_passkey_reply(esp_bd_addr_t bd_addr, bool accept, uint32_t passkey)
Reply the key value to the peer device in the legacy connection stage.
Parameters
• bd_addr –[in] : BD address of the peer
• accept –[in] : passkey entry successful or declined.
• passkey –[in] : passkey value, must be a 6 digit number, can be lead by 0.
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_confirm_reply(esp_bd_addr_t bd_addr, bool accept)
Reply the confirm value to the peer device in the secure connection stage.
Parameters
• bd_addr –[in] : BD address of the peer device
• accept –[in] : numbers to compare are the same or different.
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_remove_bond_device(esp_bd_addr_t bd_addr)
Removes a device from the security database list of peer device. It manages unpairing event while connected.
Parameters bd_addr –[in] : BD address of the peer device
Returns - ESP_OK : success
• other : failed
int esp_ble_get_bond_device_num(void)
Get the device number from the security database list of peer device. It will return the device bonded number
immediately.
Returns - >= 0 : bonded devices number.
• ESP_FAIL : failed
esp_err_t esp_ble_get_bond_device_list(int *dev_num, esp_ble_bond_dev_t *dev_list)
Get the device from the security database list of peer device. It will return the device bonded information
immediately.

Espressif Systems 263 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters
• dev_num –[inout] Indicate the dev_list array(buffer) size as input. If dev_num is large
enough, it means the actual number as output. Suggest that dev_num value equal to
esp_ble_get_bond_device_num().
• dev_list –[out] an array(buffer) of esp_ble_bond_dev_t type. Use for storing
the bonded devices address. The dev_list should be allocated by who call this API.
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_oob_req_reply(esp_bd_addr_t bd_addr, uint8_t *TK, uint8_t len)
This function is called to provide the OOB data for SMP in response to ESP_GAP_BLE_OOB_REQ_EVT.
Parameters
• bd_addr –[in] BD address of the peer device.
• TK –[in] Temporary Key value, the TK value shall be a 128-bit random number
• len –[in] length of temporary key, should always be 128-bit
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_sc_oob_req_reply(esp_bd_addr_t bd_addr, uint8_t p_c[16], uint8_t p_r[16])
This function is called to provide the OOB data for SMP in response to
ESP_GAP_BLE_SC_OOB_REQ_EVT.
Parameters
• bd_addr –[in] BD address of the peer device.
• p_c –[in] Confirmation value, it shall be a 128-bit random number
• p_r –[in] Randomizer value, it should be a 128-bit random number
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_create_sc_oob_data(void)
This function is called to create the OOB data for SMP when secure connection.
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_disconnect(esp_bd_addr_t remote_device)
This function is to disconnect the physical connection of the peer device gattc may have multiple virtual GATT
server connections when multiple app_id registered. esp_ble_gattc_close (esp_gatt_if_t gattc_if, uint16_t
conn_id) only close one virtual GATT server connection. if there exist other virtual GATT server connec-
tions, it does not disconnect the physical connection. esp_ble_gap_disconnect(esp_bd_addr_t remote_device)
disconnect the physical connection directly.
Parameters remote_device –[in] : BD address of the peer device
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_get_current_conn_params(esp_bd_addr_t bd_addr, esp_gap_conn_params_t
*conn_params)
This function is called to read the connection parameters information of the device.
Parameters
• bd_addr –[in] BD address of the peer device.
• conn_params –[out] the connection parameters information
Returns - ESP_OK : success
• other : failed
esp_err_t esp_gap_ble_set_channels(esp_gap_ble_channels channels)
BLE set channels.
Parameters channels –[in] : The n th such field (in the range 0 to 36) contains the value for
the link layer channel index n. 0 means channel n is bad. 1 means channel n is unknown. The

Espressif Systems 264 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

most significant bits are reserved and shall be set to 0. At least one channel shall be marked as
unknown.
Returns - ESP_OK : success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other : failed
esp_err_t esp_gap_ble_set_authorization(esp_bd_addr_t bd_addr, bool authorize)
This function is called to authorized a link after Authentication(MITM protection)
Parameters
• bd_addr –[in] BD address of the peer device.
• authorize –[out] Authorized the link or not.
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_read_phy(esp_bd_addr_t bd_addr)
This function is used to read the current transmitter PHY and receiver PHY on the connection identified by
remote address.
Parameters bd_addr –[in] : BD address of the peer device
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_set_preferred_default_phy(esp_ble_gap_phy_mask_t tx_phy_mask,
esp_ble_gap_phy_mask_t rx_phy_mask)
This function is used to allows the Host to specify its preferred values for the transmitter PHY and receiver
PHY to be used for all subsequent connections over the LE transport.
Parameters
• tx_phy_mask –[in] : indicates the transmitter PHYs that the Host prefers the Controller
to use
• rx_phy_mask –[in] : indicates the receiver PHYs that the Host prefers the Controller
to use
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_set_preferred_phy(esp_bd_addr_t bd_addr, esp_ble_gap_all_phys_t
all_phys_mask, esp_ble_gap_phy_mask_t tx_phy_mask,
esp_ble_gap_phy_mask_t rx_phy_mask,
esp_ble_gap_prefer_phy_options_t phy_options)
This function is used to set the PHY preferences for the connection identified by the remote address. The
Controller might not be able to make the change (e.g. because the peer does not support the requested PHY)
or may decide that the current PHY is preferable.
Parameters
• bd_addr –[in] : remote address
• all_phys_mask –[in] : a bit field that allows the Host to specify
• tx_phy_mask –[in] : a bit field that indicates the transmitter PHYs that the Host prefers
the Controller to use
• rx_phy_mask –[in] : a bit field that indicates the receiver PHYs that the Host prefers
the Controller to use
• phy_options –[in] : a bit field that allows the Host to specify options for PHYs
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_ext_adv_set_rand_addr(uint8_t instance, esp_bd_addr_t rand_addr)
This function is used by the Host to set the random device address specified by the Random_Address parameter.
Parameters
• instance –[in] : Used to identify an advertising set
• rand_addr –[in] : Random Device Address
Returns - ESP_OK : success

Espressif Systems 265 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• other : failed
esp_err_t esp_ble_gap_ext_adv_set_params(uint8_t instance, const esp_ble_gap_ext_adv_params_t
*params)
This function is used by the Host to set the advertising parameters.
Parameters
• instance –[in] : identifies the advertising set whose parameters are being configured.
• params –[in] : advertising parameters
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_config_ext_adv_data_raw(uint8_t instance, uint16_t length, const uint8_t
*data)
This function is used to set the data used in advertising PDUs that have a data field.
Parameters
• instance –[in] : identifies the advertising set whose data are being configured
• length –[in] : data length
• data –[in] : data information
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_config_ext_scan_rsp_data_raw(uint8_t instance, uint16_t length, const
uint8_t *scan_rsp_data)
This function is used to provide scan response data used in scanning response PDUs.
Parameters
• instance –[in] : identifies the advertising set whose response data are being configured.
• length –[in] : responsedata length
• scan_rsp_data –[in] : response data information
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_ext_adv_start(uint8_t num_adv, const esp_ble_gap_ext_adv_t *ext_adv)
This function is used to request the Controller to enable one or more advertising sets using the advertising sets
identified by the instance parameter.
Parameters
• num_adv –[in] : Number of advertising sets to enable or disable
• ext_adv –[in] : adv parameters
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_ext_adv_stop(uint8_t num_adv, const uint8_t *ext_adv_inst)
This function is used to request the Controller to disable one or more advertising sets using the advertising sets
identified by the instance parameter.
Parameters
• num_adv –[in] : Number of advertising sets to enable or disable
• ext_adv_inst –[in] : ext adv instance
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_ext_adv_set_remove(uint8_t instance)
This function is used to remove an advertising set from the Controller.
Parameters instance –[in] : Used to identify an advertising set
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_ext_adv_set_clear(void)
This function is used to remove all existing advertising sets from the Controller.

Espressif Systems 266 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Returns - ESP_OK : success


• other : failed
esp_err_t esp_ble_gap_periodic_adv_set_params(uint8_t instance, const
esp_ble_gap_periodic_adv_params_t *params)
This function is used by the Host to set the parameters for periodic advertising.
Parameters
• instance –[in] : identifies the advertising set whose periodic advertising parameters
are being configured.
• params –[in] : periodic adv parameters
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_config_periodic_adv_data_raw(uint8_t instance, uint16_t length, const
uint8_t *data)
This function is used to set the data used in periodic advertising PDUs.
Parameters
• instance –[in] : identifies the advertising set whose periodic advertising parameters
are being configured.
• length –[in] : the length of periodic data
• data –[in] : periodic data information
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_start(uint8_t instance)
This function is used to request the Controller to enable the periodic advertising for the advertising set specified.
Parameters instance –[in] : Used to identify an advertising set
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_stop(uint8_t instance)
This function is used to request the Controller to disable the periodic advertising for the advertising set specified.
Parameters instance –[in] : Used to identify an advertising set
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_set_ext_scan_params(const esp_ble_ext_scan_params_t *params)
This function is used to set the extended scan parameters to be used on the advertising channels.
Parameters params –[in] : scan parameters
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_start_ext_scan(uint32_t duration, uint16_t period)
This function is used to enable scanning.
Parameters
• duration –[in] : Scan duration
• period –[in] : Time interval from when the Controller started its last Scan Duration
until it begins the subsequent Scan Duration.
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_stop_ext_scan(void)
This function is used to disable scanning.
Returns - ESP_OK : success
• other : failed

Espressif Systems 267 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_ble_gap_periodic_adv_create_sync(const esp_ble_gap_periodic_adv_sync_params_t


*params)
This function is used to synchronize with periodic advertising from an advertiser and begin receiving periodic
advertising packets.
Parameters params –[in] : sync parameters
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_sync_cancel(void)
This function is used to cancel the LE_Periodic_Advertising_Create_Sync command while it is pending.
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_sync_terminate(uint16_t sync_handle)
This function is used to stop reception of the periodic advertising identified by the Sync Handle parameter.
Parameters sync_handle –[in] : identify the periodic advertiser
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_add_dev_to_list(esp_ble_addr_type_t addr_type,
esp_bd_addr_t addr, uint8_t sid)
This function is used to add a single device to the Periodic Advertiser list stored in the Controller.
Parameters
• addr_type –[in] : address type
• addr –[in] : Device Address
• sid –[in] : Advertising SID subfield in the ADI field used to identify the Periodic Ad-
vertising
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_remove_dev_from_list(esp_ble_addr_type_t addr_type,
esp_bd_addr_t addr, uint8_t sid)
This function is used to remove one device from the list of Periodic Advertisers stored in the Controller.
Removals from the Periodic Advertisers List take effect immediately.
Parameters
• addr_type –[in] : address type
• addr –[in] : Device Address
• sid –[in] : Advertising SID subfield in the ADI field used to identify the Periodic Ad-
vertising
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_clear_dev(void)
This function is used to remove all devices from the list of Periodic Advertisers in the Controller.
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_prefer_ext_connect_params_set(esp_bd_addr_t addr,
esp_ble_gap_phy_mask_t phy_mask,
const esp_ble_gap_conn_params_t
*phy_1m_conn_params, const
esp_ble_gap_conn_params_t
*phy_2m_conn_params, const
esp_ble_gap_conn_params_t
*phy_coded_conn_params)
This function is used to set aux connection parameters.

Espressif Systems 268 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters
• addr –[in] : device address
• phy_mask –[in] : indicates the PHY(s) on which the advertising packets should be re-
ceived on the primary advertising channel and the PHYs for which connection parameters
have been specified.
• phy_1m_conn_params –[in] : Scan connectable advertisements on the LE 1M PHY.
Connection parameters for the LE 1M PHY are provided.
• phy_2m_conn_params –[in] : Connection parameters for the LE 2M PHY are pro-
vided.
• phy_coded_conn_params –[in] : Scan connectable advertisements on the LE
Coded PHY. Connection parameters for the LE Coded PHY are provided.
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_recv_enable(uint16_t sync_handle, uint8_t enable)
This function is used to set periodic advertising receive enable.
Parameters
• sync_handle –[in] : Handle of periodic advertising sync
• enable –[in] : Determines whether reporting and duplicate filtering are enabled or dis-
abled
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_sync_trans(esp_bd_addr_t addr, uint16_t service_data,
uint16_t sync_handle)
This function is used to transfer periodic advertising sync.
Parameters
• addr –[in] : Peer device address
• service_data –[in] : Service data used by Host
• sync_handle –[in] : Handle of periodic advertising sync
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_periodic_adv_set_info_trans(esp_bd_addr_t addr, uint16_t service_data,
uint8_t adv_handle)
This function is used to transfer periodic advertising set info.
Parameters
• addr –[in] : Peer device address
• service_data –[in] : Service data used by Host
• adv_handle –[in] : Handle of advertising set
Returns - ESP_OK : success
• other : failed
esp_err_t esp_ble_gap_set_periodic_adv_sync_trans_params(esp_bd_addr_t addr, const
esp_ble_gap_past_params_t
*params)
This function is used to set periodic advertising sync transfer params.
Parameters
• addr –[in] : Peer device address
• params –[in] : Params of periodic advertising sync transfer
Returns - ESP_OK : success
• other : failed

Unions

union esp_ble_key_value_t
#include <esp_gap_ble_api.h> union type of the security key value

Espressif Systems 269 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_ble_penc_keys_t penc_key
received peer encryption key

esp_ble_pcsrk_keys_t pcsrk_key
received peer device SRK

esp_ble_pid_keys_t pid_key
peer device ID key

esp_ble_lenc_keys_t lenc_key
local encryption reproduction keys LTK = = d1(ER,DIV,0)

esp_ble_lcsrk_keys lcsrk_key
local device CSRK = d1(ER,DIV,1)

union esp_ble_sec_t
#include <esp_gap_ble_api.h> union associated with ble security

Public Members

esp_ble_sec_key_notif_t key_notif
passkey notification

esp_ble_sec_req_t ble_req
BLE SMP related request

esp_ble_key_t ble_key
BLE SMP keys used when pairing

esp_ble_local_id_keys_t ble_id_keys
BLE IR event

esp_ble_local_oob_data_t oob_data
BLE SMP secure connection OOB data

esp_ble_auth_cmpl_t auth_cmpl
Authentication complete indication.

union esp_ble_gap_cb_param_t
#include <esp_gap_ble_api.h> Gap callback parameters union.

Public Members

struct esp_ble_gap_cb_param_t::ble_get_dev_name_cmpl_evt_param get_dev_name_cmpl


Event parameter of ESP_GAP_BLE_GET_DEV_NAME_COMPLETE_EVT

Espressif Systems 270 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_ble_gap_cb_param_t::ble_adv_data_cmpl_evt_param adv_data_cmpl


Event parameter of ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_scan_rsp_data_cmpl_evt_param scan_rsp_data_cmpl


Event parameter of ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_scan_param_cmpl_evt_param scan_param_cmpl


Event parameter of ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_scan_result_evt_param scan_rst


Event parameter of ESP_GAP_BLE_SCAN_RESULT_EVT

struct esp_ble_gap_cb_param_t::ble_adv_data_raw_cmpl_evt_param adv_data_raw_cmpl


Event parameter of ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_scan_rsp_data_raw_cmpl_evt_param scan_rsp_data_raw_cmpl


Event parameter of ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_adv_start_cmpl_evt_param adv_start_cmpl


Event parameter of ESP_GAP_BLE_ADV_START_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_scan_start_cmpl_evt_param scan_start_cmpl


Event parameter of ESP_GAP_BLE_SCAN_START_COMPLETE_EVT

esp_ble_sec_t ble_security
ble gap security union type

struct esp_ble_gap_cb_param_t::ble_scan_stop_cmpl_evt_param scan_stop_cmpl


Event parameter of ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_adv_stop_cmpl_evt_param adv_stop_cmpl


Event parameter of ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_set_rand_cmpl_evt_param set_rand_addr_cmpl


Event parameter of ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT

struct esp_ble_gap_cb_param_t::ble_update_conn_params_evt_param update_conn_params


Event parameter of ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT

struct esp_ble_gap_cb_param_t::ble_pkt_data_length_cmpl_evt_param pkt_data_length_cmpl


Event parameter of ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_local_privacy_cmpl_evt_param local_privacy_cmpl


Event parameter of ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_remove_bond_dev_cmpl_evt_param remove_bond_dev_cmpl


Event parameter of ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT

Espressif Systems 271 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_ble_gap_cb_param_t::ble_clear_bond_dev_cmpl_evt_param clear_bond_dev_cmpl


Event parameter of ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_get_bond_dev_cmpl_evt_param get_bond_dev_cmpl


Event parameter of ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_read_rssi_cmpl_evt_param read_rssi_cmpl


Event parameter of ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_update_whitelist_cmpl_evt_param update_whitelist_cmpl


Event parameter of ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_update_duplicate_exceptional_list_cmpl_evt_param
update_duplicate_exceptional_list_cmpl
Event parameter of ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_set_channels_evt_param ble_set_channels


Event parameter of ESP_GAP_BLE_SET_CHANNELS_EVT

struct esp_ble_gap_cb_param_t::ble_read_phy_cmpl_evt_param read_phy


Event parameter of ESP_GAP_BLE_READ_PHY_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_set_perf_def_phy_cmpl_evt_param set_perf_def_phy


Event parameter of ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_set_perf_phy_cmpl_evt_param set_perf_phy


Event parameter of ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_ext_adv_set_rand_addr_cmpl_evt_param
ext_adv_set_rand_addr
Event parameter of ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_ext_adv_set_params_cmpl_evt_param ext_adv_set_params


Event parameter of ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_ext_adv_data_set_cmpl_evt_param ext_adv_data_set


Event parameter of ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_ext_adv_scan_rsp_set_cmpl_evt_param scan_rsp_set


Event parameter of ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_ext_adv_start_cmpl_evt_param ext_adv_start


Event parameter of ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_ext_adv_stop_cmpl_evt_param ext_adv_stop


Event parameter of ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_ext_adv_set_remove_cmpl_evt_param ext_adv_remove


Event parameter of ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT

Espressif Systems 272 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_ble_gap_cb_param_t::ble_ext_adv_set_clear_cmpl_evt_param ext_adv_clear


Event parameter of ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_periodic_adv_set_params_cmpl_param peroid_adv_set_params


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_periodic_adv_data_set_cmpl_param period_adv_data_set


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_periodic_adv_start_cmpl_param period_adv_start


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_periodic_adv_stop_cmpl_param period_adv_stop


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_period_adv_create_sync_cmpl_param period_adv_create_sync


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_period_adv_sync_cancel_cmpl_param period_adv_sync_cancel


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_period_adv_sync_terminate_cmpl_param period_adv_sync_term


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_period_adv_add_dev_cmpl_param period_adv_add_dev


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_period_adv_remove_dev_cmpl_param period_adv_remove_dev


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_period_adv_clear_dev_cmpl_param period_adv_clear_dev


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_set_ext_scan_params_cmpl_param set_ext_scan_params


Event parameter of ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_ext_scan_start_cmpl_param ext_scan_start


Event parameter of ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_ext_scan_stop_cmpl_param ext_scan_stop


Event parameter of ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_ext_conn_params_set_cmpl_param ext_conn_params_set


Event parameter of ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_adv_terminate_param adv_terminate


Event parameter of ESP_GAP_BLE_ADV_TERMINATED_EVT

Espressif Systems 273 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_ble_gap_cb_param_t::ble_scan_req_received_param scan_req_received


Event parameter of ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT

struct esp_ble_gap_cb_param_t::ble_channel_sel_alg_param channel_sel_alg


Event parameter of ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT

struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_lost_param periodic_adv_sync_lost


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT

struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_estab_param periodic_adv_sync_estab


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT

struct esp_ble_gap_cb_param_t::ble_phy_update_cmpl_param phy_update


Event parameter of ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_ext_adv_report_param ext_adv_report


Event parameter of ESP_GAP_BLE_EXT_ADV_REPORT_EVT

struct esp_ble_gap_cb_param_t::ble_periodic_adv_report_param period_adv_report


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT

struct esp_ble_gap_cb_param_t::ble_periodic_adv_recv_enable_cmpl_param
period_adv_recv_enable
Event parameter of ESP_GAP_BLE_PERIODIC_ADV_RECV_ENABLE_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_trans_cmpl_param period_adv_sync_trans


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_periodic_adv_set_info_trans_cmpl_param
period_adv_set_info_trans
Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SET_INFO_TRANS_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_set_past_params_cmpl_param set_past_params


Event parameter of ESP_GAP_BLE_SET_PAST_PARAMS_COMPLETE_EVT

struct esp_ble_gap_cb_param_t::ble_periodic_adv_sync_trans_recv_param past_received


Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_RECV_EVT

struct ble_adv_data_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate the set advertising data operation success status

struct ble_adv_data_raw_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT.

Espressif Systems 274 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_bt_status_t status
Indicate the set raw advertising data operation success status

struct ble_adv_start_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_START_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate advertising start operation success status

struct ble_adv_stop_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate adv stop operation success status

struct ble_adv_terminate_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_ADV_TERMINATED_EVT.

Public Members

uint8_t status
Indicate adv terminate status

uint8_t adv_instance
extend advertising handle

uint16_t conn_idx
connection index

uint8_t completed_event
the number of completed extend advertising events

struct ble_channel_sel_alg_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT.

Public Members

uint16_t conn_handle
connection handle

Espressif Systems 275 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint8_t channel_sel_alg
channel selection algorithm

struct ble_clear_bond_dev_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate the clear bond device operation success status

struct ble_ext_adv_data_set_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate extend advertising data set status

struct ble_ext_adv_report_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_REPORT_EVT.

Public Members

esp_ble_gap_ext_adv_reprot_t params
extend advertising report parameters

struct ble_ext_adv_scan_rsp_set_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate extend advertising scan response data set status

struct ble_ext_adv_set_clear_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate advertising stop operation success status

struct ble_ext_adv_set_params_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT.

Espressif Systems 276 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_bt_status_t status
Indicate extend advertising parameters set status

struct ble_ext_adv_set_rand_addr_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate extend advertising random address set status

struct ble_ext_adv_set_remove_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate advertising stop operation success status

struct ble_ext_adv_start_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate advertising start operation success status

struct ble_ext_adv_stop_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate advertising stop operation success status

struct ble_ext_conn_params_set_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate extend connection parameters set status

Espressif Systems 277 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct ble_ext_scan_start_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate extend advertising start status

struct ble_ext_scan_stop_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate extend advertising stop status

struct ble_get_bond_dev_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate the get bond device operation success status

uint8_t dev_num
Indicate the get number device in the bond list

esp_ble_bond_dev_t *bond_dev
the pointer to the bond device Structure

struct ble_get_dev_name_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_GET_DEV_NAME_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate the get device name success status

char *name
Name of bluetooth device

struct ble_local_privacy_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT.

Espressif Systems 278 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_bt_status_t status
Indicate the set local privacy operation success status

struct ble_period_adv_add_dev_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate periodic advertising device list add status

struct ble_period_adv_clear_dev_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate periodic advertising device list clean status

struct ble_period_adv_create_sync_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate periodic advertising create sync status

struct ble_period_adv_remove_dev_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate periodic advertising device list remove status

struct ble_period_adv_sync_cancel_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate periodic advertising sync cancel status

Espressif Systems 279 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct ble_period_adv_sync_terminate_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate periodic advertising sync terminate status

struct ble_periodic_adv_data_set_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate periodic advertising data set status

struct ble_periodic_adv_recv_enable_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_RECV_ENABLE_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Set periodic advertising receive enable status

struct ble_periodic_adv_report_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT.

Public Members

esp_ble_gap_periodic_adv_report_t params
periodic advertising report parameters

struct ble_periodic_adv_set_info_trans_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SET_INFO_TRANS_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Periodic advertising set info transfer status

esp_bd_addr_t bda
The remote device address

struct ble_periodic_adv_set_params_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT.

Espressif Systems 280 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_bt_status_t status
Indicate periodic advertisingparameters set status

struct ble_periodic_adv_start_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate periodic advertising start status

struct ble_periodic_adv_stop_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate periodic advertising stop status

struct ble_periodic_adv_sync_estab_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT.

Public Members

uint8_t status
periodic advertising sync status

uint16_t sync_handle
periodic advertising sync handle

uint8_t sid
periodic advertising sid

esp_ble_addr_type_t adv_addr_type
periodic advertising address type

esp_bd_addr_t adv_addr
periodic advertising address

esp_ble_gap_phy_t adv_phy
periodic advertising phy type

uint16_t period_adv_interval
periodic advertising interval

Espressif Systems 281 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint8_t adv_clk_accuracy
periodic advertising clock accuracy

struct ble_periodic_adv_sync_lost_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT.

Public Members

uint16_t sync_handle
sync handle

struct ble_periodic_adv_sync_trans_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Periodic advertising sync transfer status

esp_bd_addr_t bda
The remote device address

struct ble_periodic_adv_sync_trans_recv_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_RECV_EVT.

Public Members

esp_bt_status_t status
Periodic advertising sync transfer received status

esp_bd_addr_t bda
The remote device address

uint16_t service_data
The value provided by the peer device

uint16_t sync_handle
Periodic advertising sync handle

uint8_t adv_sid
Periodic advertising set id

uint8_t adv_addr_type
Periodic advertiser address type

Espressif Systems 282 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_bd_addr_t adv_addr
Periodic advertiser address

esp_ble_gap_phy_t adv_phy
Periodic advertising PHY

uint16_t adv_interval
Periodic advertising interval

uint8_t adv_clk_accuracy
Periodic advertising clock accuracy

struct ble_phy_update_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT.

Public Members

esp_bt_status_t status
phy update status

esp_bd_addr_t bda
address

esp_ble_gap_phy_t tx_phy
tx phy type

esp_ble_gap_phy_t rx_phy
rx phy type

struct ble_pkt_data_length_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate the set pkt data length operation success status

esp_ble_pkt_data_length_params_t params
pkt data length value

struct ble_read_phy_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_READ_PHY_COMPLETE_EVT.

Public Members

Espressif Systems 283 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_bt_status_t status
read phy complete status

esp_bd_addr_t bda
read phy address

esp_ble_gap_phy_t tx_phy
tx phy type

esp_ble_gap_phy_t rx_phy
rx phy type

struct ble_read_rssi_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate the read adv tx power operation success status

int8_t rssi
The ble remote device rssi value, the range is from -127 to 20, the unit is dbm, if the RSSI cannot
be read, the RSSI metric shall be set to 127.

esp_bd_addr_t remote_addr
The remote device address

struct ble_remove_bond_dev_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate the remove bond device operation success status

esp_bd_addr_t bd_addr
The device address which has been remove from the bond list

struct ble_scan_param_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate the set scan param operation success status

struct ble_scan_req_received_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT.

Espressif Systems 284 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

uint8_t adv_instance
extend advertising handle

esp_ble_addr_type_t scan_addr_type
scanner address type

esp_bd_addr_t scan_addr
scanner address

struct ble_scan_result_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RESULT_EVT.

Public Members

esp_gap_search_evt_t search_evt
Search event type

esp_bd_addr_t bda
Bluetooth device address which has been searched

esp_bt_dev_type_t dev_type
Device type

esp_ble_addr_type_t ble_addr_type
Ble device address type

esp_ble_evt_type_t ble_evt_type
Ble scan result event type

int rssi
Searched device’s RSSI

uint8_t ble_adv[ESP_BLE_ADV_DATA_LEN_MAX +
ESP_BLE_SCAN_RSP_DATA_LEN_MAX]
Received EIR

int flag
Advertising data flag bit

int num_resps
Scan result number

uint8_t adv_data_len
Adv data length

Espressif Systems 285 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint8_t scan_rsp_len
Scan response length

uint32_t num_dis
The number of discard packets

struct ble_scan_rsp_data_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate the set scan response data operation success status

struct ble_scan_rsp_data_raw_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate the set raw advertising data operation success status

struct ble_scan_start_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_START_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate scan start operation success status

struct ble_scan_stop_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate scan stop operation success status

struct ble_set_channels_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_CHANNELS_EVT.

Public Members

esp_bt_status_t stat
BLE set channel status

Espressif Systems 286 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct ble_set_ext_scan_params_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate extend advertising parameters set status

struct ble_set_past_params_cmpl_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PAST_PARAMS_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Set periodic advertising sync transfer params status

esp_bd_addr_t bda
The remote device address

struct ble_set_perf_def_phy_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate perf default phy set status

struct ble_set_perf_phy_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate perf phy set status

struct ble_set_rand_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT.

Public Members

esp_bt_status_t status
Indicate set static rand address operation success status

struct ble_update_conn_params_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT.

Espressif Systems 287 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_bt_status_t status
Indicate update connection parameters success status

esp_bd_addr_t bda
Bluetooth device address

uint16_t min_int
Min connection interval

uint16_t max_int
Max connection interval

uint16_t latency
Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3

uint16_t conn_int
Current connection interval

uint16_t timeout
Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to
0x0C80 Time = N * 10 msec

struct ble_update_duplicate_exceptional_list_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT.

Public Members

esp_bt_status_t status
Indicate update duplicate scan exceptional list operation success status

uint8_t subcode
Define in esp_bt_duplicate_exceptional_subcode_type_t

uint16_t length
The length of device_info

esp_duplicate_info_t device_info
device information, when subcode is ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN,
the value is invalid

struct ble_update_whitelist_cmpl_evt_param
#include <esp_gap_ble_api.h> ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT.

Public Members

Espressif Systems 288 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_bt_status_t status
Indicate the add or remove whitelist operation success status

esp_ble_wl_operation_t wl_operation
The value is ESP_BLE_WHITELIST_ADD if add address to whitelist operation success,
ESP_BLE_WHITELIST_REMOVE if remove address from the whitelist operation success

Structures

struct esp_ble_adv_params_t
Advertising parameters.

Public Members

uint16_t adv_int_min
Minimum advertising interval for undirected and low duty cycle directed advertising. Range: 0x0020 to
0x4000 Default: N = 0x0800 (1.28 second) Time = N * 0.625 msec Time Range: 20 ms to 10.24 sec

uint16_t adv_int_max
Maximum advertising interval for undirected and low duty cycle directed advertising. Range: 0x0020 to
0x4000 Default: N = 0x0800 (1.28 second) Time = N * 0.625 msec Time Range: 20 ms to 10.24 sec
Advertising max interval

esp_ble_adv_type_t adv_type
Advertising type

esp_ble_addr_type_t own_addr_type
Owner bluetooth device address type

esp_bd_addr_t peer_addr
Peer device bluetooth device address

esp_ble_addr_type_t peer_addr_type
Peer device bluetooth device address type, only support public address type and random address type

esp_ble_adv_channel_t channel_map
Advertising channel map

esp_ble_adv_filter_t adv_filter_policy
Advertising filter policy

struct esp_ble_adv_data_t
Advertising data content, according to “Supplement to the Bluetooth Core Specification”.

Public Members

bool set_scan_rsp
Set this advertising data as scan response or not

Espressif Systems 289 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

bool include_name
Advertising data include device name or not

bool include_txpower
Advertising data include TX power

int min_interval
Advertising data show slave preferred connection min interval. The connection interval in the following
manner: connIntervalmin = Conn_Interval_Min * 1.25 ms Conn_Interval_Min range: 0x0006 to 0x0C80
Value of 0xFFFF indicates no specific minimum. Values not defined above are reserved for future use.

int max_interval
Advertising data show slave preferred connection max interval. The connection interval in the follow-
ing manner: connIntervalmax = Conn_Interval_Max * 1.25 ms Conn_Interval_Max range: 0x0006 to
0x0C80 Conn_Interval_Max shall be equal to or greater than the Conn_Interval_Min. Value of 0xFFFF
indicates no specific maximum. Values not defined above are reserved for future use.

int appearance
External appearance of device

uint16_t manufacturer_len
Manufacturer data length

uint8_t *p_manufacturer_data
Manufacturer data point

uint16_t service_data_len
Service data length

uint8_t *p_service_data
Service data point

uint16_t service_uuid_len
Service uuid length

uint8_t *p_service_uuid
Service uuid array point

uint8_t flag
Advertising flag of discovery mode, see BLE_ADV_DATA_FLAG detail

struct esp_ble_scan_params_t
Ble scan parameters.

Public Members

esp_ble_scan_type_t scan_type
Scan type

Espressif Systems 290 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_ble_addr_type_t own_addr_type
Owner address type

esp_ble_scan_filter_t scan_filter_policy
Scan filter policy

uint16_t scan_interval
Scan interval. This is defined as the time interval from when the Controller started its last LE scan until
it begins the subsequent LE scan. Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms) Time = N * 0.625
msec Time Range: 2.5 msec to 10.24 seconds

uint16_t scan_window
Scan window. The duration of the LE scan. LE_Scan_Window shall be less than or equal to
LE_Scan_Interval Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms) Time = N * 0.625 msec Time
Range: 2.5 msec to 10240 msec

esp_ble_scan_duplicate_t scan_duplicate
The Scan_Duplicates parameter controls whether the Link Layer should filter out duplicate advertising
reports (BLE_SCAN_DUPLICATE_ENABLE) to the Host, or if the Link Layer should generate ad-
vertising reports for each packet received

struct esp_gap_conn_params_t
connection parameters information

Public Members

uint16_t interval
connection interval

uint16_t latency
Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3

uint16_t timeout
Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80
Time = N * 10 msec Time Range: 100 msec to 32 seconds

struct esp_ble_conn_update_params_t
Connection update parameters.

Public Members

esp_bd_addr_t bda
Bluetooth device address

uint16_t min_int
Min connection interval

Espressif Systems 291 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint16_t max_int
Max connection interval

uint16_t latency
Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3

uint16_t timeout
Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80
Time = N * 10 msec Time Range: 100 msec to 32 seconds

struct esp_ble_pkt_data_length_params_t
BLE pkt date length keys.

Public Members

uint16_t rx_len
pkt rx data length value

uint16_t tx_len
pkt tx data length value

struct esp_ble_penc_keys_t
BLE encryption keys.

Public Members

esp_bt_octet16_t ltk
The long term key

esp_bt_octet8_t rand
The random number

uint16_t ediv
The ediv value

uint8_t sec_level
The security level of the security link

uint8_t key_size
The key size(7~16) of the security link

struct esp_ble_pcsrk_keys_t
BLE CSRK keys.

Public Members

Espressif Systems 292 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint32_t counter
The counter

esp_bt_octet16_t csrk
The csrk key

uint8_t sec_level
The security level

struct esp_ble_pid_keys_t
BLE pid keys.

Public Members

esp_bt_octet16_t irk
The irk value

esp_ble_addr_type_t addr_type
The address type

esp_bd_addr_t static_addr
The static address

struct esp_ble_lenc_keys_t
BLE Encryption reproduction keys.

Public Members

esp_bt_octet16_t ltk
The long term key

uint16_t div
The div value

uint8_t key_size
The key size of the security link

uint8_t sec_level
The security level of the security link

struct esp_ble_lcsrk_keys
BLE SRK keys.

Public Members

Espressif Systems 293 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint32_t counter
The counter value

uint16_t div
The div value

uint8_t sec_level
The security level of the security link

esp_bt_octet16_t csrk
The csrk key value

struct esp_ble_sec_key_notif_t
Structure associated with ESP_KEY_NOTIF_EVT.

Public Members

esp_bd_addr_t bd_addr
peer address

uint32_t passkey
the numeric value for comparison. If just_works, do not show this number to UI

struct esp_ble_sec_req_t
Structure of the security request.

Public Members

esp_bd_addr_t bd_addr
peer address

struct esp_ble_bond_key_info_t
struct type of the bond key information value

Public Members

esp_ble_key_mask_t key_mask
the key mask to indicate witch key is present

esp_ble_penc_keys_t penc_key
received peer encryption key

esp_ble_pcsrk_keys_t pcsrk_key
received peer device SRK

Espressif Systems 294 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_ble_pid_keys_t pid_key
peer device ID key

struct esp_ble_bond_dev_t
struct type of the bond device value

Public Members

esp_bd_addr_t bd_addr
peer address

esp_ble_bond_key_info_t bond_key
the bond key information

struct esp_ble_key_t
union type of the security key value

Public Members

esp_bd_addr_t bd_addr
peer address

esp_ble_key_type_t key_type
key type of the security link

esp_ble_key_value_t p_key_value
the pointer to the key value

struct esp_ble_local_id_keys_t
structure type of the ble local id keys value

Public Members

esp_bt_octet16_t ir
the 16 bits of the ir value

esp_bt_octet16_t irk
the 16 bits of the ir key value

esp_bt_octet16_t dhk
the 16 bits of the dh key value

struct esp_ble_local_oob_data_t
structure type of the ble local oob data value

Espressif Systems 295 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_bt_octet16_t oob_c
the 128 bits of confirmation value

esp_bt_octet16_t oob_r
the 128 bits of randomizer value

struct esp_ble_auth_cmpl_t
Structure associated with ESP_AUTH_CMPL_EVT.

Public Members

esp_bd_addr_t bd_addr
BD address peer device.

bool key_present
Valid link key value in key element

esp_link_key key
Link key associated with peer device.

uint8_t key_type
The type of Link Key

bool success
TRUE of authentication succeeded, FALSE if failed.

uint8_t fail_reason
The HCI reason/error code for when success=FALSE

esp_ble_addr_type_t addr_type
Peer device address type

esp_bt_dev_type_t dev_type
Device type

esp_ble_auth_req_t auth_mode
authentication mode

struct esp_ble_gap_ext_adv_params_t
ext adv parameters

Public Members

esp_ble_ext_adv_type_mask_t type
ext adv type

Espressif Systems 296 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint32_t interval_min
ext adv minimum interval

uint32_t interval_max
ext adv maximum interval

esp_ble_adv_channel_t channel_map
ext adv channel map

esp_ble_addr_type_t own_addr_type
ext adv own address type

esp_ble_addr_type_t peer_addr_type
ext adv peer address type

esp_bd_addr_t peer_addr
ext adv peer address

esp_ble_adv_filter_t filter_policy
ext adv filter policy

int8_t tx_power
ext adv tx power

esp_ble_gap_pri_phy_t primary_phy
ext adv primary phy

uint8_t max_skip
ext adv maximum skip

esp_ble_gap_phy_t secondary_phy
ext adv secondary phy

uint8_t sid
ext adv sid

bool scan_req_notif
ext adv scan request event notify

struct esp_ble_ext_scan_cfg_t
ext scan config

Public Members

esp_ble_scan_type_t scan_type
ext scan type

Espressif Systems 297 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint16_t scan_interval
ext scan interval

uint16_t scan_window
ext scan window

struct esp_ble_ext_scan_params_t
ext scan parameters

Public Members

esp_ble_addr_type_t own_addr_type
ext scan own address type

esp_ble_scan_filter_t filter_policy
ext scan filter policy

esp_ble_scan_duplicate_t scan_duplicate
ext scan duplicate scan

esp_ble_ext_scan_cfg_mask_t cfg_mask
ext scan config mask

esp_ble_ext_scan_cfg_t uncoded_cfg
ext scan uncoded config parameters

esp_ble_ext_scan_cfg_t coded_cfg
ext scan coded config parameters

struct esp_ble_gap_conn_params_t
create extend connection parameters

Public Members

uint16_t scan_interval
init scan interval

uint16_t scan_window
init scan window

uint16_t interval_min
minimum interval

uint16_t interval_max
maximum interval

Espressif Systems 298 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint16_t latency
ext scan type

uint16_t supervision_timeout
connection supervision timeout

uint16_t min_ce_len
minimum ce length

uint16_t max_ce_len
maximum ce length

struct esp_ble_gap_ext_adv_t
extend adv enable parameters

Public Members

uint8_t instance
advertising handle

int duration
advertising duration

int max_events
maximum number of extended advertising events

struct esp_ble_gap_periodic_adv_params_t
periodic adv parameters

Public Members

uint16_t interval_min
periodic advertising minimum interval

uint16_t interval_max
periodic advertising maximum interval

uint8_t properties
periodic advertising properties

struct esp_ble_gap_periodic_adv_sync_params_t
periodic adv sync parameters

Public Members

Espressif Systems 299 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_ble_gap_sync_t filter_policy
periodic advertising sync filter policy

uint8_t sid
periodic advertising sid

esp_ble_addr_type_t addr_type
periodic advertising address type

esp_bd_addr_t addr
periodic advertising address

uint16_t skip
the maximum number of periodic advertising events that can be skipped

uint16_t sync_timeout
synchronization timeout

struct esp_ble_gap_ext_adv_reprot_t
extend adv report parameters

Public Members

esp_ble_gap_adv_type_t event_type
extend advertising type

uint8_t addr_type
extend advertising address type

esp_bd_addr_t addr
extend advertising address

esp_ble_gap_pri_phy_t primary_phy
extend advertising primary phy

esp_ble_gap_phy_t secondly_phy
extend advertising secondary phy

uint8_t sid
extend advertising sid

uint8_t tx_power
extend advertising tx power

int8_t rssi
extend advertising rssi

Espressif Systems 300 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint16_t per_adv_interval
periodic advertising interval

uint8_t dir_addr_type
direct address type

esp_bd_addr_t dir_addr
direct address

esp_ble_gap_ext_adv_data_status_t data_status
data type

uint8_t adv_data_len
extend advertising data length

uint8_t adv_data[251]
extend advertising data

struct esp_ble_gap_periodic_adv_report_t
periodic adv report parameters

Public Members

uint16_t sync_handle
periodic advertising train handle

uint8_t tx_power
periodic advertising tx power

int8_t rssi
periodic advertising rssi

esp_ble_gap_ext_adv_data_status_t data_status
periodic advertising data type

uint8_t data_length
periodic advertising data length

uint8_t data[251]
periodic advertising data

struct esp_ble_gap_periodic_adv_sync_estab_t
perodic adv sync establish parameters

Public Members

Espressif Systems 301 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint8_t status
periodic advertising sync status

uint16_t sync_handle
periodic advertising train handle

uint8_t sid
periodic advertising sid

esp_ble_addr_type_t addr_type
periodic advertising address type

esp_bd_addr_t adv_addr
periodic advertising address

esp_ble_gap_phy_t adv_phy
periodic advertising adv phy type

uint16_t period_adv_interval
periodic advertising interval

uint8_t adv_clk_accuracy
periodic advertising clock accuracy

struct esp_ble_gap_past_params_t
periodic adv sync transfer parameters

Public Members

esp_ble_gap_past_mode_t mode
periodic advertising sync transfer mode

uint16_t skip
the number of periodic advertising packets that can be skipped

uint16_t sync_timeout
synchronization timeout for the periodic advertising train

uint8_t cte_type
periodic advertising sync transfer CET type

Macros

ESP_BLE_ADV_FLAG_LIMIT_DISC
BLE_ADV_DATA_FLAG data flag bit definition used for advertising data flag.

ESP_BLE_ADV_FLAG_GEN_DISC

Espressif Systems 302 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BLE_ADV_FLAG_BREDR_NOT_SPT

ESP_BLE_ADV_FLAG_DMT_CONTROLLER_SPT

ESP_BLE_ADV_FLAG_DMT_HOST_SPT

ESP_BLE_ADV_FLAG_NON_LIMIT_DISC

ESP_LE_KEY_NONE
relate to BTM_LE_KEY_xxx in stack/btm_api.h
No encryption key

ESP_LE_KEY_PENC
encryption key, encryption information of peer device

ESP_LE_KEY_PID
identity key of the peer device

ESP_LE_KEY_PCSRK
peer SRK

ESP_LE_KEY_PLK
Link key

ESP_LE_KEY_LLK
peer link key

ESP_LE_KEY_LENC
master role security information:div

ESP_LE_KEY_LID
master device ID key

ESP_LE_KEY_LCSRK
local CSRK has been deliver to peer

ESP_LE_AUTH_NO_BOND
relate to BTM_LE_AUTH_xxx in stack/btm_api.h
0 no bondingv

ESP_LE_AUTH_BOND
1 << 0 device in the bonding with peer

ESP_LE_AUTH_REQ_MITM
1 << 2 man in the middle attack

ESP_LE_AUTH_REQ_BOND_MITM
0101 banding with man in the middle attack

Espressif Systems 303 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_LE_AUTH_REQ_SC_ONLY
1 << 3 secure connection

ESP_LE_AUTH_REQ_SC_BOND
1001 secure connection with band

ESP_LE_AUTH_REQ_SC_MITM
1100 secure conn with MITM

ESP_LE_AUTH_REQ_SC_MITM_BOND
1101 SC with MITM and Bonding

ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE
authentication disable

ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_ENABLE
authentication enable

ESP_BLE_OOB_DISABLE
disbale the out of bond

ESP_BLE_OOB_ENABLE
enable the out of bond

ESP_IO_CAP_OUT
relate to BTM_IO_CAP_xxx in stack/btm_api.h
DisplayOnly

ESP_IO_CAP_IO
DisplayYesNo

ESP_IO_CAP_IN
KeyboardOnly

ESP_IO_CAP_NONE
NoInputNoOutput

ESP_IO_CAP_KBDISP
Keyboard display

ESP_BLE_APPEARANCE_UNKNOWN
relate to BTM_BLE_APPEARANCE_UNKNOWN in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_PHONE
relate to BTM_BLE_APPEARANCE_GENERIC_PHONE in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_COMPUTER
relate to BTM_BLE_APPEARANCE_GENERIC_COMPUTER in stack/btm_ble_api.h

Espressif Systems 304 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BLE_APPEARANCE_GENERIC_WATCH
relate to BTM_BLE_APPEARANCE_GENERIC_WATCH in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_SPORTS_WATCH
relate to BTM_BLE_APPEARANCE_SPORTS_WATCH in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_CLOCK
relate to BTM_BLE_APPEARANCE_GENERIC_CLOCK in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_DISPLAY
relate to BTM_BLE_APPEARANCE_GENERIC_DISPLAY in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_REMOTE
relate to BTM_BLE_APPEARANCE_GENERIC_REMOTE in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_EYEGLASSES
relate to BTM_BLE_APPEARANCE_GENERIC_EYEGLASSES in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_TAG
relate to BTM_BLE_APPEARANCE_GENERIC_TAG in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_KEYRING
relate to BTM_BLE_APPEARANCE_GENERIC_KEYRING in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER
relate to BTM_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER
relate to BTM_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_THERMOMETER
relate to BTM_BLE_APPEARANCE_GENERIC_THERMOMETER in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_THERMOMETER_EAR
relate to BTM_BLE_APPEARANCE_THERMOMETER_EAR in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_HEART_RATE
relate to BTM_BLE_APPEARANCE_GENERIC_HEART_RATE in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_HEART_RATE_BELT
relate to BTM_BLE_APPEARANCE_HEART_RATE_BELT in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE
relate to BTM_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_BLOOD_PRESSURE_ARM
relate to BTM_BLE_APPEARANCE_BLOOD_PRESSURE_ARM in stack/btm_ble_api.h

Espressif Systems 305 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST
relate to BTM_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_HID
relate to BTM_BLE_APPEARANCE_GENERIC_HID in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_HID_KEYBOARD
relate to BTM_BLE_APPEARANCE_HID_KEYBOARD in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_HID_MOUSE
relate to BTM_BLE_APPEARANCE_HID_MOUSE in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_HID_JOYSTICK
relate to BTM_BLE_APPEARANCE_HID_JOYSTICK in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_HID_GAMEPAD
relate to BTM_BLE_APPEARANCE_HID_GAMEPAD in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_HID_DIGITIZER_TABLET
relate to BTM_BLE_APPEARANCE_HID_DIGITIZER_TABLET in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_HID_CARD_READER
relate to BTM_BLE_APPEARANCE_HID_CARD_READER in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_HID_DIGITAL_PEN
relate to BTM_BLE_APPEARANCE_HID_DIGITAL_PEN in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_HID_BARCODE_SCANNER
relate to BTM_BLE_APPEARANCE_HID_BARCODE_SCANNER in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_GLUCOSE
relate to BTM_BLE_APPEARANCE_GENERIC_GLUCOSE in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_WALKING
relate to BTM_BLE_APPEARANCE_GENERIC_WALKING in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_WALKING_IN_SHOE
relate to BTM_BLE_APPEARANCE_WALKING_IN_SHOE in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_WALKING_ON_SHOE
relate to BTM_BLE_APPEARANCE_WALKING_ON_SHOE in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_WALKING_ON_HIP
relate to BTM_BLE_APPEARANCE_WALKING_ON_HIP in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_CYCLING
relate to BTM_BLE_APPEARANCE_GENERIC_CYCLING in stack/btm_ble_api.h

Espressif Systems 306 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BLE_APPEARANCE_CYCLING_COMPUTER
relate to BTM_BLE_APPEARANCE_CYCLING_COMPUTER in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_CYCLING_SPEED
relate to BTM_BLE_APPEARANCE_CYCLING_SPEED in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_CYCLING_CADENCE
relate to BTM_BLE_APPEARANCE_CYCLING_CADENCE in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_CYCLING_POWER
relate to BTM_BLE_APPEARANCE_CYCLING_POWER in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_CYCLING_SPEED_CADENCE
relate to BTM_BLE_APPEARANCE_CYCLING_SPEED_CADENCE in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER
relate to BTM_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP
relate to BTM_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_PULSE_OXIMETER_WRIST
relate to BTM_BLE_APPEARANCE_PULSE_OXIMETER_WRIST in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_WEIGHT
relate to BTM_BLE_APPEARANCE_GENERIC_WEIGHT in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_PERSONAL_MOBILITY_DEVICE
relate to BTM_BLE_APPEARANCE_GENERIC_PERSONAL_MOBILITY_DEVICE in
stack/btm_ble_api.h

ESP_BLE_APPEARANCE_POWERED_WHEELCHAIR
relate to BTM_BLE_APPEARANCE_POWERED_WHEELCHAIR in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_MOBILITY_SCOOTER
relate to BTM_BLE_APPEARANCE_MOBILITY_SCOOTER in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_CONTINUOUS_GLUCOSE_MONITOR
relate to BTM_BLE_APPEARANCE_GENERIC_CONTINUOUS_GLUCOSE_MONITOR in
stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_INSULIN_PUMP
relate to BTM_BLE_APPEARANCE_GENERIC_INSULIN_PUMP in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_INSULIN_PUMP_DURABLE_PUMP
relate to BTM_BLE_APPEARANCE_INSULIN_PUMP_DURABLE_PUMP in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_INSULIN_PUMP_PATCH_PUMP
relate to BTM_BLE_APPEARANCE_INSULIN_PUMP_PATCH_PUMP in stack/btm_ble_api.h

Espressif Systems 307 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BLE_APPEARANCE_INSULIN_PEN
relate to BTM_BLE_APPEARANCE_INSULIN_PEN in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_MEDICATION_DELIVERY
relate to BTM_BLE_APPEARANCE_GENERIC_MEDICATION_DELIVERY in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS
relate to BTM_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION
relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV
relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV in
stack/btm_ble_api.h

ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD
relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD in stack/btm_ble_api.h

ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV
relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV in
stack/btm_ble_api.h

ESP_GAP_BLE_CHANNELS_LEN
channel length

ESP_GAP_BLE_ADD_WHITELIST_COMPLETE_EVT
This is the old name, just for backwards compatibility.

ESP_BLE_ADV_DATA_LEN_MAX
Advertising data maximum length.

ESP_BLE_SCAN_RSP_DATA_LEN_MAX
Scan response data maximum length.
BLE_BIT(n)

ESP_BLE_GAP_SET_EXT_ADV_PROP_NONCONN_NONSCANNABLE_UNDIRECTED
Non-Connectable and Non-Scannable Undirected advertising

ESP_BLE_GAP_SET_EXT_ADV_PROP_CONNECTABLE
Connectable advertising

ESP_BLE_GAP_SET_EXT_ADV_PROP_SCANNABLE
Scannable advertising

ESP_BLE_GAP_SET_EXT_ADV_PROP_DIRECTED
Directed advertising

Espressif Systems 308 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BLE_GAP_SET_EXT_ADV_PROP_HD_DIRECTED
High Duty Cycle Directed Connectable advertising (<= 3.75 ms Advertising Interval)

ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY
Use legacy advertising PDUs

ESP_BLE_GAP_SET_EXT_ADV_PROP_ANON_ADV
Omit advertiser’s address from all PDUs (“anonymous advertising”)

ESP_BLE_GAP_SET_EXT_ADV_PROP_INCLUDE_TX_PWR
Include TxPower in the extended header of the advertising PDU

ESP_BLE_GAP_SET_EXT_ADV_PROP_MASK
Reserved for future use If extended advertising PDU types are being used (bit 4 = 0) then: The advertisement
shall not be both connectable and scannable. High duty cycle directed connectable advertising (<= 3.75 ms
advertising interval) shall not be used (bit 3 = 0) ADV_IND

ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_IND
ADV_DIRECT_IND (low duty cycle)

ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_LD_DIR
ADV_DIRECT_IND (high duty cycle)

ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_HD_DIR
ADV_SCAN_IND

ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_SCAN
ADV_NONCONN_IND

ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_NONCONN

ESP_BLE_GAP_PHY_1M
Secondery Advertisement PHY is LE1M

ESP_BLE_GAP_PHY_2M
Secondery Advertisement PHY is LE2M

ESP_BLE_GAP_PHY_CODED
Secondery Advertisement PHY is LE Coded

ESP_BLE_GAP_NO_PREFER_TRANSMIT_PHY
No Prefer TX PHY supported by controller

ESP_BLE_GAP_NO_PREFER_RECEIVE_PHY
No Prefer RX PHY supported by controller

ESP_BLE_GAP_PRI_PHY_1M
Primary phy only support 1M and LE coded phy.
Primary Phy is LE1M

Espressif Systems 309 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BLE_GAP_PRI_PHY_CODED
Primary Phy is LE CODED

ESP_BLE_GAP_PHY_1M_PREF_MASK
The Host prefers use the LE1M transmitter or reciever PHY

ESP_BLE_GAP_PHY_2M_PREF_MASK
The Host prefers use the LE2M transmitter or reciever PHY

ESP_BLE_GAP_PHY_CODED_PREF_MASK
The Host prefers use the LE CODED transmitter or reciever PHY

ESP_BLE_GAP_PHY_OPTIONS_NO_PREF
The Host has no preferred coding when transmitting on the LE Coded PHY

ESP_BLE_GAP_PHY_OPTIONS_PREF_S2_CODING
The Host prefers that S=2 coding be used when transmitting on the LE Coded PHY

ESP_BLE_GAP_PHY_OPTIONS_PREF_S8_CODING
The Host prefers that S=8 coding be used when transmitting on the LE Coded PHY

ESP_BLE_GAP_EXT_SCAN_CFG_UNCODE_MASK
Scan Advertisements on the LE1M PHY

ESP_BLE_GAP_EXT_SCAN_CFG_CODE_MASK
Scan advertisements on the LE coded PHY

ESP_BLE_GAP_EXT_ADV_DATA_COMPLETE
Advertising data.
extended advertising data compete

ESP_BLE_GAP_EXT_ADV_DATA_INCOMPLETE
extended advertising data incomplete

ESP_BLE_GAP_EXT_ADV_DATA_TRUNCATED
extended advertising data truncated mode

ESP_BLE_GAP_SYNC_POLICY_BY_ADV_INFO
Advertising SYNC policy.
sync policy by advertising info

ESP_BLE_GAP_SYNC_POLICY_BY_PERIODIC_LIST
periodic advertising sync policy

ESP_BLE_ADV_REPORT_EXT_ADV_IND
Advertising report.
advertising report with extended advertising indication type

Espressif Systems 310 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BLE_ADV_REPORT_EXT_SCAN_IND
advertising report with extended scan indication type

ESP_BLE_ADV_REPORT_EXT_DIRECT_ADV
advertising report with extended direct advertising indication type

ESP_BLE_ADV_REPORT_EXT_SCAN_RSP
advertising report with extended scan response indication type Bluetooth 5.0, Vol 2, Part E, 7.7.65.13

ESP_BLE_LEGACY_ADV_TYPE_IND
advertising report with legacy advertising indication type

ESP_BLE_LEGACY_ADV_TYPE_DIRECT_IND
advertising report with legacy direct indication type

ESP_BLE_LEGACY_ADV_TYPE_SCAN_IND
advertising report with legacy scan indication type

ESP_BLE_LEGACY_ADV_TYPE_NONCON_IND
advertising report with legacy non connectable indication type

ESP_BLE_LEGACY_ADV_TYPE_SCAN_RSP_TO_ADV_IND
advertising report with legacy scan response indication type

ESP_BLE_LEGACY_ADV_TYPE_SCAN_RSP_TO_ADV_SCAN_IND
advertising report with legacy advertising with scan response indication type

EXT_ADV_TX_PWR_NO_PREFERENCE
Extend advertising tx power, range: [-127, +126] dBm.
host has no preference for tx power

ESP_BLE_GAP_PAST_MODE_NO_SYNC_EVT
Periodic advertising sync trans mode.
No attempt is made to sync and no periodic adv sync transfer received event

ESP_BLE_GAP_PAST_MODE_NO_REPORT_EVT
An periodic adv sync transfer received event and no periodic adv report events

ESP_BLE_GAP_PAST_MODE_DUP_FILTER_DISABLED
Periodic adv report events will be enabled with duplicate filtering disabled

ESP_BLE_GAP_PAST_MODE_DUP_FILTER_ENABLED
Periodic adv report events will be enabled with duplicate filtering enabled

Type Definitions

typedef uint8_t esp_ble_key_type_t

Espressif Systems 311 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

typedef uint8_t esp_ble_auth_req_t


combination of the above bit pattern

typedef uint8_t esp_ble_io_cap_t


combination of the io capability

typedef uint8_t esp_gap_ble_channels[ESP_GAP_BLE_CHANNELS_LEN]

typedef uint8_t esp_duplicate_info_t[ESP_BD_ADDR_LEN]

typedef uint16_t esp_ble_ext_adv_type_mask_t

typedef uint8_t esp_ble_gap_phy_t

typedef uint8_t esp_ble_gap_all_phys_t

typedef uint8_t esp_ble_gap_pri_phy_t

typedef uint8_t esp_ble_gap_phy_mask_t

typedef uint16_t esp_ble_gap_prefer_phy_options_t

typedef uint8_t esp_ble_ext_scan_cfg_mask_t

typedef uint8_t esp_ble_gap_ext_adv_data_status_t

typedef uint8_t esp_ble_gap_sync_t

typedef uint8_t esp_ble_gap_adv_type_t

typedef uint8_t esp_ble_gap_past_mode_t

typedef void (*esp_gap_ble_cb_t)(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)


GAP callback function type.
Param event : Event type
Param param : Point to callback parameter, currently is union type

Enumerations

enum esp_gap_ble_cb_event_t
GAP BLE callback event type.
Values:

enumerator ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT
When advertising data set complete, the event comes

Espressif Systems 312 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT
When scan response data set complete, the event comes

enumerator ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT
When scan parameters set complete, the event comes

enumerator ESP_GAP_BLE_SCAN_RESULT_EVT
When one scan result ready, the event comes each time

enumerator ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT
When raw advertising data set complete, the event comes

enumerator ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT
When raw scan response data set complete, the event comes

enumerator ESP_GAP_BLE_ADV_START_COMPLETE_EVT
When start advertising complete, the event comes

enumerator ESP_GAP_BLE_SCAN_START_COMPLETE_EVT
When start scan complete, the event comes

enumerator ESP_GAP_BLE_AUTH_CMPL_EVT
Authentication complete indication.

enumerator ESP_GAP_BLE_KEY_EVT
BLE key event for peer device keys

enumerator ESP_GAP_BLE_SEC_REQ_EVT
BLE security request

enumerator ESP_GAP_BLE_PASSKEY_NOTIF_EVT
passkey notification event

enumerator ESP_GAP_BLE_PASSKEY_REQ_EVT
passkey request event

enumerator ESP_GAP_BLE_OOB_REQ_EVT
OOB request event

enumerator ESP_GAP_BLE_LOCAL_IR_EVT
BLE local IR (identity Root 128-bit random static value used to generate Long Term Key) event

enumerator ESP_GAP_BLE_LOCAL_ER_EVT
BLE local ER (Encryption Root vakue used to genrate identity resolving key) event

enumerator ESP_GAP_BLE_NC_REQ_EVT
Numeric Comparison request event

Espressif Systems 313 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT
When stop adv complete, the event comes

enumerator ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT
When stop scan complete, the event comes

enumerator ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT
When set the static rand address complete, the event comes

enumerator ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT
When update connection parameters complete, the event comes

enumerator ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT
When set pkt length complete, the event comes

enumerator ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT
When Enable/disable privacy on the local device complete, the event comes

enumerator ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT
When remove the bond device complete, the event comes

enumerator ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT
When clear the bond device clear complete, the event comes

enumerator ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT
When get the bond device list complete, the event comes

enumerator ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT
When read the rssi complete, the event comes

enumerator ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT
When add or remove whitelist complete, the event comes

enumerator ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT
When update duplicate exceptional list complete, the event comes

enumerator ESP_GAP_BLE_SET_CHANNELS_EVT
When setting BLE channels complete, the event comes

enumerator ESP_GAP_BLE_READ_PHY_COMPLETE_EVT
when reading phy complete, this event comes

enumerator ESP_GAP_BLE_SET_PREFERRED_DEFAULT_PHY_COMPLETE_EVT
when preferred default phy complete, this event comes

enumerator ESP_GAP_BLE_SET_PREFERRED_PHY_COMPLETE_EVT
when preferred phy complete , this event comes

Espressif Systems 314 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT
when extended set random address complete, the event comes

enumerator ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT
when extended advertising parameter complete, the event comes

enumerator ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT
when extended advertising data complete, the event comes

enumerator ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT
when extended scan response data complete, the event comes

enumerator ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT
when extended advertising start complete, the event comes

enumerator ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT
when extended advertising stop complete, the event comes

enumerator ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT
when extended advertising set remove complete, the event comes

enumerator ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT
when extended advertising set clear complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT
when periodic advertising parameter complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT
when periodic advertising data complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT
when periodic advertising start complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT
when periodic advertising stop complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT
when periodic advertising create sync complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT
when extended advertising sync cancel complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT
when extended advertising sync terminate complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT
when extended advertising add device complete , the event comes

Espressif Systems 315 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT
when extended advertising remove device complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT
when extended advertising clear device, the event comes

enumerator ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT
when extended scan parameter complete, the event comes

enumerator ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT
when extended scan start complete, the event comes

enumerator ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT
when extended scan stop complete, the event comes

enumerator ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT
when extended prefer connection parameter set complete, the event comes

enumerator ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT
when ble phy update complete, the event comes

enumerator ESP_GAP_BLE_EXT_ADV_REPORT_EVT
when extended advertising report complete, the event comes

enumerator ESP_GAP_BLE_SCAN_TIMEOUT_EVT
when scan timeout complete, the event comes

enumerator ESP_GAP_BLE_ADV_TERMINATED_EVT
when advertising terminate data complete, the event comes

enumerator ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT
when scan req received complete, the event comes

enumerator ESP_GAP_BLE_CHANNEL_SELECT_ALGORITHM_EVT
when channel select algorithm complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT
when periodic report advertising complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT
when periodic advertising sync lost complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT
when periodic advertising sync establish complete, the event comes

enumerator ESP_GAP_BLE_SC_OOB_REQ_EVT
Secure Connection OOB request event

Espressif Systems 316 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GAP_BLE_SC_CR_LOC_OOB_EVT
Secure Connection create OOB data complete event

enumerator ESP_GAP_BLE_GET_DEV_NAME_COMPLETE_EVT
When getting BT device name complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_RECV_ENABLE_COMPLETE_EVT
when set periodic advertising receive enable complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_COMPLETE_EVT
when periodic advertising sync transfer complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_SET_INFO_TRANS_COMPLETE_EVT
when periodic advertising set info transfer complete, the event comes

enumerator ESP_GAP_BLE_SET_PAST_PARAMS_COMPLETE_EVT
when set periodic advertising sync transfer params complete, the event comes

enumerator ESP_GAP_BLE_PERIODIC_ADV_SYNC_TRANS_RECV_EVT
when periodic advertising sync transfer received, the event comes

enumerator ESP_GAP_BLE_EVT_MAX
when maximum advertising event complete, the event comes

enum esp_ble_adv_data_type
The type of advertising data(not adv_type)
Values:

enumerator ESP_BLE_AD_TYPE_FLAG

enumerator ESP_BLE_AD_TYPE_16SRV_PART

enumerator ESP_BLE_AD_TYPE_16SRV_CMPL

enumerator ESP_BLE_AD_TYPE_32SRV_PART

enumerator ESP_BLE_AD_TYPE_32SRV_CMPL

enumerator ESP_BLE_AD_TYPE_128SRV_PART

enumerator ESP_BLE_AD_TYPE_128SRV_CMPL

enumerator ESP_BLE_AD_TYPE_NAME_SHORT

enumerator ESP_BLE_AD_TYPE_NAME_CMPL

enumerator ESP_BLE_AD_TYPE_TX_PWR

Espressif Systems 317 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BLE_AD_TYPE_DEV_CLASS

enumerator ESP_BLE_AD_TYPE_SM_TK

enumerator ESP_BLE_AD_TYPE_SM_OOB_FLAG

enumerator ESP_BLE_AD_TYPE_INT_RANGE

enumerator ESP_BLE_AD_TYPE_SOL_SRV_UUID

enumerator ESP_BLE_AD_TYPE_128SOL_SRV_UUID

enumerator ESP_BLE_AD_TYPE_SERVICE_DATA

enumerator ESP_BLE_AD_TYPE_PUBLIC_TARGET

enumerator ESP_BLE_AD_TYPE_RANDOM_TARGET

enumerator ESP_BLE_AD_TYPE_APPEARANCE

enumerator ESP_BLE_AD_TYPE_ADV_INT

enumerator ESP_BLE_AD_TYPE_LE_DEV_ADDR

enumerator ESP_BLE_AD_TYPE_LE_ROLE

enumerator ESP_BLE_AD_TYPE_SPAIR_C256

enumerator ESP_BLE_AD_TYPE_SPAIR_R256

enumerator ESP_BLE_AD_TYPE_32SOL_SRV_UUID

enumerator ESP_BLE_AD_TYPE_32SERVICE_DATA

enumerator ESP_BLE_AD_TYPE_128SERVICE_DATA

enumerator ESP_BLE_AD_TYPE_LE_SECURE_CONFIRM

enumerator ESP_BLE_AD_TYPE_LE_SECURE_RANDOM

enumerator ESP_BLE_AD_TYPE_URI

enumerator ESP_BLE_AD_TYPE_INDOOR_POSITION

enumerator ESP_BLE_AD_TYPE_TRANS_DISC_DATA

Espressif Systems 318 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BLE_AD_TYPE_LE_SUPPORT_FEATURE

enumerator ESP_BLE_AD_TYPE_CHAN_MAP_UPDATE

enumerator ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE

enum esp_ble_adv_type_t
Advertising mode.
Values:

enumerator ADV_TYPE_IND

enumerator ADV_TYPE_DIRECT_IND_HIGH

enumerator ADV_TYPE_SCAN_IND

enumerator ADV_TYPE_NONCONN_IND

enumerator ADV_TYPE_DIRECT_IND_LOW

enum esp_ble_adv_channel_t
Advertising channel mask.
Values:

enumerator ADV_CHNL_37

enumerator ADV_CHNL_38

enumerator ADV_CHNL_39

enumerator ADV_CHNL_ALL

enum esp_ble_adv_filter_t
Values:

enumerator ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY
Allow both scan and connection requests from anyone.

enumerator ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY
Allow both scan req from White List devices only and connection req from anyone.

enumerator ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST
Allow both scan req from anyone and connection req from White List devices only.

enumerator ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST
Allow scan and connection requests from White List devices only.

Espressif Systems 319 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enum esp_ble_sec_act_t
Values:

enumerator ESP_BLE_SEC_ENCRYPT
relate to BTA_DM_BLE_SEC_ENCRYPT in bta/bta_api.h. If the device has already bonded, the stack
will used Long Term Key (LTK) to encrypt with the remote device directly. Else if the device hasn’t
bonded, the stack will used the default authentication request used the esp_ble_gap_set_security_param
function set by the user.

enumerator ESP_BLE_SEC_ENCRYPT_NO_MITM
relate to BTA_DM_BLE_SEC_ENCRYPT_NO_MITM in bta/bta_api.h. If the device has been already
bonded, the stack will check the LTK (Long Term Key) Whether the authentication request has been met,
and if met, use the LTK to encrypt with the remote device directly, else re-pair with the remote device.
Else if the device hasn’t been bonded, the stack will use NO MITM authentication request in the current
link instead of using the authreq in the esp_ble_gap_set_security_param function set by the user.

enumerator ESP_BLE_SEC_ENCRYPT_MITM
relate to BTA_DM_BLE_SEC_ENCRYPT_MITM in bta/bta_api.h. If the device has been already
bonded, the stack will check the LTK (Long Term Key) whether the authentication request has been
met, and if met, use the LTK to encrypt with the remote device directly, else re-pair with the remote
device. Else if the device hasn’t been bonded, the stack will use MITM authentication request in the
current link instead of using the authreq in the esp_ble_gap_set_security_param function set by the user.

enum esp_ble_sm_param_t
Values:

enumerator ESP_BLE_SM_PASSKEY
Authentication requirements of local device

enumerator ESP_BLE_SM_AUTHEN_REQ_MODE
The IO capability of local device

enumerator ESP_BLE_SM_IOCAP_MODE
Initiator Key Distribution/Generation

enumerator ESP_BLE_SM_SET_INIT_KEY
Responder Key Distribution/Generation

enumerator ESP_BLE_SM_SET_RSP_KEY
Maximum Encryption key size to support

enumerator ESP_BLE_SM_MAX_KEY_SIZE
Minimum Encryption key size requirement from Peer

enumerator ESP_BLE_SM_MIN_KEY_SIZE
Set static Passkey

enumerator ESP_BLE_SM_SET_STATIC_PASSKEY
Reset static Passkey

Espressif Systems 320 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BLE_SM_CLEAR_STATIC_PASSKEY
Accept only specified SMP Authentication requirement

enumerator ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH
Enable/Disable OOB support

enumerator ESP_BLE_SM_OOB_SUPPORT
Appl encryption key size

enumerator ESP_BLE_APP_ENC_KEY_SIZE
authentication max param

enumerator ESP_BLE_SM_MAX_PARAM

enum esp_ble_scan_type_t
Ble scan type.
Values:

enumerator BLE_SCAN_TYPE_PASSIVE
Passive scan

enumerator BLE_SCAN_TYPE_ACTIVE
Active scan

enum esp_ble_scan_filter_t
Ble scan filter type.
Values:

enumerator BLE_SCAN_FILTER_ALLOW_ALL
Accept all :
i. advertisement packets except directed advertising packets not addressed to this device (default).

enumerator BLE_SCAN_FILTER_ALLOW_ONLY_WLST
Accept only :
i. advertisement packets from devices where the advertiser’s address is in the White list.
ii. Directed advertising packets which are not addressed for this device shall be ignored.

enumerator BLE_SCAN_FILTER_ALLOW_UND_RPA_DIR
Accept all :
i. undirected advertisement packets, and
ii. directed advertising packets where the initiator address is a resolvable private address, and
iii. directed advertising packets addressed to this device.

enumerator BLE_SCAN_FILTER_ALLOW_WLIST_RPA_DIR
Accept all :
i. advertisement packets from devices where the advertiser’s address is in the White list, and
ii. directed advertising packets where the initiator address is a resolvable private address, and
iii. directed advertising packets addressed to this device.

Espressif Systems 321 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enum esp_ble_scan_duplicate_t
Ble scan duplicate type.
Values:

enumerator BLE_SCAN_DUPLICATE_DISABLE
the Link Layer should generate advertising reports to the host for each packet received

enumerator BLE_SCAN_DUPLICATE_ENABLE
the Link Layer should filter out duplicate advertising reports to the Host

enumerator BLE_SCAN_DUPLICATE_MAX
0x02 –0xFF, Reserved for future use

enum esp_gap_search_evt_t
Sub Event of ESP_GAP_BLE_SCAN_RESULT_EVT.
Values:

enumerator ESP_GAP_SEARCH_INQ_RES_EVT
Inquiry result for a peer device.

enumerator ESP_GAP_SEARCH_INQ_CMPL_EVT
Inquiry complete.

enumerator ESP_GAP_SEARCH_DISC_RES_EVT
Discovery result for a peer device.

enumerator ESP_GAP_SEARCH_DISC_BLE_RES_EVT
Discovery result for BLE GATT based service on a peer device.

enumerator ESP_GAP_SEARCH_DISC_CMPL_EVT
Discovery complete.

enumerator ESP_GAP_SEARCH_DI_DISC_CMPL_EVT
Discovery complete.

enumerator ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT
Search cancelled

enumerator ESP_GAP_SEARCH_INQ_DISCARD_NUM_EVT
The number of pkt discarded by flow control

enum esp_ble_evt_type_t
Ble scan result event type, to indicate the result is scan response or advertising data or other.
Values:

enumerator ESP_BLE_EVT_CONN_ADV
Connectable undirected advertising (ADV_IND)

Espressif Systems 322 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BLE_EVT_CONN_DIR_ADV
Connectable directed advertising (ADV_DIRECT_IND)

enumerator ESP_BLE_EVT_DISC_ADV
Scannable undirected advertising (ADV_SCAN_IND)

enumerator ESP_BLE_EVT_NON_CONN_ADV
Non connectable undirected advertising (ADV_NONCONN_IND)

enumerator ESP_BLE_EVT_SCAN_RSP
Scan Response (SCAN_RSP)

enum esp_ble_wl_operation_t
Values:

enumerator ESP_BLE_WHITELIST_REMOVE
remove mac from whitelist

enumerator ESP_BLE_WHITELIST_ADD
add address to whitelist

enumerator ESP_BLE_WHITELIST_CLEAR
clear all device in whitelist

enum esp_bt_duplicate_exceptional_subcode_type_t
Values:

enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_ADD
Add device info into duplicate scan exceptional list

enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_REMOVE
Remove device info from duplicate scan exceptional list

enumerator ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN
Clean duplicate scan exceptional list

enum esp_ble_duplicate_exceptional_info_type_t
Values:

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_ADV_ADDR
BLE advertising address , device info will be added into ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_LINK_ID
BLE mesh link ID, it is for BLE mesh, device info will be added into
ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_LINK_ID_LIST

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_BEACON_TYPE
BLE mesh beacon AD type, the format is | Len | 0x2B | Beacon Type | Beacon Data |

Espressif Systems 323 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROV_SRV_ADV
BLE mesh provisioning service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1827 | …. |`

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROXY_SRV_ADV
BLE mesh adv with proxy service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1828 | …. |`

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROXY_SOLIC_ADV
BLE mesh adv with proxy service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x7fcb | …. |`

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_URI_ADV
BLE mesh URI adv, the format is …| Len | 0x24 | data |…

enum esp_duplicate_scan_exceptional_list_type_t
Values:

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST
duplicate scan exceptional addr list

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_LINK_ID_LIST
duplicate scan exceptional mesh link ID list

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_BEACON_TYPE_LIST
duplicate scan exceptional mesh beacon type list

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROV_SRV_ADV_LIST
duplicate scan exceptional mesh adv with provisioning service uuid

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROXY_SRV_ADV_LIST
duplicate scan exceptional mesh adv with proxy service uuid

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROXY_SOLIC_ADV_LIST
duplicate scan exceptional mesh adv with proxy solicitation PDU uuid

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_URI_ADV_LIST
duplicate scan exceptional URI list

enumerator ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ALL_LIST
duplicate scan exceptional all list

GATT Defines

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_gatt_defs.h

Espressif Systems 324 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Unions

union esp_gatt_rsp_t
#include <esp_gatt_defs.h> GATT remote read request response type.

Public Members

esp_gatt_value_t attr_value
Gatt attribute structure

uint16_t handle
Gatt attribute handle

Structures

struct esp_gatt_id_t
Gatt id, include uuid and instance id.

Public Members

esp_bt_uuid_t uuid
UUID

uint8_t inst_id
Instance id

struct esp_gatt_srvc_id_t
Gatt service id, include id (uuid and instance id) and primary flag.

Public Members

esp_gatt_id_t id
Gatt id, include uuid and instance

bool is_primary
This service is primary or not

struct esp_attr_desc_t
Attribute description (used to create database)

Public Members

uint16_t uuid_length
UUID length

uint8_t *uuid_p
UUID value

Espressif Systems 325 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint16_t perm
Attribute permission

uint16_t max_length
Maximum length of the element

uint16_t length
Current length of the element

uint8_t *value
Element value array

struct esp_attr_control_t
attribute auto response flag

Public Members

uint8_t auto_rsp
if auto_rsp set to ESP_GATT_RSP_BY_APP, means the response of Write/Read operation will by
replied by application. if auto_rsp set to ESP_GATT_AUTO_RSP, means the response of Write/Read
operation will be replied by GATT stack automatically.

struct esp_gatts_attr_db_t
attribute type added to the gatt server database

Public Members

esp_attr_control_t attr_control
The attribute control type

esp_attr_desc_t att_desc
The attribute type

struct esp_attr_value_t
set the attribute value type

Public Members

uint16_t attr_max_len
attribute max value length

uint16_t attr_len
attribute current value length

uint8_t *attr_value
the pointer to attribute value

Espressif Systems 326 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_gatts_incl_svc_desc_t
Gatt include service entry element.

Public Members

uint16_t start_hdl
Gatt start handle value of included service

uint16_t end_hdl
Gatt end handle value of included service

uint16_t uuid
Gatt attribute value UUID of included service

struct esp_gatts_incl128_svc_desc_t
Gatt include 128 bit service entry element.

Public Members

uint16_t start_hdl
Gatt start handle value of included 128 bit service

uint16_t end_hdl
Gatt end handle value of included 128 bit service

struct esp_gatt_value_t
Gatt attribute value.

Public Members

uint8_t value[ESP_GATT_MAX_ATTR_LEN]
Gatt attribute value

uint16_t handle
Gatt attribute handle

uint16_t offset
Gatt attribute value offset

uint16_t len
Gatt attribute value length

uint8_t auth_req
Gatt authentication request

struct esp_gatt_conn_params_t
Connection parameters information.

Espressif Systems 327 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

uint16_t interval
connection interval

uint16_t latency
Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3

uint16_t timeout
Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. Mandatory Range: 0x000A to 0x0C80
Time = N * 10 msec Time Range: 100 msec to 32 seconds

struct esp_gattc_multi_t
read multiple attribute

Public Members

uint8_t num_attr
The number of the attribute

uint16_t handles[ESP_GATT_MAX_READ_MULTI_HANDLES]
The handles list

struct esp_gattc_db_elem_t
data base attribute element

Public Members

esp_gatt_db_attr_type_t type
The attribute type

uint16_t attribute_handle
The attribute handle, it’s valid for all of the type

uint16_t start_handle
The service start handle, it’s valid only when the type = ESP_GATT_DB_PRIMARY_SERVICE or
ESP_GATT_DB_SECONDARY_SERVICE

uint16_t end_handle
The service end handle, it’s valid only when the type = ESP_GATT_DB_PRIMARY_SERVICE or
ESP_GATT_DB_SECONDARY_SERVICE

esp_gatt_char_prop_t properties
The characteristic properties, it’s valid only when the type = ESP_GATT_DB_CHARACTERISTIC

esp_bt_uuid_t uuid
The attribute uuid, it’s valid for all of the type

Espressif Systems 328 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_gattc_service_elem_t
service element

Public Members

bool is_primary
The service flag, true if the service is primary service, else is secondary service

uint16_t start_handle
The start handle of the service

uint16_t end_handle
The end handle of the service

esp_bt_uuid_t uuid
The uuid of the service

struct esp_gattc_char_elem_t
characteristic element

Public Members

uint16_t char_handle
The characteristic handle

esp_gatt_char_prop_t properties
The characteristic properties

esp_bt_uuid_t uuid
The characteristic uuid

struct esp_gattc_descr_elem_t
descriptor element

Public Members

uint16_t handle
The characteristic descriptor handle

esp_bt_uuid_t uuid
The characteristic descriptor uuid

struct esp_gattc_incl_svc_elem_t
include service element

Espressif Systems 329 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

uint16_t handle
The include service current attribute handle

uint16_t incl_srvc_s_handle
The start handle of the service which has been included

uint16_t incl_srvc_e_handle
The end handle of the service which has been included

esp_bt_uuid_t uuid
The include service uuid

Macros

ESP_GATT_UUID_IMMEDIATE_ALERT_SVC
All “ESP_GATT_UUID_xxx”is attribute types

ESP_GATT_UUID_LINK_LOSS_SVC

ESP_GATT_UUID_TX_POWER_SVC

ESP_GATT_UUID_CURRENT_TIME_SVC

ESP_GATT_UUID_REF_TIME_UPDATE_SVC

ESP_GATT_UUID_NEXT_DST_CHANGE_SVC

ESP_GATT_UUID_GLUCOSE_SVC

ESP_GATT_UUID_HEALTH_THERMOM_SVC

ESP_GATT_UUID_DEVICE_INFO_SVC

ESP_GATT_UUID_HEART_RATE_SVC

ESP_GATT_UUID_PHONE_ALERT_STATUS_SVC

ESP_GATT_UUID_BATTERY_SERVICE_SVC

ESP_GATT_UUID_BLOOD_PRESSURE_SVC

ESP_GATT_UUID_ALERT_NTF_SVC

ESP_GATT_UUID_HID_SVC

Espressif Systems 330 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_GATT_UUID_SCAN_PARAMETERS_SVC

ESP_GATT_UUID_RUNNING_SPEED_CADENCE_SVC

ESP_GATT_UUID_Automation_IO_SVC

ESP_GATT_UUID_CYCLING_SPEED_CADENCE_SVC

ESP_GATT_UUID_CYCLING_POWER_SVC

ESP_GATT_UUID_LOCATION_AND_NAVIGATION_SVC

ESP_GATT_UUID_ENVIRONMENTAL_SENSING_SVC

ESP_GATT_UUID_BODY_COMPOSITION

ESP_GATT_UUID_USER_DATA_SVC

ESP_GATT_UUID_WEIGHT_SCALE_SVC

ESP_GATT_UUID_BOND_MANAGEMENT_SVC

ESP_GATT_UUID_CONT_GLUCOSE_MONITOR_SVC

ESP_GATT_UUID_PRI_SERVICE

ESP_GATT_UUID_SEC_SERVICE

ESP_GATT_UUID_INCLUDE_SERVICE

ESP_GATT_UUID_CHAR_DECLARE

ESP_GATT_UUID_CHAR_EXT_PROP

ESP_GATT_UUID_CHAR_DESCRIPTION

ESP_GATT_UUID_CHAR_CLIENT_CONFIG

ESP_GATT_UUID_CHAR_SRVR_CONFIG

ESP_GATT_UUID_CHAR_PRESENT_FORMAT

ESP_GATT_UUID_CHAR_AGG_FORMAT

ESP_GATT_UUID_CHAR_VALID_RANGE

Espressif Systems 331 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_GATT_UUID_EXT_RPT_REF_DESCR

ESP_GATT_UUID_RPT_REF_DESCR

ESP_GATT_UUID_NUM_DIGITALS_DESCR

ESP_GATT_UUID_VALUE_TRIGGER_DESCR

ESP_GATT_UUID_ENV_SENSING_CONFIG_DESCR

ESP_GATT_UUID_ENV_SENSING_MEASUREMENT_DESCR

ESP_GATT_UUID_ENV_SENSING_TRIGGER_DESCR

ESP_GATT_UUID_TIME_TRIGGER_DESCR

ESP_GATT_UUID_GAP_DEVICE_NAME

ESP_GATT_UUID_GAP_ICON

ESP_GATT_UUID_GAP_PREF_CONN_PARAM

ESP_GATT_UUID_GAP_CENTRAL_ADDR_RESOL

ESP_GATT_UUID_GATT_SRV_CHGD

ESP_GATT_UUID_ALERT_LEVEL

ESP_GATT_UUID_TX_POWER_LEVEL

ESP_GATT_UUID_CURRENT_TIME

ESP_GATT_UUID_LOCAL_TIME_INFO

ESP_GATT_UUID_REF_TIME_INFO

ESP_GATT_UUID_NW_STATUS

ESP_GATT_UUID_NW_TRIGGER

ESP_GATT_UUID_ALERT_STATUS

ESP_GATT_UUID_RINGER_CP

ESP_GATT_UUID_RINGER_SETTING

Espressif Systems 332 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_GATT_UUID_GM_MEASUREMENT

ESP_GATT_UUID_GM_CONTEXT

ESP_GATT_UUID_GM_CONTROL_POINT

ESP_GATT_UUID_GM_FEATURE

ESP_GATT_UUID_SYSTEM_ID

ESP_GATT_UUID_MODEL_NUMBER_STR

ESP_GATT_UUID_SERIAL_NUMBER_STR

ESP_GATT_UUID_FW_VERSION_STR

ESP_GATT_UUID_HW_VERSION_STR

ESP_GATT_UUID_SW_VERSION_STR

ESP_GATT_UUID_MANU_NAME

ESP_GATT_UUID_IEEE_DATA

ESP_GATT_UUID_PNP_ID

ESP_GATT_UUID_HID_INFORMATION

ESP_GATT_UUID_HID_REPORT_MAP

ESP_GATT_UUID_HID_CONTROL_POINT

ESP_GATT_UUID_HID_REPORT

ESP_GATT_UUID_HID_PROTO_MODE

ESP_GATT_UUID_HID_BT_KB_INPUT

ESP_GATT_UUID_HID_BT_KB_OUTPUT

ESP_GATT_UUID_HID_BT_MOUSE_INPUT

ESP_GATT_HEART_RATE_MEAS
Heart Rate Measurement.

Espressif Systems 333 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_GATT_BODY_SENSOR_LOCATION
Body Sensor Location.

ESP_GATT_HEART_RATE_CNTL_POINT
Heart Rate Control Point.

ESP_GATT_UUID_BATTERY_LEVEL

ESP_GATT_UUID_SC_CONTROL_POINT

ESP_GATT_UUID_SENSOR_LOCATION

ESP_GATT_UUID_RSC_MEASUREMENT

ESP_GATT_UUID_RSC_FEATURE

ESP_GATT_UUID_CSC_MEASUREMENT

ESP_GATT_UUID_CSC_FEATURE

ESP_GATT_UUID_SCAN_INT_WINDOW

ESP_GATT_UUID_SCAN_REFRESH

ESP_GATT_ILLEGAL_UUID
GATT INVALID UUID.

ESP_GATT_ILLEGAL_HANDLE
GATT INVALID HANDLE.

ESP_GATT_ATTR_HANDLE_MAX
GATT attribute max handle.

ESP_GATT_MAX_READ_MULTI_HANDLES

ESP_GATT_PERM_READ
Attribute permissions.

ESP_GATT_PERM_READ_ENCRYPTED

ESP_GATT_PERM_READ_ENC_MITM

ESP_GATT_PERM_WRITE

ESP_GATT_PERM_WRITE_ENCRYPTED

Espressif Systems 334 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_GATT_PERM_WRITE_ENC_MITM

ESP_GATT_PERM_WRITE_SIGNED

ESP_GATT_PERM_WRITE_SIGNED_MITM

ESP_GATT_PERM_READ_AUTHORIZATION

ESP_GATT_PERM_WRITE_AUTHORIZATION

ESP_GATT_PERM_ENCRYPT_KEY_SIZE(keysize)

ESP_GATT_CHAR_PROP_BIT_BROADCAST

ESP_GATT_CHAR_PROP_BIT_READ

ESP_GATT_CHAR_PROP_BIT_WRITE_NR

ESP_GATT_CHAR_PROP_BIT_WRITE

ESP_GATT_CHAR_PROP_BIT_NOTIFY

ESP_GATT_CHAR_PROP_BIT_INDICATE

ESP_GATT_CHAR_PROP_BIT_AUTH

ESP_GATT_CHAR_PROP_BIT_EXT_PROP

ESP_GATT_MAX_ATTR_LEN
GATT maximum attribute length.

ESP_GATT_RSP_BY_APP

ESP_GATT_AUTO_RSP

ESP_GATT_IF_NONE
If callback report gattc_if/gatts_if as this macro, means this event is not correspond to any app

Type Definitions

typedef uint16_t esp_gatt_perm_t

typedef uint8_t esp_gatt_char_prop_t

typedef uint8_t esp_gatt_if_t


Gatt interface type, different application on GATT client use different gatt_if

Espressif Systems 335 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Enumerations

enum esp_gatt_prep_write_type
Attribute write data type from the client.
Values:

enumerator ESP_GATT_PREP_WRITE_CANCEL
Prepare write cancel

enumerator ESP_GATT_PREP_WRITE_EXEC
Prepare write execute

enum esp_gatt_status_t
GATT success code and error codes.
Values:

enumerator ESP_GATT_OK

enumerator ESP_GATT_INVALID_HANDLE

enumerator ESP_GATT_READ_NOT_PERMIT

enumerator ESP_GATT_WRITE_NOT_PERMIT

enumerator ESP_GATT_INVALID_PDU

enumerator ESP_GATT_INSUF_AUTHENTICATION

enumerator ESP_GATT_REQ_NOT_SUPPORTED

enumerator ESP_GATT_INVALID_OFFSET

enumerator ESP_GATT_INSUF_AUTHORIZATION

enumerator ESP_GATT_PREPARE_Q_FULL

enumerator ESP_GATT_NOT_FOUND

enumerator ESP_GATT_NOT_LONG

enumerator ESP_GATT_INSUF_KEY_SIZE

enumerator ESP_GATT_INVALID_ATTR_LEN

enumerator ESP_GATT_ERR_UNLIKELY

enumerator ESP_GATT_INSUF_ENCRYPTION

Espressif Systems 336 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GATT_UNSUPPORT_GRP_TYPE

enumerator ESP_GATT_INSUF_RESOURCE

enumerator ESP_GATT_NO_RESOURCES

enumerator ESP_GATT_INTERNAL_ERROR

enumerator ESP_GATT_WRONG_STATE

enumerator ESP_GATT_DB_FULL

enumerator ESP_GATT_BUSY

enumerator ESP_GATT_ERROR

enumerator ESP_GATT_CMD_STARTED

enumerator ESP_GATT_ILLEGAL_PARAMETER

enumerator ESP_GATT_PENDING

enumerator ESP_GATT_AUTH_FAIL

enumerator ESP_GATT_MORE

enumerator ESP_GATT_INVALID_CFG

enumerator ESP_GATT_SERVICE_STARTED

enumerator ESP_GATT_ENCRYPTED_MITM

enumerator ESP_GATT_ENCRYPTED_NO_MITM

enumerator ESP_GATT_NOT_ENCRYPTED

enumerator ESP_GATT_CONGESTED

enumerator ESP_GATT_DUP_REG

enumerator ESP_GATT_ALREADY_OPEN

enumerator ESP_GATT_CANCEL

enumerator ESP_GATT_STACK_RSP

Espressif Systems 337 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GATT_APP_RSP

enumerator ESP_GATT_UNKNOWN_ERROR

enumerator ESP_GATT_CCC_CFG_ERR

enumerator ESP_GATT_PRC_IN_PROGRESS

enumerator ESP_GATT_OUT_OF_RANGE

enum esp_gatt_conn_reason_t
Gatt Connection reason enum.
Values:

enumerator ESP_GATT_CONN_UNKNOWN
Gatt connection unknown

enumerator ESP_GATT_CONN_L2C_FAILURE
General L2cap failure

enumerator ESP_GATT_CONN_TIMEOUT
Connection timeout

enumerator ESP_GATT_CONN_TERMINATE_PEER_USER
Connection terminate by peer user

enumerator ESP_GATT_CONN_TERMINATE_LOCAL_HOST
Connection terminated by local host

enumerator ESP_GATT_CONN_FAIL_ESTABLISH
Connection fail to establish

enumerator ESP_GATT_CONN_LMP_TIMEOUT
Connection fail for LMP response tout

enumerator ESP_GATT_CONN_CONN_CANCEL
L2CAP connection cancelled

enumerator ESP_GATT_CONN_NONE
No connection to cancel

enum esp_gatt_auth_req_t
Gatt authentication request type.
Values:

enumerator ESP_GATT_AUTH_REQ_NONE

Espressif Systems 338 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GATT_AUTH_REQ_NO_MITM

enumerator ESP_GATT_AUTH_REQ_MITM

enumerator ESP_GATT_AUTH_REQ_SIGNED_NO_MITM

enumerator ESP_GATT_AUTH_REQ_SIGNED_MITM

enum esp_service_source_t
Values:

enumerator ESP_GATT_SERVICE_FROM_REMOTE_DEVICE

enumerator ESP_GATT_SERVICE_FROM_NVS_FLASH

enumerator ESP_GATT_SERVICE_FROM_UNKNOWN

enum esp_gatt_write_type_t
Gatt write type.
Values:

enumerator ESP_GATT_WRITE_TYPE_NO_RSP
Gatt write attribute need no response

enumerator ESP_GATT_WRITE_TYPE_RSP
Gatt write attribute need remote response

enum esp_gatt_db_attr_type_t
the type of attribute element
Values:

enumerator ESP_GATT_DB_PRIMARY_SERVICE
Gattc primary service attribute type in the cache

enumerator ESP_GATT_DB_SECONDARY_SERVICE
Gattc secondary service attribute type in the cache

enumerator ESP_GATT_DB_CHARACTERISTIC
Gattc characteristic attribute type in the cache

enumerator ESP_GATT_DB_DESCRIPTOR
Gattc characteristic descriptor attribute type in the cache

enumerator ESP_GATT_DB_INCLUDED_SERVICE
Gattc include service attribute type in the cache

Espressif Systems 339 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GATT_DB_ALL
Gattc all the attribute (primary service & secondary service & include service & char & descriptor) type
in the cache

GATT Server API

Application Examples Check bluetooth/bluedroid/ble folder in ESP-IDF examples, which contains the following
demos and their tutorials:
• This is a GATT server demo and its tutorial. This demo creates a GATT service with an attribute table, which
releases the user from the operation of adding attributes one by one. This is the recommended method of
adding attributes (officially recommended).
– bluetooth/bluedroid/ble/gatt_server_service_table
– GATT Server Service Table Example Walkthrough
• This is a GATT server demo and its tutorial. This demo creates a GATT service by adding attributes one by one
as defined by Bluedroid. The recommended method of adding attributes is presented in the example below.
– bluetooth/bluedroid/ble/gatt_server
– GATT Server Example Walkthrough
• This is a demo similar to Bluetooth® Low Energy (Bluetooth LE) SPP. In this demo, GATT server can receive
data from UART and then send the data to the peer device automatically.
– bluetooth/bluedroid/ble/ble_spp_server

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_gatts_api.h

Functions
esp_err_t esp_ble_gatts_register_callback(esp_gatts_cb_t callback)
This function is called to register application callbacks with BTA GATTS module.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_app_register(uint16_t app_id)
This function is called to register application identifier.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_app_unregister(esp_gatt_if_t gatts_if)
unregister with GATT Server.
Parameters gatts_if –[in] GATT server access interface
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_create_service(esp_gatt_if_t gatts_if, esp_gatt_srvc_id_t *service_id,
uint16_t num_handle)

Espressif Systems 340 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Create a service. When service creation is done, a callback event ESP_GATTS_CREATE_EVT is called to
report status and service ID to the profile. The service ID obtained in the callback function needs to be used
when adding included service and characteristics/descriptors into the service.
Parameters
• gatts_if –[in] GATT server access interface
• service_id –[in] service ID.
• num_handle –[in] number of handle requested for this service.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_create_attr_tab(const esp_gatts_attr_db_t *gatts_attr_db, esp_gatt_if_t
gatts_if, uint16_t max_nb_attr, uint8_t srvc_inst_id)
Create a service attribute tab.
Parameters
• gatts_attr_db –[in] the pointer to the service attr tab
• gatts_if –[in] GATT server access interface
• max_nb_attr –[in] the number of attribute to be added to the service database.
• srvc_inst_id –[in] the instance id of the service
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_add_included_service(uint16_t service_handle, uint16_t
included_service_handle)
This function is called to add an included service. This function have to be called between
‘esp_ble_gatts_create_service’and‘esp_ble_gatts_add_char’. After included service is included, a callback
event ESP_GATTS_ADD_INCL_SRVC_EVT is reported the included service ID.
Parameters
• service_handle –[in] service handle to which this included service is to be added.
• included_service_handle –[in] the service ID to be included.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_add_char(uint16_t service_handle, esp_bt_uuid_t *char_uuid, esp_gatt_perm_t
perm, esp_gatt_char_prop_t property, esp_attr_value_t *char_val,
esp_attr_control_t *control)
This function is called to add a characteristic into a service.
Parameters
• service_handle –[in] service handle to which this included service is to be added.
• char_uuid –[in] : Characteristic UUID.
• perm –[in] : Characteristic value declaration attribute permission.
• property –[in] : Characteristic Properties
• char_val –[in] : Characteristic value
• control –[in] : attribute response control byte
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_add_char_descr(uint16_t service_handle, esp_bt_uuid_t *descr_uuid,
esp_gatt_perm_t perm, esp_attr_value_t *char_descr_val,
esp_attr_control_t *control)
This function is called to add characteristic descriptor. When it’s done, a callback event
ESP_GATTS_ADD_DESCR_EVT is called to report the status and an ID number for this descriptor.

Espressif Systems 341 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters
• service_handle –[in] service handle to which this characteristic descriptor is to be
added.
• perm –[in] descriptor access permission.
• descr_uuid –[in] descriptor UUID.
• char_descr_val –[in] : Characteristic descriptor value
• control –[in] : attribute response control byte
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_delete_service(uint16_t service_handle)
This function is called to delete a service. When this is done, a callback event ESP_GATTS_DELETE_EVT
is report with the status.
Parameters service_handle –[in] service_handle to be deleted.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_start_service(uint16_t service_handle)
This function is called to start a service.
Parameters service_handle –[in] the service handle to be started.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_stop_service(uint16_t service_handle)
This function is called to stop a service.
Parameters service_handle –[in] - service to be topped.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_send_indicate(esp_gatt_if_t gatts_if, uint16_t conn_id, uint16_t attr_handle,
uint16_t value_len, uint8_t *value, bool need_confirm)
Send indicate or notify to GATT client. Set param need_confirm as false will send notification, otherwise indi-
cation. Note: the size of indicate or notify data need less than MTU size,see “esp_ble_gattc_send_mtu_req”
.
Parameters
• gatts_if –[in] GATT server access interface
• conn_id –[in] - connection id to indicate.
• attr_handle –[in] - attribute handle to indicate.
• value_len –[in] - indicate value length.
• value –[in] value to indicate.
• need_confirm –[in] - Whether a confirmation is required. false sends a GATT notifi-
cation, true sends a GATT indication.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_send_response(esp_gatt_if_t gatts_if, uint16_t conn_id, uint32_t trans_id,
esp_gatt_status_t status, esp_gatt_rsp_t *rsp)
This function is called to send a response to a request.
Parameters
• gatts_if –[in] GATT server access interface
• conn_id –[in] - connection identifier.
• trans_id –[in] - transfer id

Espressif Systems 342 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• status –[in] - response status


• rsp –[in] - response data.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_set_attr_value(uint16_t attr_handle, uint16_t length, const uint8_t *value)
This function is called to set the attribute value by the application.
Parameters
• attr_handle –[in] the attribute handle which to be set
• length –[in] the value length
• value –[in] the pointer to the attribute value
Returns
• ESP_OK : success
• other : failed
esp_gatt_status_t esp_ble_gatts_get_attr_value(uint16_t attr_handle, uint16_t *length, const uint8_t
**value)
Retrieve attribute value.
Parameters
• attr_handle –[in] Attribute handle.
• length –[out] pointer to the attribute value length
• value –[out] Pointer to attribute value payload, the value cannot be modified by user
Returns
• ESP_GATT_OK : success
• other : failed
esp_err_t esp_ble_gatts_open(esp_gatt_if_t gatts_if, esp_bd_addr_t remote_bda, bool is_direct)
Open a direct open connection or add a background auto connection.
Parameters
• gatts_if –[in] GATT server access interface
• remote_bda –[in] remote device bluetooth device address.
• is_direct –[in] direct connection or background auto connection
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_close(esp_gatt_if_t gatts_if, uint16_t conn_id)
Close a connection a remote device.
Parameters
• gatts_if –[in] GATT server access interface
• conn_id –[in] connection ID to be closed.
Returns
• ESP_OK : success
• other : failed
esp_err_t esp_ble_gatts_send_service_change_indication(esp_gatt_if_t gatts_if,
esp_bd_addr_t remote_bda)
Send service change indication.
Parameters
• gatts_if –[in] GATT server access interface
• remote_bda –[in] remote device bluetooth device address. If remote_bda is NULL
then it will send service change indication to all the connected devices and if not then to a
specific device
Returns
• ESP_OK : success
• other : failed

Espressif Systems 343 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_ble_gatts_show_local_database(void)
Print local database (GATT service table)
Returns
• ESP_OK : success
• other : failed

Unions

union esp_ble_gatts_cb_param_t
#include <esp_gatts_api.h> Gatt server callback parameters union.

Public Members

struct esp_ble_gatts_cb_param_t::gatts_reg_evt_param reg


Gatt server callback param of ESP_GATTS_REG_EVT

struct esp_ble_gatts_cb_param_t::gatts_read_evt_param read


Gatt server callback param of ESP_GATTS_READ_EVT

struct esp_ble_gatts_cb_param_t::gatts_write_evt_param write


Gatt server callback param of ESP_GATTS_WRITE_EVT

struct esp_ble_gatts_cb_param_t::gatts_exec_write_evt_param exec_write


Gatt server callback param of ESP_GATTS_EXEC_WRITE_EVT

struct esp_ble_gatts_cb_param_t::gatts_mtu_evt_param mtu


Gatt server callback param of ESP_GATTS_MTU_EVT

struct esp_ble_gatts_cb_param_t::gatts_conf_evt_param conf


Gatt server callback param of ESP_GATTS_CONF_EVT (confirm)

struct esp_ble_gatts_cb_param_t::gatts_create_evt_param create


Gatt server callback param of ESP_GATTS_CREATE_EVT

struct esp_ble_gatts_cb_param_t::gatts_add_incl_srvc_evt_param add_incl_srvc


Gatt server callback param of ESP_GATTS_ADD_INCL_SRVC_EVT

struct esp_ble_gatts_cb_param_t::gatts_add_char_evt_param add_char


Gatt server callback param of ESP_GATTS_ADD_CHAR_EVT

struct esp_ble_gatts_cb_param_t::gatts_add_char_descr_evt_param add_char_descr


Gatt server callback param of ESP_GATTS_ADD_CHAR_DESCR_EVT

struct esp_ble_gatts_cb_param_t::gatts_delete_evt_param del


Gatt server callback param of ESP_GATTS_DELETE_EVT

struct esp_ble_gatts_cb_param_t::gatts_start_evt_param start


Gatt server callback param of ESP_GATTS_START_EVT

Espressif Systems 344 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_ble_gatts_cb_param_t::gatts_stop_evt_param stop


Gatt server callback param of ESP_GATTS_STOP_EVT

struct esp_ble_gatts_cb_param_t::gatts_connect_evt_param connect


Gatt server callback param of ESP_GATTS_CONNECT_EVT

struct esp_ble_gatts_cb_param_t::gatts_disconnect_evt_param disconnect


Gatt server callback param of ESP_GATTS_DISCONNECT_EVT

struct esp_ble_gatts_cb_param_t::gatts_open_evt_param open


Gatt server callback param of ESP_GATTS_OPEN_EVT

struct esp_ble_gatts_cb_param_t::gatts_cancel_open_evt_param cancel_open


Gatt server callback param of ESP_GATTS_CANCEL_OPEN_EVT

struct esp_ble_gatts_cb_param_t::gatts_close_evt_param close


Gatt server callback param of ESP_GATTS_CLOSE_EVT

struct esp_ble_gatts_cb_param_t::gatts_congest_evt_param congest


Gatt server callback param of ESP_GATTS_CONGEST_EVT

struct esp_ble_gatts_cb_param_t::gatts_rsp_evt_param rsp


Gatt server callback param of ESP_GATTS_RESPONSE_EVT

struct esp_ble_gatts_cb_param_t::gatts_add_attr_tab_evt_param add_attr_tab


Gatt server callback param of ESP_GATTS_CREAT_ATTR_TAB_EVT

struct esp_ble_gatts_cb_param_t::gatts_set_attr_val_evt_param set_attr_val


Gatt server callback param of ESP_GATTS_SET_ATTR_VAL_EVT

struct esp_ble_gatts_cb_param_t::gatts_send_service_change_evt_param service_change


Gatt server callback param of ESP_GATTS_SEND_SERVICE_CHANGE_EVT

struct gatts_add_attr_tab_evt_param
#include <esp_gatts_api.h> ESP_GATTS_CREAT_ATTR_TAB_EVT.

Public Members

esp_gatt_status_t status
Operation status

esp_bt_uuid_t svc_uuid
Service uuid type

uint8_t svc_inst_id
Service id

Espressif Systems 345 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint16_t num_handle
The number of the attribute handle to be added to the gatts database

uint16_t *handles
The number to the handles

struct gatts_add_char_descr_evt_param
#include <esp_gatts_api.h> ESP_GATTS_ADD_CHAR_DESCR_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t attr_handle
Descriptor attribute handle

uint16_t service_handle
Service attribute handle

esp_bt_uuid_t descr_uuid
Characteristic descriptor uuid

struct gatts_add_char_evt_param
#include <esp_gatts_api.h> ESP_GATTS_ADD_CHAR_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t attr_handle
Characteristic attribute handle

uint16_t service_handle
Service attribute handle

esp_bt_uuid_t char_uuid
Characteristic uuid

struct gatts_add_incl_srvc_evt_param
#include <esp_gatts_api.h> ESP_GATTS_ADD_INCL_SRVC_EVT.

Public Members

Espressif Systems 346 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_gatt_status_t status
Operation status

uint16_t attr_handle
Included service attribute handle

uint16_t service_handle
Service attribute handle

struct gatts_cancel_open_evt_param
#include <esp_gatts_api.h> ESP_GATTS_CANCEL_OPEN_EVT.

Public Members

esp_gatt_status_t status
Operation status

struct gatts_close_evt_param
#include <esp_gatts_api.h> ESP_GATTS_CLOSE_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t conn_id
Connection id

struct gatts_conf_evt_param
#include <esp_gatts_api.h> ESP_GATTS_CONF_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t conn_id
Connection id

uint16_t handle
attribute handle

uint16_t len
The indication or notification value length, len is valid when send notification or indication failed

Espressif Systems 347 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint8_t *value
The indication or notification value , value is valid when send notification or indication failed

struct gatts_congest_evt_param
#include <esp_gatts_api.h> ESP_GATTS_LISTEN_EVT.
ESP_GATTS_CONGEST_EVT

Public Members

uint16_t conn_id
Connection id

bool congested
Congested or not

struct gatts_connect_evt_param
#include <esp_gatts_api.h> ESP_GATTS_CONNECT_EVT.

Public Members

uint16_t conn_id
Connection id

uint8_t link_role
Link role : master role = 0 ; slave role = 1

esp_bd_addr_t remote_bda
Remote bluetooth device address

esp_gatt_conn_params_t conn_params
current Connection parameters

esp_ble_addr_type_t ble_addr_type
Remote BLE device address type

uint16_t conn_handle
HCI connection handle

struct gatts_create_evt_param
#include <esp_gatts_api.h> ESP_GATTS_UNREG_EVT.
ESP_GATTS_CREATE_EVT

Public Members

esp_gatt_status_t status
Operation status

Espressif Systems 348 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint16_t service_handle
Service attribute handle

esp_gatt_srvc_id_t service_id
Service id, include service uuid and other information

struct gatts_delete_evt_param
#include <esp_gatts_api.h> ESP_GATTS_DELETE_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t service_handle
Service attribute handle

struct gatts_disconnect_evt_param
#include <esp_gatts_api.h> ESP_GATTS_DISCONNECT_EVT.

Public Members

uint16_t conn_id
Connection id

esp_bd_addr_t remote_bda
Remote bluetooth device address

esp_gatt_conn_reason_t reason
Indicate the reason of disconnection

struct gatts_exec_write_evt_param
#include <esp_gatts_api.h> ESP_GATTS_EXEC_WRITE_EVT.

Public Members

uint16_t conn_id
Connection id

uint32_t trans_id
Transfer id

esp_bd_addr_t bda
The bluetooth device address which been written

Espressif Systems 349 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint8_t exec_write_flag
Execute write flag

struct gatts_mtu_evt_param
#include <esp_gatts_api.h> ESP_GATTS_MTU_EVT.

Public Members

uint16_t conn_id
Connection id

uint16_t mtu
MTU size

struct gatts_open_evt_param
#include <esp_gatts_api.h> ESP_GATTS_OPEN_EVT.

Public Members

esp_gatt_status_t status
Operation status

struct gatts_read_evt_param
#include <esp_gatts_api.h> ESP_GATTS_READ_EVT.

Public Members

uint16_t conn_id
Connection id

uint32_t trans_id
Transfer id

esp_bd_addr_t bda
The bluetooth device address which been read

uint16_t handle
The attribute handle

uint16_t offset
Offset of the value, if the value is too long

bool is_long
The value is too long or not

Espressif Systems 350 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

bool need_rsp
The read operation need to do response

struct gatts_reg_evt_param
#include <esp_gatts_api.h> ESP_GATTS_REG_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t app_id
Application id which input in register API

struct gatts_rsp_evt_param
#include <esp_gatts_api.h> ESP_GATTS_RESPONSE_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t handle
Attribute handle which send response

struct gatts_send_service_change_evt_param
#include <esp_gatts_api.h> ESP_GATTS_SEND_SERVICE_CHANGE_EVT.

Public Members

esp_gatt_status_t status
Operation status

struct gatts_set_attr_val_evt_param
#include <esp_gatts_api.h> ESP_GATTS_SET_ATTR_VAL_EVT.

Public Members

uint16_t srvc_handle
The service handle

uint16_t attr_handle
The attribute handle

esp_gatt_status_t status
Operation status

Espressif Systems 351 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct gatts_start_evt_param
#include <esp_gatts_api.h> ESP_GATTS_START_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t service_handle
Service attribute handle

struct gatts_stop_evt_param
#include <esp_gatts_api.h> ESP_GATTS_STOP_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t service_handle
Service attribute handle

struct gatts_write_evt_param
#include <esp_gatts_api.h> ESP_GATTS_WRITE_EVT.

Public Members

uint16_t conn_id
Connection id

uint32_t trans_id
Transfer id

esp_bd_addr_t bda
The bluetooth device address which been written

uint16_t handle
The attribute handle

uint16_t offset
Offset of the value, if the value is too long

bool need_rsp
The write operation need to do response

Espressif Systems 352 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

bool is_prep
This write operation is prepare write

uint16_t len
The write attribute value length

uint8_t *value
The write attribute value

Macros

ESP_GATT_PREP_WRITE_CANCEL
Prepare write flag to indicate cancel prepare write

ESP_GATT_PREP_WRITE_EXEC
Prepare write flag to indicate execute prepare write

Type Definitions
typedef void (*esp_gatts_cb_t)(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t
*param)
GATT Server callback function type.
Param event : Event type
Param gatts_if : GATT server access interface, normally different gatts_if correspond to different
profile
Param param : Point to callback parameter, currently is union type

Enumerations

enum esp_gatts_cb_event_t
GATT Server callback function events.
Values:

enumerator ESP_GATTS_REG_EVT
When register application id, the event comes

enumerator ESP_GATTS_READ_EVT
When gatt client request read operation, the event comes

enumerator ESP_GATTS_WRITE_EVT
When gatt client request write operation, the event comes

enumerator ESP_GATTS_EXEC_WRITE_EVT
When gatt client request execute write, the event comes

enumerator ESP_GATTS_MTU_EVT
When set mtu complete, the event comes

enumerator ESP_GATTS_CONF_EVT
When receive confirm, the event comes

Espressif Systems 353 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GATTS_UNREG_EVT
When unregister application id, the event comes

enumerator ESP_GATTS_CREATE_EVT
When create service complete, the event comes

enumerator ESP_GATTS_ADD_INCL_SRVC_EVT
When add included service complete, the event comes

enumerator ESP_GATTS_ADD_CHAR_EVT
When add characteristic complete, the event comes

enumerator ESP_GATTS_ADD_CHAR_DESCR_EVT
When add descriptor complete, the event comes

enumerator ESP_GATTS_DELETE_EVT
When delete service complete, the event comes

enumerator ESP_GATTS_START_EVT
When start service complete, the event comes

enumerator ESP_GATTS_STOP_EVT
When stop service complete, the event comes

enumerator ESP_GATTS_CONNECT_EVT
When gatt client connect, the event comes

enumerator ESP_GATTS_DISCONNECT_EVT
When gatt client disconnect, the event comes

enumerator ESP_GATTS_OPEN_EVT
When connect to peer, the event comes

enumerator ESP_GATTS_CANCEL_OPEN_EVT
When disconnect from peer, the event comes

enumerator ESP_GATTS_CLOSE_EVT
When gatt server close, the event comes

enumerator ESP_GATTS_LISTEN_EVT
When gatt listen to be connected the event comes

enumerator ESP_GATTS_CONGEST_EVT
When congest happen, the event comes

enumerator ESP_GATTS_RESPONSE_EVT
When gatt send response complete, the event comes

Espressif Systems 354 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GATTS_CREAT_ATTR_TAB_EVT
When gatt create table complete, the event comes

enumerator ESP_GATTS_SET_ATTR_VAL_EVT
When gatt set attr value complete, the event comes

enumerator ESP_GATTS_SEND_SERVICE_CHANGE_EVT
When gatt send service change indication complete, the event comes

GATT Client API

Application Example Check bluetooth/bluedroid/ble folder in ESP-IDF examples, which contains the following
demos and their tutorials:
• This is a GATT client demo and its tutorial. This demo can scan for devices, connect to the GATT server and
discover its services.
– bluetooth/bluedroid/ble/gatt_client
– GATT Client Example Walkthrough
• This is a multiple connection demo and its tutorial. This demo can connect to multiple GATT server devices
and discover their services.
– bluetooth/bluedroid/ble/gattc_multi_connect
– GATT Client Multi-connection Example Walkthrough
• This is a demo similar to Bluetooth® Low Energy (Bluetooth LE) SPP. This demo, which acts as a GATT
client, can receive data from UART and then send the data to the peer device automatically.
– bluetooth/bluedroid/ble/ble_spp_client

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_gattc_api.h

Functions
esp_err_t esp_ble_gattc_register_callback(esp_gattc_cb_t callback)
This function is called to register application callbacks with GATTC module.
Parameters callback –[in] : pointer to the application callback function.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_app_register(uint16_t app_id)
This function is called to register application callbacks with GATTC module.
Parameters app_id –[in] : Application Identify (UUID), for different application
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_app_unregister(esp_gatt_if_t gattc_if)
This function is called to unregister an application from GATTC module.
Parameters gattc_if –[in] Gatt client access interface.
Returns
• ESP_OK: success
• other: failed

Espressif Systems 355 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_ble_gattc_open(esp_gatt_if_t gattc_if, esp_bd_addr_t remote_bda, esp_ble_addr_type_t


remote_addr_type, bool is_direct)
Open a direct connection or add a background auto connection.
Parameters
• gattc_if –[in] Gatt client access interface.
• remote_bda –[in] remote device bluetooth device address.
• remote_addr_type –[in] remote device bluetooth device the address type.
• is_direct –[in] direct connection or background auto connection(by now, background
auto connection is not supported).
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_aux_open(esp_gatt_if_t gattc_if, esp_bd_addr_t remote_bda,
esp_ble_addr_type_t remote_addr_type, bool is_direct)

esp_err_t esp_ble_gattc_close(esp_gatt_if_t gattc_if, uint16_t conn_id)


Close the virtual connection to the GATT server. gattc may have multiple virtual GATT server connections
when multiple app_id registered, this API only close one virtual GATT server connection. if there exist other
virtual GATT server connections, it does not disconnect the physical connection. if you want to disconnect the
physical connection directly, you can use esp_ble_gap_disconnect(esp_bd_addr_t remote_device).
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID to be closed.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_send_mtu_req(esp_gatt_if_t gattc_if, uint16_t conn_id)
Configure the MTU size in the GATT channel. This can be done only once per connection. Before using, use
esp_ble_gatt_set_local_mtu() to configure the local MTU size.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_search_service(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_bt_uuid_t
*filter_uuid)
This function is called to get service from local cache. This function report service search result by a call-
back event, and followed by a service search complete event. Note: 128-bit base UUID will automatically be
converted to a 16-bit UUID in the search results. Other types of UUID remain unchanged.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID.
• filter_uuid –[in] a UUID of the service application is interested in. If Null, discover
for all services.
Returns
• ESP_OK: success
• other: failed
esp_gatt_status_t esp_ble_gattc_get_service(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_bt_uuid_t
*svc_uuid, esp_gattc_service_elem_t *result, uint16_t
*count, uint16_t offset)
Find all the service with the given service uuid in the gattc cache, if the svc_uuid is NULL, find all the service.

Espressif Systems 356 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Note: It just get service from local cache, won’t get from remote devices. If want to get it from remote device,
need to used the esp_ble_gattc_cache_refresh, then call esp_ble_gattc_get_service again.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID which identify the server.
• svc_uuid –[in] the pointer to the service uuid.
• result –[out] The pointer to the service which has been found in the gattc cache.
• count –[inout] input the number of service want to find, it will output the number of
service has been found in the gattc cache with the given service uuid.
• offset –[in] Offset of the service position to get.
Returns
• ESP_OK: success
• other: failed
esp_gatt_status_t esp_ble_gattc_get_all_char(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t
start_handle, uint16_t end_handle,
esp_gattc_char_elem_t *result, uint16_t *count, uint16_t
offset)
Find all the characteristic with the given service in the gattc cache Note: It just get characteristic from local
cache, won’t get from remote devices.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID which identify the server.
• start_handle –[in] the attribute start handle.
• end_handle –[in] the attribute end handle
• result –[out] The pointer to the characteristic in the service.
• count –[inout] input the number of characteristic want to find, it will output the number
of characteristic has been found in the gattc cache with the given service.
• offset –[in] Offset of the characteristic position to get.
Returns
• ESP_OK: success
• other: failed
esp_gatt_status_t esp_ble_gattc_get_all_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t
char_handle, esp_gattc_descr_elem_t *result, uint16_t
*count, uint16_t offset)
Find all the descriptor with the given characteristic in the gattc cache Note: It just get descriptor from local
cache, won’t get from remote devices.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID which identify the server.
• char_handle –[in] the given characteristic handle
• result –[out] The pointer to the descriptor in the characteristic.
• count –[inout] input the number of descriptor want to find, it will output the number of
descriptor has been found in the gattc cache with the given characteristic.
• offset –[in] Offset of the descriptor position to get.
Returns
• ESP_OK: success
• other: failed
esp_gatt_status_t esp_ble_gattc_get_char_by_uuid(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t
start_handle, uint16_t end_handle, esp_bt_uuid_t
char_uuid, esp_gattc_char_elem_t *result,
uint16_t *count)
Find the characteristic with the given characteristic uuid in the gattc cache Note: It just get characteristic from
local cache, won’t get from remote devices.
Parameters

Espressif Systems 357 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• gattc_if –[in] Gatt client access interface.


• conn_id –[in] connection ID which identify the server.
• start_handle –[in] the attribute start handle
• end_handle –[in] the attribute end handle
• char_uuid –[in] the characteristic uuid
• result –[out] The pointer to the characteristic in the service.
• count –[inout] input the number of characteristic want to find, it will output the number
of characteristic has been found in the gattc cache with the given service.
Returns
• ESP_OK: success
• other: failed
esp_gatt_status_t esp_ble_gattc_get_descr_by_uuid(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t
start_handle, uint16_t end_handle, esp_bt_uuid_t
char_uuid, esp_bt_uuid_t descr_uuid,
esp_gattc_descr_elem_t *result, uint16_t *count)
Find the descriptor with the given characteristic uuid in the gattc cache Note: It just get descriptor from local
cache, won’t get from remote devices.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID which identify the server.
• start_handle –[in] the attribute start handle
• end_handle –[in] the attribute end handle
• char_uuid –[in] the characteristic uuid.
• descr_uuid –[in] the descriptor uuid.
• result –[out] The pointer to the descriptor in the given characteristic.
• count –[inout] input the number of descriptor want to find, it will output the number of
descriptor has been found in the gattc cache with the given characteristic.
Returns
• ESP_OK: success
• other: failed
esp_gatt_status_t esp_ble_gattc_get_descr_by_char_handle(esp_gatt_if_t gattc_if, uint16_t
conn_id, uint16_t char_handle,
esp_bt_uuid_t descr_uuid,
esp_gattc_descr_elem_t *result,
uint16_t *count)
Find the descriptor with the given characteristic handle in the gattc cache Note: It just get descriptor from local
cache, won’t get from remote devices.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID which identify the server.
• char_handle –[in] the characteristic handle.
• descr_uuid –[in] the descriptor uuid.
• result –[out] The pointer to the descriptor in the given characteristic.
• count –[inout] input the number of descriptor want to find, it will output the number of
descriptor has been found in the gattc cache with the given characteristic.
Returns
• ESP_OK: success
• other: failed
esp_gatt_status_t esp_ble_gattc_get_include_service(esp_gatt_if_t gattc_if, uint16_t conn_id,
uint16_t start_handle, uint16_t end_handle,
esp_bt_uuid_t *incl_uuid,
esp_gattc_incl_svc_elem_t *result, uint16_t
*count)
Find the include service with the given service handle in the gattc cache Note: It just get include service from
local cache, won’t get from remote devices.

Espressif Systems 358 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID which identify the server.
• start_handle –[in] the attribute start handle
• end_handle –[in] the attribute end handle
• incl_uuid –[in] the include service uuid
• result –[out] The pointer to the include service in the given service.
• count –[inout] input the number of include service want to find, it will output the number
of include service has been found in the gattc cache with the given service.
Returns
• ESP_OK: success
• other: failed
esp_gatt_status_t esp_ble_gattc_get_attr_count(esp_gatt_if_t gattc_if, uint16_t conn_id,
esp_gatt_db_attr_type_t type, uint16_t start_handle,
uint16_t end_handle, uint16_t char_handle, uint16_t
*count)
Find the attribute count with the given service or characteristic in the gattc cache.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] connection ID which identify the server.
• type –[in] the attribute type.
• start_handle –[in] the attribute start handle, if the type is
ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore
• end_handle –[in] the attribute end handle, if the type is
ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore
• char_handle –[in] the characteristic handle, this parameter valid when the type is
ESP_GATT_DB_DESCRIPTOR. If the type isn’t ESP_GATT_DB_DESCRIPTOR,
this parameter should be ignore.
• count –[out] output the number of attribute has been found in the gattc cache with the
given attribute type.
Returns
• ESP_OK: success
• other: failed
esp_gatt_status_t esp_ble_gattc_get_db(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle,
uint16_t end_handle, esp_gattc_db_elem_t *db, uint16_t *count)
This function is called to get the GATT database. Note: It just get attribute data base from local cache, won’
t get from remote devices.
Parameters
• gattc_if –[in] Gatt client access interface.
• start_handle –[in] the attribute start handle
• end_handle –[in] the attribute end handle
• conn_id –[in] connection ID which identify the server.
• db –[in] output parameter which will contain the GATT database copy. Caller is respon-
sible for freeing it.
• count –[in] number of elements in database.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_read_char(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle,
esp_gatt_auth_req_t auth_req)
This function is called to read a service’s characteristics of the given characteristic handle.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID.

Espressif Systems 359 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• handle –[in] : characteritic handle to read.


• auth_req –[in] : authenticate request type
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_read_by_type(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle,
uint16_t end_handle, esp_bt_uuid_t *uuid, esp_gatt_auth_req_t
auth_req)
This function is called to read a service’s characteristics of the given characteristic UUID.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID.
• start_handle –[in] : the attribute start handle.
• end_handle –[in] : the attribute end handle
• uuid –[in] : The UUID of attribute which will be read.
• auth_req –[in] : authenticate request type
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_read_multiple(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_gattc_multi_t
*read_multi, esp_gatt_auth_req_t auth_req)
This function is called to read multiple characteristic or characteristic descriptors.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID.
• read_multi –[in] : pointer to the read multiple parameter.
• auth_req –[in] : authenticate request type
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_read_multiple_variable(esp_gatt_if_t gattc_if, uint16_t conn_id,
esp_gattc_multi_t *read_multi,
esp_gatt_auth_req_t auth_req)
This function is called to read multiple variable length characteristic or characteristic descriptors.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID.
• read_multi –[in] : pointer to the read multiple parameter.
• auth_req –[in] : authenticate request type
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_read_char_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle,
esp_gatt_auth_req_t auth_req)
This function is called to read a characteristics descriptor.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID.
• handle –[in] : descriptor handle to read.
• auth_req –[in] : authenticate request type
Returns
• ESP_OK: success
• other: failed

Espressif Systems 360 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_ble_gattc_write_char(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle, uint16_t


value_len, uint8_t *value, esp_gatt_write_type_t write_type,
esp_gatt_auth_req_t auth_req)
This function is called to write characteristic value.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID.
• handle –[in] : characteristic handle to write.
• value_len –[in] length of the value to be written.
• value –[in] : the value to be written.
• write_type –[in] : the type of attribute write operation.
• auth_req –[in] : authentication request.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_write_char_descr(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle,
uint16_t value_len, uint8_t *value, esp_gatt_write_type_t
write_type, esp_gatt_auth_req_t auth_req)
This function is called to write characteristic descriptor value.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID
• handle –[in] : descriptor handle to write.
• value_len –[in] length of the value to be written.
• value –[in] : the value to be written.
• write_type –[in] : the type of attribute write operation.
• auth_req –[in] : authentication request.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_prepare_write(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t handle,
uint16_t offset, uint16_t value_len, uint8_t *value,
esp_gatt_auth_req_t auth_req)
This function is called to prepare write a characteristic value.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID.
• handle –[in] : characteristic handle to prepare write.
• offset –[in] : offset of the write value.
• value_len –[in] length of the value to be written.
• value –[in] : the value to be written.
• auth_req –[in] : authentication request.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_prepare_write_char_descr(esp_gatt_if_t gattc_if, uint16_t conn_id,
uint16_t handle, uint16_t offset, uint16_t
value_len, uint8_t *value,
esp_gatt_auth_req_t auth_req)
This function is called to prepare write a characteristic descriptor value.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID.

Espressif Systems 361 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• handle –[in] : characteristic descriptor handle to prepare write.


• offset –[in] : offset of the write value.
• value_len –[in] length of the value to be written.
• value –[in] : the value to be written.
• auth_req –[in] : authentication request.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_execute_write(esp_gatt_if_t gattc_if, uint16_t conn_id, bool is_execute)
This function is called to execute write a prepare write sequence.
Parameters
• gattc_if –[in] Gatt client access interface.
• conn_id –[in] : connection ID.
• is_execute –[in] : execute or cancel.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_register_for_notify(esp_gatt_if_t gattc_if, esp_bd_addr_t server_bda,
uint16_t handle)
This function is called to register for notification of a service.
Parameters
• gattc_if –[in] Gatt client access interface.
• server_bda –[in] : target GATT server.
• handle –[in] : GATT characteristic handle.
Returns
• ESP_OK: registration succeeds
• other: failed
esp_err_t esp_ble_gattc_unregister_for_notify(esp_gatt_if_t gattc_if, esp_bd_addr_t server_bda,
uint16_t handle)
This function is called to de-register for notification of a service.
Parameters
• gattc_if –[in] Gatt client access interface.
• server_bda –[in] : target GATT server.
• handle –[in] : GATT characteristic handle.
Returns
• ESP_OK: unregister succeeds
• other: failed
esp_err_t esp_ble_gattc_cache_refresh(esp_bd_addr_t remote_bda)
Refresh the server cache store in the gattc stack of the remote device. If the device is connected, this API will
restart the discovery of service information of the remote device.
Parameters remote_bda –[in] remote device BD address.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_cache_assoc(esp_gatt_if_t gattc_if, esp_bd_addr_t src_addr, esp_bd_addr_t
assoc_addr, bool is_assoc)
Add or delete the associated address with the source address. Note: The role of this API is mainly when the
client side has stored a server-side database, when it needs to connect another device, but the device’s attribute
database is the same as the server database stored on the client-side, calling this API can use the database that
the device has stored used as the peer server database to reduce the attribute database search and discovery
process and speed up the connection time. The associated address mains that device want to used the database

Espressif Systems 362 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

has stored in the local cache. The source address mains that device want to share the database to the associated
address device.
Parameters
• gattc_if –[in] Gatt client access interface.
• src_addr –[in] the source address which provide the attribute table.
• assoc_addr –[in] the associated device address which went to share the attribute table
with the source address.
• is_assoc –[in] true add the associated device address, false remove the associated de-
vice address.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_cache_get_addr_list(esp_gatt_if_t gattc_if)
Get the address list which has store the attribute table in the gattc cache. There will callback
ESP_GATTC_GET_ADDR_LIST_EVT event when get address list complete.
Parameters gattc_if –[in] Gatt client access interface.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_ble_gattc_cache_clean(esp_bd_addr_t remote_bda)
Clean the service cache of this device in the gattc stack,.
Parameters remote_bda –[in] remote device BD address.
Returns
• ESP_OK: success
• other: failed

Unions

union esp_ble_gattc_cb_param_t
#include <esp_gattc_api.h> Gatt client callback parameters union.

Public Members

struct esp_ble_gattc_cb_param_t::gattc_reg_evt_param reg


Gatt client callback param of ESP_GATTC_REG_EVT

struct esp_ble_gattc_cb_param_t::gattc_open_evt_param open


Gatt client callback param of ESP_GATTC_OPEN_EVT

struct esp_ble_gattc_cb_param_t::gattc_close_evt_param close


Gatt client callback param of ESP_GATTC_CLOSE_EVT

struct esp_ble_gattc_cb_param_t::gattc_cfg_mtu_evt_param cfg_mtu


Gatt client callback param of ESP_GATTC_CFG_MTU_EVT

struct esp_ble_gattc_cb_param_t::gattc_search_cmpl_evt_param search_cmpl


Gatt client callback param of ESP_GATTC_SEARCH_CMPL_EVT

struct esp_ble_gattc_cb_param_t::gattc_search_res_evt_param search_res


Gatt client callback param of ESP_GATTC_SEARCH_RES_EVT

Espressif Systems 363 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_ble_gattc_cb_param_t::gattc_read_char_evt_param read


Gatt client callback param of ESP_GATTC_READ_CHAR_EVT

struct esp_ble_gattc_cb_param_t::gattc_write_evt_param write


Gatt client callback param of ESP_GATTC_WRITE_DESCR_EVT

struct esp_ble_gattc_cb_param_t::gattc_exec_cmpl_evt_param exec_cmpl


Gatt client callback param of ESP_GATTC_EXEC_EVT

struct esp_ble_gattc_cb_param_t::gattc_notify_evt_param notify


Gatt client callback param of ESP_GATTC_NOTIFY_EVT

struct esp_ble_gattc_cb_param_t::gattc_srvc_chg_evt_param srvc_chg


Gatt client callback param of ESP_GATTC_SRVC_CHG_EVT

struct esp_ble_gattc_cb_param_t::gattc_congest_evt_param congest


Gatt client callback param of ESP_GATTC_CONGEST_EVT

struct esp_ble_gattc_cb_param_t::gattc_reg_for_notify_evt_param reg_for_notify


Gatt client callback param of ESP_GATTC_REG_FOR_NOTIFY_EVT

struct esp_ble_gattc_cb_param_t::gattc_unreg_for_notify_evt_param unreg_for_notify


Gatt client callback param of ESP_GATTC_UNREG_FOR_NOTIFY_EVT

struct esp_ble_gattc_cb_param_t::gattc_connect_evt_param connect


Gatt client callback param of ESP_GATTC_CONNECT_EVT

struct esp_ble_gattc_cb_param_t::gattc_disconnect_evt_param disconnect


Gatt client callback param of ESP_GATTC_DISCONNECT_EVT

struct esp_ble_gattc_cb_param_t::gattc_set_assoc_addr_cmp_evt_param set_assoc_cmp


Gatt client callback param of ESP_GATTC_SET_ASSOC_EVT

struct esp_ble_gattc_cb_param_t::gattc_get_addr_list_evt_param get_addr_list


Gatt client callback param of ESP_GATTC_GET_ADDR_LIST_EVT

struct esp_ble_gattc_cb_param_t::gattc_queue_full_evt_param queue_full


Gatt client callback param of ESP_GATTC_QUEUE_FULL_EVT

struct esp_ble_gattc_cb_param_t::gattc_dis_srvc_cmpl_evt_param dis_srvc_cmpl


Gatt client callback param of ESP_GATTC_DIS_SRVC_CMPL_EVT

struct gattc_cfg_mtu_evt_param
#include <esp_gattc_api.h> ESP_GATTC_CFG_MTU_EVT.

Public Members

Espressif Systems 364 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_gatt_status_t status
Operation status

uint16_t conn_id
Connection id

uint16_t mtu
MTU size

struct gattc_close_evt_param
#include <esp_gattc_api.h> ESP_GATTC_CLOSE_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t conn_id
Connection id

esp_bd_addr_t remote_bda
Remote bluetooth device address

esp_gatt_conn_reason_t reason
The reason of gatt connection close

struct gattc_congest_evt_param
#include <esp_gattc_api.h> ESP_GATTC_CONGEST_EVT.

Public Members

uint16_t conn_id
Connection id

bool congested
Congested or not

struct gattc_connect_evt_param
#include <esp_gattc_api.h> ESP_GATTC_CONNECT_EVT.

Public Members

uint16_t conn_id
Connection id

Espressif Systems 365 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint8_t link_role
Link role : master role = 0 ; slave role = 1

esp_bd_addr_t remote_bda
Remote bluetooth device address

esp_gatt_conn_params_t conn_params
current connection parameters

esp_ble_addr_type_t ble_addr_type
Remote BLE device address type

uint16_t conn_handle
HCI connection handle

struct gattc_dis_srvc_cmpl_evt_param
#include <esp_gattc_api.h> ESP_GATTC_DIS_SRVC_CMPL_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t conn_id
Connection id

struct gattc_disconnect_evt_param
#include <esp_gattc_api.h> ESP_GATTC_DISCONNECT_EVT.

Public Members

esp_gatt_conn_reason_t reason
disconnection reason

uint16_t conn_id
Connection id

esp_bd_addr_t remote_bda
Remote bluetooth device address

struct gattc_exec_cmpl_evt_param
#include <esp_gattc_api.h> ESP_GATTC_EXEC_EVT.

Public Members

Espressif Systems 366 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_gatt_status_t status
Operation status

uint16_t conn_id
Connection id

struct gattc_get_addr_list_evt_param
#include <esp_gattc_api.h> ESP_GATTC_GET_ADDR_LIST_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint8_t num_addr
The number of address in the gattc cache address list

esp_bd_addr_t *addr_list
The pointer to the address list which has been get from the gattc cache

struct gattc_notify_evt_param
#include <esp_gattc_api.h> ESP_GATTC_NOTIFY_EVT.

Public Members

uint16_t conn_id
Connection id

esp_bd_addr_t remote_bda
Remote bluetooth device address

uint16_t handle
The Characteristic or descriptor handle

uint16_t value_len
Notify attribute value

uint8_t *value
Notify attribute value

bool is_notify
True means notify, false means indicate

struct gattc_open_evt_param
#include <esp_gattc_api.h> ESP_GATTC_OPEN_EVT.

Espressif Systems 367 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_gatt_status_t status
Operation status

uint16_t conn_id
Connection id

esp_bd_addr_t remote_bda
Remote bluetooth device address

uint16_t mtu
MTU size

struct gattc_queue_full_evt_param
#include <esp_gattc_api.h> ESP_GATTC_QUEUE_FULL_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t conn_id
Connection id

bool is_full
The gattc command queue is full or not

struct gattc_read_char_evt_param
#include <esp_gattc_api.h> ESP_GATTC_READ_CHAR_EVT, ESP_GATTC_READ_DESCR_EVT,
ESP_GATTC_READ_MULTIPLE_EVT, ESP_GATTC_READ_MULTI_VAR_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t conn_id
Connection id

uint16_t handle
Characteristic handle

uint8_t *value
Characteristic value

uint16_t value_len
Characteristic value length

Espressif Systems 368 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct gattc_reg_evt_param
#include <esp_gattc_api.h> ESP_GATTC_REG_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t app_id
Application id which input in register API

struct gattc_reg_for_notify_evt_param
#include <esp_gattc_api.h> ESP_GATTC_REG_FOR_NOTIFY_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t handle
The characteristic or descriptor handle

struct gattc_search_cmpl_evt_param
#include <esp_gattc_api.h> ESP_GATTC_SEARCH_CMPL_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t conn_id
Connection id

esp_service_source_t searched_service_source
The source of the service information

struct gattc_search_res_evt_param
#include <esp_gattc_api.h> ESP_GATTC_SEARCH_RES_EVT.

Public Members

uint16_t conn_id
Connection id

uint16_t start_handle
Service start handle

Espressif Systems 369 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint16_t end_handle
Service end handle

esp_gatt_id_t srvc_id
Service id, include service uuid and other information

bool is_primary
True if this is the primary service

struct gattc_set_assoc_addr_cmp_evt_param
#include <esp_gattc_api.h> ESP_GATTC_SET_ASSOC_EVT.

Public Members

esp_gatt_status_t status
Operation status

struct gattc_srvc_chg_evt_param
#include <esp_gattc_api.h> ESP_GATTC_SRVC_CHG_EVT.

Public Members

esp_bd_addr_t remote_bda
Remote bluetooth device address

struct gattc_unreg_for_notify_evt_param
#include <esp_gattc_api.h> ESP_GATTC_UNREG_FOR_NOTIFY_EVT.

Public Members

esp_gatt_status_t status
Operation status

uint16_t handle
The characteristic or descriptor handle

struct gattc_write_evt_param
#include <esp_gattc_api.h> ESP_GATTC_WRITE_CHAR_EVT, ESP_GATTC_PREP_WRITE_EVT,
ESP_GATTC_WRITE_DESCR_EVT.

Public Members

esp_gatt_status_t status
Operation status

Espressif Systems 370 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint16_t conn_id
Connection id

uint16_t handle
The Characteristic or descriptor handle

uint16_t offset
The prepare write offset, this value is valid only when prepare write

Type Definitions
typedef void (*esp_gattc_cb_t)(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t
*param)
GATT Client callback function type.
Param event : Event type
Param gattc_if : GATT client access interface, normally different gattc_if correspond to different
profile
Param param : Point to callback parameter, currently is union type

Enumerations

enum esp_gattc_cb_event_t
GATT Client callback function events.
Values:

enumerator ESP_GATTC_REG_EVT
When GATT client is registered, the event comes

enumerator ESP_GATTC_UNREG_EVT
When GATT client is unregistered, the event comes

enumerator ESP_GATTC_OPEN_EVT
When GATT virtual connection is set up, the event comes

enumerator ESP_GATTC_READ_CHAR_EVT
When GATT characteristic is read, the event comes

enumerator ESP_GATTC_WRITE_CHAR_EVT
When GATT characteristic write operation completes, the event comes

enumerator ESP_GATTC_CLOSE_EVT
When GATT virtual connection is closed, the event comes

enumerator ESP_GATTC_SEARCH_CMPL_EVT
When GATT service discovery is completed, the event comes

enumerator ESP_GATTC_SEARCH_RES_EVT
When GATT service discovery result is got, the event comes

Espressif Systems 371 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GATTC_READ_DESCR_EVT
When GATT characteristic descriptor read completes, the event comes

enumerator ESP_GATTC_WRITE_DESCR_EVT
When GATT characteristic descriptor write completes, the event comes

enumerator ESP_GATTC_NOTIFY_EVT
When GATT notification or indication arrives, the event comes

enumerator ESP_GATTC_PREP_WRITE_EVT
When GATT prepare-write operation completes, the event comes

enumerator ESP_GATTC_EXEC_EVT
When write execution completes, the event comes

enumerator ESP_GATTC_ACL_EVT
When ACL connection is up, the event comes

enumerator ESP_GATTC_CANCEL_OPEN_EVT
When GATT client ongoing connection is cancelled, the event comes

enumerator ESP_GATTC_SRVC_CHG_EVT
When “service changed”occurs, the event comes

enumerator ESP_GATTC_ENC_CMPL_CB_EVT
When encryption procedure completes, the event comes

enumerator ESP_GATTC_CFG_MTU_EVT
When configuration of MTU completes, the event comes

enumerator ESP_GATTC_ADV_DATA_EVT
When advertising of data, the event comes

enumerator ESP_GATTC_MULT_ADV_ENB_EVT
When multi-advertising is enabled, the event comes

enumerator ESP_GATTC_MULT_ADV_UPD_EVT
When multi-advertising parameters are updated, the event comes

enumerator ESP_GATTC_MULT_ADV_DATA_EVT
When multi-advertising data arrives, the event comes

enumerator ESP_GATTC_MULT_ADV_DIS_EVT
When multi-advertising is disabled, the event comes

enumerator ESP_GATTC_CONGEST_EVT
When GATT connection congestion comes, the event comes

Espressif Systems 372 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GATTC_BTH_SCAN_ENB_EVT
When batch scan is enabled, the event comes

enumerator ESP_GATTC_BTH_SCAN_CFG_EVT
When batch scan storage is configured, the event comes

enumerator ESP_GATTC_BTH_SCAN_RD_EVT
When Batch scan read event is reported, the event comes

enumerator ESP_GATTC_BTH_SCAN_THR_EVT
When Batch scan threshold is set, the event comes

enumerator ESP_GATTC_BTH_SCAN_PARAM_EVT
When Batch scan parameters are set, the event comes

enumerator ESP_GATTC_BTH_SCAN_DIS_EVT
When Batch scan is disabled, the event comes

enumerator ESP_GATTC_SCAN_FLT_CFG_EVT
When Scan filter configuration completes, the event comes

enumerator ESP_GATTC_SCAN_FLT_PARAM_EVT
When Scan filter parameters are set, the event comes

enumerator ESP_GATTC_SCAN_FLT_STATUS_EVT
When Scan filter status is reported, the event comes

enumerator ESP_GATTC_ADV_VSC_EVT
When advertising vendor spec content event is reported, the event comes

enumerator ESP_GATTC_REG_FOR_NOTIFY_EVT
When register for notification of a service completes, the event comes

enumerator ESP_GATTC_UNREG_FOR_NOTIFY_EVT
When unregister for notification of a service completes, the event comes

enumerator ESP_GATTC_CONNECT_EVT
When the ble physical connection is set up, the event comes

enumerator ESP_GATTC_DISCONNECT_EVT
When the ble physical connection disconnected, the event comes

enumerator ESP_GATTC_READ_MULTIPLE_EVT
When the ble characteristic or descriptor multiple complete, the event comes

enumerator ESP_GATTC_QUEUE_FULL_EVT
When the gattc command queue full, the event comes

Espressif Systems 373 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_GATTC_SET_ASSOC_EVT
When the ble gattc set the associated address complete, the event comes

enumerator ESP_GATTC_GET_ADDR_LIST_EVT
When the ble get gattc address list in cache finish, the event comes

enumerator ESP_GATTC_DIS_SRVC_CMPL_EVT
When the ble discover service complete, the event comes

enumerator ESP_GATTC_READ_MULTI_VAR_EVT
When read multiple variable characteristic complete, the event comes

BluFi API

Overview BluFi is a profile based GATT to config ESP32 Wi-Fi to connect/disconnect AP or setup a softap and
etc.
Use should concern these things:
1. The event sent from profile. Then you need to do something as the event indicate.
2. Security reference. You can write your own Security functions such as symmetrical encryption/decryption and
checksum functions. Even you can define the “Key Exchange/Negotiation”procedure.

Application Example Check bluetooth folder in ESP-IDF examples, which contains the following application:
• This is the BluFi demo. This demo can set ESP32’s Wi-Fi to softap/station/softap&station mode and config
Wi-Fi connections - bluetooth/blufi

API Reference

Header File
• components/bt/common/api/include/api/esp_blufi_api.h

Functions
esp_err_t esp_blufi_register_callbacks(esp_blufi_callbacks_t *callbacks)
This function is called to receive blufi callback event.
Parameters callbacks –[in] callback functions
Returns ESP_OK - success, other - failed
esp_err_t esp_blufi_profile_init(void)
This function is called to initialize blufi_profile.
Returns ESP_OK - success, other - failed
esp_err_t esp_blufi_profile_deinit(void)
This function is called to de-initialize blufi_profile.
Returns ESP_OK - success, other - failed
esp_err_t esp_blufi_send_wifi_conn_report(wifi_mode_t opmode, esp_blufi_sta_conn_state_t
sta_conn_state, uint8_t softap_conn_num,
esp_blufi_extra_info_t *extra_info)
This function is called to send wifi connection report.
Parameters

Espressif Systems 374 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• opmode –: wifi opmode


• sta_conn_state –: station is already in connection or not
• softap_conn_num –: softap connection number
• extra_info –: extra information, such as sta_ssid, softap_ssid and etc.
Returns ESP_OK - success, other - failed
esp_err_t esp_blufi_send_wifi_list(uint16_t apCount, esp_blufi_ap_record_t *list)
This function is called to send wifi list.
Parameters
• apCount –: wifi list count
• list –: wifi list
Returns ESP_OK - success, other - failed
uint16_t esp_blufi_get_version(void)
Get BLUFI profile version.
Returns Most 8bit significant is Great version, Least 8bit is Sub version
esp_err_t esp_blufi_send_error_info(esp_blufi_error_state_t state)
This function is called to send blufi error information.
Parameters state –: error state
Returns ESP_OK - success, other - failed
esp_err_t esp_blufi_send_custom_data(uint8_t *data, uint32_t data_len)
This function is called to custom data.
Parameters
• data –: custom data value
• data_len –: the length of custom data
Returns ESP_OK - success, other - failed

Unions

union esp_blufi_cb_param_t
#include <esp_blufi_api.h> BLUFI callback parameters union.

Public Members

struct esp_blufi_cb_param_t::blufi_init_finish_evt_param init_finish


Blufi callback param of ESP_BLUFI_EVENT_INIT_FINISH

struct esp_blufi_cb_param_t::blufi_deinit_finish_evt_param deinit_finish


Blufi callback param of ESP_BLUFI_EVENT_DEINIT_FINISH

struct esp_blufi_cb_param_t::blufi_set_wifi_mode_evt_param wifi_mode


Blufi callback param of ESP_BLUFI_EVENT_INIT_FINISH

struct esp_blufi_cb_param_t::blufi_connect_evt_param connect


Blufi callback param of ESP_BLUFI_EVENT_CONNECT

struct esp_blufi_cb_param_t::blufi_disconnect_evt_param disconnect


Blufi callback param of ESP_BLUFI_EVENT_DISCONNECT

Espressif Systems 375 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_blufi_cb_param_t::blufi_recv_sta_bssid_evt_param sta_bssid


Blufi callback param of ESP_BLUFI_EVENT_RECV_STA_BSSID

struct esp_blufi_cb_param_t::blufi_recv_sta_ssid_evt_param sta_ssid


Blufi callback param of ESP_BLUFI_EVENT_RECV_STA_SSID

struct esp_blufi_cb_param_t::blufi_recv_sta_passwd_evt_param sta_passwd


Blufi callback param of ESP_BLUFI_EVENT_RECV_STA_PASSWD

struct esp_blufi_cb_param_t::blufi_recv_softap_ssid_evt_param softap_ssid


Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_SSID

struct esp_blufi_cb_param_t::blufi_recv_softap_passwd_evt_param softap_passwd


Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD

struct esp_blufi_cb_param_t::blufi_recv_softap_max_conn_num_evt_param softap_max_conn_num


Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM

struct esp_blufi_cb_param_t::blufi_recv_softap_auth_mode_evt_param softap_auth_mode


Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE

struct esp_blufi_cb_param_t::blufi_recv_softap_channel_evt_param softap_channel


Blufi callback param of ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL

struct esp_blufi_cb_param_t::blufi_recv_username_evt_param username


Blufi callback param of ESP_BLUFI_EVENT_RECV_USERNAME

struct esp_blufi_cb_param_t::blufi_recv_ca_evt_param ca
Blufi callback param of ESP_BLUFI_EVENT_RECV_CA_CERT

struct esp_blufi_cb_param_t::blufi_recv_client_cert_evt_param client_cert


Blufi callback param of ESP_BLUFI_EVENT_RECV_CLIENT_CERT

struct esp_blufi_cb_param_t::blufi_recv_server_cert_evt_param server_cert


Blufi callback param of ESP_BLUFI_EVENT_RECV_SERVER_CERT

struct esp_blufi_cb_param_t::blufi_recv_client_pkey_evt_param client_pkey


Blufi callback param of ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY

struct esp_blufi_cb_param_t::blufi_recv_server_pkey_evt_param server_pkey


Blufi callback param of ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY

struct esp_blufi_cb_param_t::blufi_get_error_evt_param report_error


Blufi callback param of ESP_BLUFI_EVENT_REPORT_ERROR

struct esp_blufi_cb_param_t::blufi_recv_custom_data_evt_param custom_data


Blufi callback param of ESP_BLUFI_EVENT_RECV_CUSTOM_DATA

struct blufi_connect_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_CONNECT.

Espressif Systems 376 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_blufi_bd_addr_t remote_bda
Blufi Remote bluetooth device address

uint8_t server_if
server interface

uint16_t conn_id
Connection id

struct blufi_deinit_finish_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_DEINIT_FINISH.

Public Members

esp_blufi_deinit_state_t state
De-initial status

struct blufi_disconnect_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_DISCONNECT.

Public Members

esp_blufi_bd_addr_t remote_bda
Blufi Remote bluetooth device address

struct blufi_get_error_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_REPORT_ERROR.

Public Members

esp_blufi_error_state_t state
Blufi error state

struct blufi_init_finish_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_INIT_FINISH.

Public Members

esp_blufi_init_state_t state
Initial status

struct blufi_recv_ca_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CA_CERT.

Espressif Systems 377 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

uint8_t *cert
CA certificate point

int cert_len
CA certificate length

struct blufi_recv_client_cert_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CLIENT_CERT

Public Members

uint8_t *cert
Client certificate point

int cert_len
Client certificate length

struct blufi_recv_client_pkey_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY

Public Members

uint8_t *pkey
Client Private Key point, if Client certificate not contain Key

int pkey_len
Client Private key length

struct blufi_recv_custom_data_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_CUSTOM_DATA.

Public Members

uint8_t *data
Custom data

uint32_t data_len
Custom data Length

struct blufi_recv_server_cert_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SERVER_CERT

Espressif Systems 378 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

uint8_t *cert
Client certificate point

int cert_len
Client certificate length

struct blufi_recv_server_pkey_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY

Public Members

uint8_t *pkey
Client Private Key point, if Client certificate not contain Key

int pkey_len
Client Private key length

struct blufi_recv_softap_auth_mode_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE.

Public Members

wifi_auth_mode_t auth_mode
Authentication mode

struct blufi_recv_softap_channel_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL.

Public Members

uint8_t channel
Authentication mode

struct blufi_recv_softap_max_conn_num_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM.

Public Members

int max_conn_num
SSID

struct blufi_recv_softap_passwd_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD.

Espressif Systems 379 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

uint8_t *passwd
Password

int passwd_len
Password Length

struct blufi_recv_softap_ssid_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_SOFTAP_SSID.

Public Members

uint8_t *ssid
SSID

int ssid_len
SSID length

struct blufi_recv_sta_bssid_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_BSSID.

Public Members

uint8_t bssid[6]
BSSID

struct blufi_recv_sta_passwd_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_PASSWD.

Public Members

uint8_t *passwd
Password

int passwd_len
Password Length

struct blufi_recv_sta_ssid_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_STA_SSID.

Public Members

uint8_t *ssid
SSID

Espressif Systems 380 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

int ssid_len
SSID length

struct blufi_recv_username_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_RECV_USERNAME.

Public Members

uint8_t *name
Username point

int name_len
Username length

struct blufi_set_wifi_mode_evt_param
#include <esp_blufi_api.h> ESP_BLUFI_EVENT_SET_WIFI_MODE.

Public Members

wifi_mode_t op_mode
Wifi operation mode

Structures

struct esp_blufi_extra_info_t
BLUFI extra information structure.

Public Members

uint8_t sta_bssid[6]
BSSID of station interface

bool sta_bssid_set
is BSSID of station interface set

uint8_t *sta_ssid
SSID of station interface

int sta_ssid_len
length of SSID of station interface

uint8_t *sta_passwd
password of station interface

int sta_passwd_len
length of password of station interface

Espressif Systems 381 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint8_t *softap_ssid
SSID of softap interface

int softap_ssid_len
length of SSID of softap interface

uint8_t *softap_passwd
password of station interface

int softap_passwd_len
length of password of station interface

uint8_t softap_authmode
authentication mode of softap interface

bool softap_authmode_set
is authentication mode of softap interface set

uint8_t softap_max_conn_num
max connection number of softap interface

bool softap_max_conn_num_set
is max connection number of softap interface set

uint8_t softap_channel
channel of softap interface

bool softap_channel_set
is channel of softap interface set

uint8_t sta_max_conn_retry
max retry of sta establish connection

bool sta_max_conn_retry_set
is max retry of sta establish connection set

uint8_t sta_conn_end_reason
reason of sta connection end

bool sta_conn_end_reason_set
is reason of sta connection end set

int8_t sta_conn_rssi
rssi of sta connection

bool sta_conn_rssi_set
is rssi of sta connection set

struct esp_blufi_ap_record_t
Description of an WiFi AP.

Espressif Systems 382 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

uint8_t ssid[33]
SSID of AP

int8_t rssi
signal strength of AP

struct esp_blufi_callbacks_t
BLUFI callback functions type.

Public Members

esp_blufi_event_cb_t event_cb
BLUFI event callback

esp_blufi_negotiate_data_handler_t negotiate_data_handler
BLUFI negotiate data function for negotiate share key

esp_blufi_encrypt_func_t encrypt_func
BLUFI encrypt data function with share key generated by negotiate_data_handler

esp_blufi_decrypt_func_t decrypt_func
BLUFI decrypt data function with share key generated by negotiate_data_handler

esp_blufi_checksum_func_t checksum_func
BLUFI check sum function (FCS)

Macros

ESP_BLUFI_BD_ADDR_LEN
Bluetooth address length.

Type Definitions

typedef uint8_t esp_blufi_bd_addr_t[ESP_BLUFI_BD_ADDR_LEN]


Bluetooth device address.

typedef void (*esp_blufi_event_cb_t)(esp_blufi_cb_event_t event, esp_blufi_cb_param_t *param)


BLUFI event callback function type.
Param event : Event type
Param param : Point to callback parameter, currently is union type

typedef void (*esp_blufi_negotiate_data_handler_t)(uint8_t *data, int len, uint8_t **output_data,


int *output_len, bool *need_free)
BLUFI negotiate data handler.
Param data : data from phone
Param len : length of data from phone
Param output_data : data want to send to phone

Espressif Systems 383 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Param output_len : length of data want to send to phone


Param need_free : output reporting if memory needs to be freed or not *

typedef int (*esp_blufi_encrypt_func_t)(uint8_t iv8, uint8_t *crypt_data, int crypt_len)


BLUFI encrypt the data after negotiate a share key.
Param iv8 : initial vector(8bit), normally, blufi core will input packet sequence number
Param crypt_data : plain text and encrypted data, the encrypt function must support au-
tochthonous encrypt
Param crypt_len : length of plain text
Return Nonnegative number is encrypted length, if error, return negative number;

typedef int (*esp_blufi_decrypt_func_t)(uint8_t iv8, uint8_t *crypt_data, int crypt_len)


BLUFI decrypt the data after negotiate a share key.
Param iv8 : initial vector(8bit), normally, blufi core will input packet sequence number
Param crypt_data : encrypted data and plain text, the encrypt function must support au-
tochthonous decrypt
Param crypt_len : length of encrypted text
Return Nonnegative number is decrypted length, if error, return negative number;

typedef uint16_t (*esp_blufi_checksum_func_t)(uint8_t iv8, uint8_t *data, int len)


BLUFI checksum.
Param iv8 : initial vector(8bit), normally, blufi core will input packet sequence number
Param data : data need to checksum
Param len : length of data

Enumerations

enum esp_blufi_cb_event_t
Values:

enumerator ESP_BLUFI_EVENT_INIT_FINISH

enumerator ESP_BLUFI_EVENT_DEINIT_FINISH

enumerator ESP_BLUFI_EVENT_SET_WIFI_OPMODE

enumerator ESP_BLUFI_EVENT_BLE_CONNECT

enumerator ESP_BLUFI_EVENT_BLE_DISCONNECT

enumerator ESP_BLUFI_EVENT_REQ_CONNECT_TO_AP

enumerator ESP_BLUFI_EVENT_REQ_DISCONNECT_FROM_AP

enumerator ESP_BLUFI_EVENT_GET_WIFI_STATUS

enumerator ESP_BLUFI_EVENT_DEAUTHENTICATE_STA

enumerator ESP_BLUFI_EVENT_RECV_STA_BSSID

Espressif Systems 384 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BLUFI_EVENT_RECV_STA_SSID

enumerator ESP_BLUFI_EVENT_RECV_STA_PASSWD

enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_SSID

enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_PASSWD

enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_MAX_CONN_NUM

enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_AUTH_MODE

enumerator ESP_BLUFI_EVENT_RECV_SOFTAP_CHANNEL

enumerator ESP_BLUFI_EVENT_RECV_USERNAME

enumerator ESP_BLUFI_EVENT_RECV_CA_CERT

enumerator ESP_BLUFI_EVENT_RECV_CLIENT_CERT

enumerator ESP_BLUFI_EVENT_RECV_SERVER_CERT

enumerator ESP_BLUFI_EVENT_RECV_CLIENT_PRIV_KEY

enumerator ESP_BLUFI_EVENT_RECV_SERVER_PRIV_KEY

enumerator ESP_BLUFI_EVENT_RECV_SLAVE_DISCONNECT_BLE

enumerator ESP_BLUFI_EVENT_GET_WIFI_LIST

enumerator ESP_BLUFI_EVENT_REPORT_ERROR

enumerator ESP_BLUFI_EVENT_RECV_CUSTOM_DATA

enum esp_blufi_sta_conn_state_t
BLUFI config status.
Values:

enumerator ESP_BLUFI_STA_CONN_SUCCESS

enumerator ESP_BLUFI_STA_CONN_FAIL

enumerator ESP_BLUFI_STA_CONNECTING

enumerator ESP_BLUFI_STA_NO_IP

Espressif Systems 385 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enum esp_blufi_init_state_t
BLUFI init status.
Values:

enumerator ESP_BLUFI_INIT_OK

enumerator ESP_BLUFI_INIT_FAILED

enum esp_blufi_deinit_state_t
BLUFI deinit status.
Values:

enumerator ESP_BLUFI_DEINIT_OK

enumerator ESP_BLUFI_DEINIT_FAILED

enum esp_blufi_error_state_t
Values:

enumerator ESP_BLUFI_SEQUENCE_ERROR

enumerator ESP_BLUFI_CHECKSUM_ERROR

enumerator ESP_BLUFI_DECRYPT_ERROR

enumerator ESP_BLUFI_ENCRYPT_ERROR

enumerator ESP_BLUFI_INIT_SECURITY_ERROR

enumerator ESP_BLUFI_DH_MALLOC_ERROR

enumerator ESP_BLUFI_DH_PARAM_ERROR

enumerator ESP_BLUFI_READ_PARAM_ERROR

enumerator ESP_BLUFI_MAKE_PUBLIC_ERROR

enumerator ESP_BLUFI_DATA_FORMAT_ERROR

enumerator ESP_BLUFI_CALC_MD5_ERROR

enumerator ESP_BLUFI_WIFI_SCAN_FAIL

enumerator ESP_BLUFI_MSG_STATE_ERROR

Espressif Systems 386 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

2.3.3 Classic Bluetooth®

Classic Bluetooth® GAP API

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_gap_bt_api.h

Functions
static inline uint32_t esp_bt_gap_get_cod_srvc(uint32_t cod)
get major service field of COD
Parameters cod –[in] Class of Device
Returns major service bits
static inline uint32_t esp_bt_gap_get_cod_major_dev(uint32_t cod)
get major device field of COD
Parameters cod –[in] Class of Device
Returns major device bits
static inline uint32_t esp_bt_gap_get_cod_minor_dev(uint32_t cod)
get minor service field of COD
Parameters cod –[in] Class of Device
Returns minor service bits
static inline uint32_t esp_bt_gap_get_cod_format_type(uint32_t cod)
get format type of COD
Parameters cod –[in] Class of Device
Returns format type
static inline bool esp_bt_gap_is_valid_cod(uint32_t cod)
decide the integrity of COD
Parameters cod –[in] Class of Device
Returns
• true if cod is valid
• false otherise
esp_err_t esp_bt_gap_register_callback(esp_bt_gap_cb_t callback)
register callback function. This function should be called after esp_bluedroid_enable() completes successfully
Returns
• ESP_OK : Succeed
• ESP_FAIL: others
esp_err_t esp_bt_gap_set_scan_mode(esp_bt_connection_mode_t c_mode, esp_bt_discovery_mode_t
d_mode)
Set discoverability and connectability mode for legacy bluetooth. This function should be called after
esp_bluedroid_enable() completes successfully.
Parameters
• c_mode –[in] : one of the enums of esp_bt_connection_mode_t
• d_mode –[in] : one of the enums of esp_bt_discovery_mode_t
Returns
• ESP_OK : Succeed
• ESP_ERR_INVALID_ARG: if argument invalid
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled

Espressif Systems 387 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• ESP_FAIL: others
esp_err_t esp_bt_gap_start_discovery(esp_bt_inq_mode_t mode, uint8_t inq_len, uint8_t num_rsps)
This function starts Inquiry and Name Discovery. This function should be called after esp_bluedroid_enable()
completes successfully. When Inquiry is halted and cached results do not contain device name, then Name
Discovery will connect to the peer target to get the device name. esp_bt_gap_cb_t will be called with
ESP_BT_GAP_DISC_STATE_CHANGED_EVT when Inquiry is started or Name Discovery is completed.
esp_bt_gap_cb_t will be called with ESP_BT_GAP_DISC_RES_EVT each time the two types of discovery
results are got.
Parameters
• mode –[in] - Inquiry mode
• inq_len –[in] - Inquiry duration in 1.28 sec units, ranging from 0x01 to 0x30. This
parameter only specifies the total duration of the Inquiry process,
– when this time expires, Inquiry will be halted.
• num_rsps –[in] - Number of responses that can be received before the Inquiry is halted,
value 0 indicates an unlimited number of responses.
Returns
• ESP_OK : Succeed
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_ERR_INVALID_ARG: if invalid parameters are provided
• ESP_FAIL: others
esp_err_t esp_bt_gap_cancel_discovery(void)
Cancel Inquiry and Name Discovery. This function should be called after esp_bluedroid_enable() completes
successfully. esp_bt_gap_cb_t will be called with ESP_BT_GAP_DISC_STATE_CHANGED_EVT if In-
quiry or Name Discovery is cancelled by calling this function.
Returns
• ESP_OK : Succeed
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_bt_gap_get_remote_services(esp_bd_addr_t remote_bda)
Start SDP to get remote services. This function should be called after esp_bluedroid_enable() completes suc-
cessfully. esp_bt_gap_cb_t will be called with ESP_BT_GAP_RMT_SRVCS_EVT after service discovery
ends.
Returns
• ESP_OK : Succeed
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_bt_gap_get_remote_service_record(esp_bd_addr_t remote_bda, esp_bt_uuid_t
*uuid)
Start SDP to look up the service matching uuid on the remote device. This function should be called after
esp_bluedroid_enable() completes successfully.
esp_bt_gap_cb_t will be called with ESP_BT_GAP_RMT_SRVC_REC_EVT after service discovery ends
Returns
• ESP_OK : Succeed
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
uint8_t *esp_bt_gap_resolve_eir_data(uint8_t *eir, esp_bt_eir_type_t type, uint8_t *length)
This function is called to get EIR data for a specific type.
Parameters
• eir –[in] - pointer of raw eir data to be resolved
• type –[in] - specific EIR data type
• length –[out] - return the length of EIR data excluding fields of length and data type

Espressif Systems 388 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Returns pointer of starting position of eir data excluding eir data type, NULL if not found
esp_err_t esp_bt_gap_config_eir_data(esp_bt_eir_data_t *eir_data)
This function is called to config EIR data.

esp_bt_gap_cb_t will be called with ESP_BT_GAP_CONFIG_EIR_DATA_


,→EVT after config EIR ends.

Parameters eir_data –[in] - pointer of EIR data content


Returns
• ESP_OK : Succeed
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_ERR_INVALID_ARG: if param is invalid
• ESP_FAIL: others

esp_err_t esp_bt_gap_set_cod(esp_bt_cod_t cod, esp_bt_cod_mode_t mode)


This function is called to set class of device. The structure esp_bt_gap_cb_t will be called with
ESP_BT_GAP_SET_COD_EVT after set COD ends. This function should be called after Bluetooth profiles
are initialized, otherwise the user configured class of device can be overwritten. Some profiles have special
restrictions on class of device, and changes may make these profiles unable to work.
Parameters
• cod –[in] - class of device
• mode –[in] - setting mode
Returns
• ESP_OK : Succeed
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_ERR_INVALID_ARG: if param is invalid
• ESP_FAIL: others
esp_err_t esp_bt_gap_get_cod(esp_bt_cod_t *cod)
This function is called to get class of device.
Parameters cod –[out] - class of device
Returns
• ESP_OK : Succeed
• ESP_FAIL: others
esp_err_t esp_bt_gap_read_rssi_delta(esp_bd_addr_t remote_addr)
This function is called to read RSSI delta by address after connected. The RSSI value returned by
ESP_BT_GAP_READ_RSSI_DELTA_EVT.
Parameters remote_addr –[in] - remote device address, corresponding to a certain connection
handle
Returns
• ESP_OK : Succeed
• ESP_FAIL: others
esp_err_t esp_bt_gap_remove_bond_device(esp_bd_addr_t bd_addr)
Removes a device from the security database list of peer device.
Parameters bd_addr –[in] : BD address of the peer device
Returns - ESP_OK : success
• ESP_FAIL : failed
int esp_bt_gap_get_bond_device_num(void)
Get the device number from the security database list of peer device. It will return the device bonded number
immediately.
Returns - >= 0 : bonded devices number

Espressif Systems 389 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• ESP_FAIL : failed
esp_err_t esp_bt_gap_get_bond_device_list(int *dev_num, esp_bd_addr_t *dev_list)
Get the device from the security database list of peer device. It will return the device bonded information
immediately.
Parameters
• dev_num –[inout] Indicate the dev_list array(buffer) size as input. If dev_num is large
enough, it means the actual number as output. Suggest that dev_num value equal to
esp_ble_get_bond_device_num().
• dev_list –[out] an array(buffer) of esp_bd_addr_t type. Use for storing the
bonded devices address. The dev_list should be allocated by who call this API.
Returns
• ESP_OK : Succeed
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_bt_gap_set_pin(esp_bt_pin_type_t pin_type, uint8_t pin_code_len, esp_bt_pin_code_t
pin_code)
Set pin type and default pin code for legacy pairing.
Parameters
• pin_type –[in] Use variable or fixed pin. If pin_type is
ESP_BT_PIN_TYPE_VARIABLE, pin_code and pin_code_len will be ignored,
and ESP_BT_GAP_PIN_REQ_EVT will come when control requests for pin code. Else,
will use fixed pin code and not callback to users.
• pin_code_len –[in] Length of pin_code
• pin_code –[in] Pin_code
Returns - ESP_OK : success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other : failed
esp_err_t esp_bt_gap_pin_reply(esp_bd_addr_t bd_addr, bool accept, uint8_t pin_code_len,
esp_bt_pin_code_t pin_code)
Reply the pin_code to the peer device for legacy pairing when ESP_BT_GAP_PIN_REQ_EVT is coming.
Parameters
• bd_addr –[in] BD address of the peer
• accept –[in] Pin_code reply successful or declined.
• pin_code_len –[in] Length of pin_code
• pin_code –[in] Pin_code
Returns - ESP_OK : success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other : failed
esp_err_t esp_bt_gap_set_security_param(esp_bt_sp_param_t param_type, void *value, uint8_t len)
Set a GAP security parameter value. Overrides the default value.
Parameters
• param_type –[in] : the type of the param which is to be set
• value –[in] : the param value
• len –[in] : the length of the param value
Returns - ESP_OK : success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other : failed
esp_err_t esp_bt_gap_ssp_passkey_reply(esp_bd_addr_t bd_addr, bool accept, uint32_t passkey)
Reply the key value to the peer device in the legacy connection stage.
Parameters
• bd_addr –[in] : BD address of the peer
• accept –[in] : passkey entry successful or declined.

Espressif Systems 390 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• passkey –[in] : passkey value, must be a 6 digit number, can be lead by 0.


Returns - ESP_OK : success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other : failed
esp_err_t esp_bt_gap_ssp_confirm_reply(esp_bd_addr_t bd_addr, bool accept)
Reply the confirm value to the peer device in the legacy connection stage.
Parameters
• bd_addr –[in] : BD address of the peer device
• accept –[in] : numbers to compare are the same or different
Returns - ESP_OK : success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other : failed
esp_err_t esp_bt_gap_set_afh_channels(esp_bt_gap_afh_channels channels)
Set the AFH channels.
Parameters channels –[in] : The n th such field (in the range 0 to 78) contains the value for
channel n : 0 means channel n is bad. 1 means channel n is unknown. The most significant bit
is reserved and shall be set to 0. At least 20 channels shall be marked as unknown.
Returns - ESP_OK : success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other : failed
esp_err_t esp_bt_gap_read_remote_name(esp_bd_addr_t remote_bda)
Read the remote device name.
Parameters remote_bda –[in] The remote device’s address
Returns - ESP_OK : success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other : failed
esp_err_t esp_bt_gap_set_qos(esp_bd_addr_t remote_bda, uint32_t t_poll)
Config Quality of service.
Parameters
• remote_bda –[in] The remote device’s address
• t_poll –[in] Poll interval, the maximum time between transmissions which from the
master to a particular slave on the ACL logical transport. unit is 0.625ms
Returns - ESP_OK : success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other : failed
esp_err_t esp_bt_gap_set_page_timeout(uint16_t page_to)
Set the page timeout esp_bt_gap_cb_t will be called with ESP_BT_GAP_SET_PAGE_TO_EVT after set page
timeout ends. The value to be set will not be effective util the next page procedure, it’s suggested to set the
page timeout before initiating a connection.
Parameters page_to –[in] Page timeout, the maximum time the master will wait for a Base-
band page response from the remote device at a locally initiated connection attempt. The valid
range is 0x0016 ~ 0xffff, the default value is 0x2000, unit is 0.625ms.
Returns - ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other: failed
esp_err_t esp_bt_gap_get_page_timeout(void)
Get the page timeout esp_bt_gap_cb_t will be called with ESP_BT_GAP_GET_PAGE_TO_EVT after get
page timeout ends.
Returns - ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• other: failed

Espressif Systems 391 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Unions

union esp_bt_gap_cb_param_t
#include <esp_gap_bt_api.h> GAP state callback parameters.

Public Members

struct esp_bt_gap_cb_param_t::disc_res_param disc_res


discovery result parameter struct

struct esp_bt_gap_cb_param_t::disc_state_changed_param disc_st_chg


discovery state changed parameter struct

struct esp_bt_gap_cb_param_t::rmt_srvcs_param rmt_srvcs


services of remote device parameter struct

struct esp_bt_gap_cb_param_t::rmt_srvc_rec_param rmt_srvc_rec


specific service record from remote device parameter struct

struct esp_bt_gap_cb_param_t::read_rssi_delta_param read_rssi_delta


read rssi parameter struct

struct esp_bt_gap_cb_param_t::config_eir_data_param config_eir_data


config EIR data

struct esp_bt_gap_cb_param_t::auth_cmpl_param auth_cmpl


authentication complete parameter struct

struct esp_bt_gap_cb_param_t::pin_req_param pin_req


pin request parameter struct

struct esp_bt_gap_cb_param_t::cfm_req_param cfm_req


confirm request parameter struct

struct esp_bt_gap_cb_param_t::key_notif_param key_notif


passkey notif parameter struct

struct esp_bt_gap_cb_param_t::key_req_param key_req


passkey request parameter struct

struct esp_bt_gap_cb_param_t::set_afh_channels_param set_afh_channels


set AFH channel parameter struct

struct esp_bt_gap_cb_param_t::read_rmt_name_param read_rmt_name


read Remote Name parameter struct

struct esp_bt_gap_cb_param_t::mode_chg_param mode_chg


mode change event parameter struct

Espressif Systems 392 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_bt_gap_cb_param_t::bt_remove_bond_dev_cmpl_evt_param remove_bond_dev_cmpl


Event parameter of ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT

struct esp_bt_gap_cb_param_t::qos_cmpl_param qos_cmpl


QoS complete parameter struct

struct esp_bt_gap_cb_param_t::page_to_set_param set_page_timeout


set page timeout parameter struct

struct esp_bt_gap_cb_param_t::page_to_get_param get_page_timeout


get page timeout parameter struct

struct esp_bt_gap_cb_param_t::acl_conn_cmpl_stat_param acl_conn_cmpl_stat


ACL connection complete status parameter struct

struct esp_bt_gap_cb_param_t::acl_disconn_cmpl_stat_param acl_disconn_cmpl_stat


ACL disconnection complete status parameter struct

struct acl_conn_cmpl_stat_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_ACL_CONN_CMPL_STAT_EVT.

Public Members

esp_bt_status_t stat
ACL connection status

uint16_t handle
ACL connection handle

esp_bd_addr_t bda
remote bluetooth device address

struct acl_disconn_cmpl_stat_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_ACL_DISCONN_CMPL_STAT_EVT.

Public Members

esp_bt_status_t reason
ACL disconnection reason

uint16_t handle
ACL connection handle

esp_bd_addr_t bda
remote bluetooth device address

struct auth_cmpl_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_AUTH_CMPL_EVT.

Espressif Systems 393 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_bd_addr_t bda
remote bluetooth device address

esp_bt_status_t stat
authentication complete status

uint8_t device_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1]
device name

struct bt_remove_bond_dev_cmpl_evt_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT.

Public Members

esp_bd_addr_t bda
remote bluetooth device address

esp_bt_status_t status
Indicate the remove bond device operation success status

struct cfm_req_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_CFM_REQ_EVT.

Public Members

esp_bd_addr_t bda
remote bluetooth device address

uint32_t num_val
the numeric value for comparison.

struct config_eir_data_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_CONFIG_EIR_DATA_EVT *.

Public Members

esp_bt_status_t stat
config EIR status: ESP_BT_STATUS_SUCCESS: config success
ESP_BT_STATUS_EIR_TOO_LARGE: the EIR data is more than 240B. The EIR may not
contain the whole data. others: failed

uint8_t eir_type_num
the number of EIR types in EIR type

Espressif Systems 394 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_bt_eir_type_t eir_type[ESP_BT_EIR_TYPE_MAX_NUM]
EIR types in EIR type

struct disc_res_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_DISC_RES_EVT.

Public Members

esp_bd_addr_t bda
remote bluetooth device address

int num_prop
number of properties got

esp_bt_gap_dev_prop_t *prop
properties discovered from the new device

struct disc_state_changed_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_DISC_STATE_CHANGED_EVT.

Public Members

esp_bt_gap_discovery_state_t state
discovery state

struct key_notif_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_KEY_NOTIF_EVT.

Public Members

esp_bd_addr_t bda
remote bluetooth device address

uint32_t passkey
the numeric value for passkey entry.

struct key_req_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_KEY_REQ_EVT.

Public Members

esp_bd_addr_t bda
remote bluetooth device address

struct mode_chg_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_MODE_CHG_EVT.

Espressif Systems 395 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_bd_addr_t bda
remote bluetooth device address

esp_bt_pm_mode_t mode
PM mode

struct page_to_get_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_GET_PAGE_TO_EVT.

Public Members

esp_bt_status_t stat
get page timeout status

uint16_t page_to
page_timeout value to be set, unit is 0.625ms.

struct page_to_set_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_SET_PAGE_TO_EVT.

Public Members

esp_bt_status_t stat
set page timeout status

struct pin_req_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_PIN_REQ_EVT.

Public Members

esp_bd_addr_t bda
remote bluetooth device address

bool min_16_digit
TRUE if the pin returned must be at least 16 digits

struct qos_cmpl_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_QOS_CMPL_EVT.

Public Members

esp_bt_status_t stat
QoS status

Espressif Systems 396 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_bd_addr_t bda
remote bluetooth device address

uint32_t t_poll
poll interval, the maximum time between transmissions which from the master to a particular slave
on the ACL logical transport. unit is 0.625ms.

struct read_rmt_name_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_READ_REMOTE_NAME_EVT.

Public Members

esp_bd_addr_t bda
remote bluetooth device address

esp_bt_status_t stat
read Remote Name status

uint8_t rmt_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1]
Remote device name

struct read_rssi_delta_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_READ_RSSI_DELTA_EVT *.

Public Members

esp_bd_addr_t bda
remote bluetooth device address

esp_bt_status_t stat
read rssi status

int8_t rssi_delta
rssi delta value range -128 ~127, The value zero indicates that the RSSI is inside the Golden Receive
Power Range, the Golden Receive Power Range is from ESP_BT_GAP_RSSI_LOW_THRLD to
ESP_BT_GAP_RSSI_HIGH_THRLD

struct rmt_srvc_rec_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_RMT_SRVC_REC_EVT.

Public Members

esp_bd_addr_t bda
remote bluetooth device address

esp_bt_status_t stat
service search status

Espressif Systems 397 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct rmt_srvcs_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_RMT_SRVCS_EVT.

Public Members

esp_bd_addr_t bda
remote bluetooth device address

esp_bt_status_t stat
service search status

int num_uuids
number of UUID in uuid_list

esp_bt_uuid_t *uuid_list
list of service UUIDs of remote device

struct set_afh_channels_param
#include <esp_gap_bt_api.h> ESP_BT_GAP_SET_AFH_CHANNELS_EVT.

Public Members

esp_bt_status_t stat
set AFH channel status

Structures

struct esp_bt_cod_t
Class of device.

Public Members

uint32_t reserved_2
undefined

uint32_t minor
minor class

uint32_t major
major class

uint32_t service
service class

uint32_t reserved_8
undefined

Espressif Systems 398 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_bt_gap_dev_prop_t
Bluetooth Device Property Descriptor.

Public Members

esp_bt_gap_dev_prop_type_t type
Device property type

int len
Device property value length

void *val
Device property value

struct esp_bt_eir_data_t
EIR data content, according to “Supplement to the Bluetooth Core Specification”.

Public Members

bool fec_required
FEC is required or not, true by default

bool include_txpower
EIR data include TX power, false by default

bool include_uuid
EIR data include UUID, false by default

bool include_name
EIR data include device name, true by default

uint8_t flag
EIR flags, see ESP_BT_EIR_FLAG for details, EIR will not include flag if it is 0, 0 by default

uint16_t manufacturer_len
Manufacturer data length, 0 by default

uint8_t *p_manufacturer_data
Manufacturer data point

uint16_t url_len
URL length, 0 by default

uint8_t *p_url
URL point

Espressif Systems 399 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Macros

ESP_BT_GAP_RSSI_HIGH_THRLD
RSSI threshold.
High RSSI threshold

ESP_BT_GAP_RSSI_LOW_THRLD
Low RSSI threshold

ESP_BT_GAP_AFH_CHANNELS_LEN

ESP_BT_GAP_MAX_BDNAME_LEN
Maximum bytes of Bluetooth device name.

ESP_BT_GAP_EIR_DATA_LEN
Maximum size of EIR Significant part.

ESP_BT_EIR_TYPE_FLAGS
Extended Inquiry Response data type.
Flag with information such as BR/EDR and LE support

ESP_BT_EIR_TYPE_INCMPL_16BITS_UUID
Incomplete list of 16-bit service UUIDs

ESP_BT_EIR_TYPE_CMPL_16BITS_UUID
Complete list of 16-bit service UUIDs

ESP_BT_EIR_TYPE_INCMPL_32BITS_UUID
Incomplete list of 32-bit service UUIDs

ESP_BT_EIR_TYPE_CMPL_32BITS_UUID
Complete list of 32-bit service UUIDs

ESP_BT_EIR_TYPE_INCMPL_128BITS_UUID
Incomplete list of 128-bit service UUIDs

ESP_BT_EIR_TYPE_CMPL_128BITS_UUID
Complete list of 128-bit service UUIDs

ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME
Shortened Local Name

ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME
Complete Local Name

ESP_BT_EIR_TYPE_TX_POWER_LEVEL
Tx power level, value is 1 octet ranging from -127 to 127, unit is dBm

ESP_BT_EIR_TYPE_URL
Uniform resource identifier

Espressif Systems 400 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BT_EIR_TYPE_MANU_SPECIFIC
Manufacturer specific data

ESP_BT_EIR_TYPE_MAX_NUM
MAX number of EIR type

ESP_BT_EIR_FLAG_LIMIT_DISC

ESP_BT_EIR_FLAG_GEN_DISC

ESP_BT_EIR_FLAG_BREDR_NOT_SPT

ESP_BT_EIR_FLAG_DMT_CONTROLLER_SPT

ESP_BT_EIR_FLAG_DMT_HOST_SPT

ESP_BT_EIR_MAX_LEN

ESP_BT_PIN_CODE_LEN
Max pin code length

ESP_BT_IO_CAP_OUT

ESP_BT_IO_CAP_IO

ESP_BT_IO_CAP_IN

ESP_BT_IO_CAP_NONE

ESP_BT_PM_MD_ACTIVE
Active mode

ESP_BT_PM_MD_HOLD
Hold mode

ESP_BT_PM_MD_SNIFF
Sniff mode

ESP_BT_PM_MD_PARK
Park state

ESP_BT_COD_SRVC_BIT_MASK
Bits of major service class field.
Major service bit mask

ESP_BT_COD_SRVC_BIT_OFFSET
Major service bit offset

Espressif Systems 401 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BT_COD_MAJOR_DEV_BIT_MASK
Bits of major device class field.
Major device bit mask

ESP_BT_COD_MAJOR_DEV_BIT_OFFSET
Major device bit offset

ESP_BT_COD_MINOR_DEV_BIT_MASK
Bits of minor device class field.
Minor device bit mask

ESP_BT_COD_MINOR_DEV_BIT_OFFSET
Minor device bit offset

ESP_BT_COD_FORMAT_TYPE_BIT_MASK
Bits of format type.
Format type bit mask

ESP_BT_COD_FORMAT_TYPE_BIT_OFFSET
Format type bit offset

ESP_BT_COD_FORMAT_TYPE_1
Class of device format type 1.

ESP_BT_GAP_MIN_INQ_LEN
Minimum and Maximum inquiry length Minimum inquiry duration, unit is 1.28s

ESP_BT_GAP_MAX_INQ_LEN
Maximum inquiry duration, unit is 1.28s

Type Definitions

typedef uint8_t esp_bt_gap_afh_channels[ESP_BT_GAP_AFH_CHANNELS_LEN]

typedef uint8_t esp_bt_eir_type_t

typedef uint8_t esp_bt_pin_code_t[ESP_BT_PIN_CODE_LEN]


Pin Code (upto 128 bits) MSB is 0

typedef uint8_t esp_bt_io_cap_t


Combination of the IO Capability

typedef uint8_t esp_bt_pm_mode_t

typedef void (*esp_bt_gap_cb_t)(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param)


bluetooth GAP callback function type
Param event : Event type
Param param : Pointer to callback parameter

Espressif Systems 402 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Enumerations

enum esp_bt_cod_mode_t
class of device settings
Values:

enumerator ESP_BT_SET_COD_MAJOR_MINOR
overwrite major, minor class

enumerator ESP_BT_SET_COD_SERVICE_CLASS
set the bits in the input, the current bit will remain

enumerator ESP_BT_CLR_COD_SERVICE_CLASS
clear the bits in the input, others will remain

enumerator ESP_BT_SET_COD_ALL
overwrite major, minor, set the bits in service class

enumerator ESP_BT_INIT_COD
overwrite major, minor, and service class

enum esp_bt_connection_mode_t
Discoverability and Connectability mode.
Values:

enumerator ESP_BT_NON_CONNECTABLE
Non-connectable

enumerator ESP_BT_CONNECTABLE
Connectable

enum esp_bt_discovery_mode_t
Values:

enumerator ESP_BT_NON_DISCOVERABLE
Non-discoverable

enumerator ESP_BT_LIMITED_DISCOVERABLE
Limited Discoverable

enumerator ESP_BT_GENERAL_DISCOVERABLE
General Discoverable

enum esp_bt_gap_dev_prop_type_t
Bluetooth Device Property type.
Values:

enumerator ESP_BT_GAP_DEV_PROP_BDNAME
Bluetooth device name, value type is int8_t []

Espressif Systems 403 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BT_GAP_DEV_PROP_COD
Class of Device, value type is uint32_t

enumerator ESP_BT_GAP_DEV_PROP_RSSI
Received Signal strength Indication, value type is int8_t, ranging from -128 to 127

enumerator ESP_BT_GAP_DEV_PROP_EIR
Extended Inquiry Response, value type is uint8_t []

enum esp_bt_cod_srvc_t
Major service class field of Class of Device, mutiple bits can be set.
Values:

enumerator ESP_BT_COD_SRVC_NONE
None indicates an invalid value

enumerator ESP_BT_COD_SRVC_LMTD_DISCOVER
Limited Discoverable Mode

enumerator ESP_BT_COD_SRVC_POSITIONING
Positioning (Location identification)

enumerator ESP_BT_COD_SRVC_NETWORKING
Networking, e.g. LAN, Ad hoc

enumerator ESP_BT_COD_SRVC_RENDERING
Rendering, e.g. Printing, Speakers

enumerator ESP_BT_COD_SRVC_CAPTURING
Capturing, e.g. Scanner, Microphone

enumerator ESP_BT_COD_SRVC_OBJ_TRANSFER
Object Transfer, e.g. v-Inbox, v-Folder

enumerator ESP_BT_COD_SRVC_AUDIO
Audio, e.g. Speaker, Microphone, Headset service

enumerator ESP_BT_COD_SRVC_TELEPHONY
Telephony, e.g. Cordless telephony, Modem, Headset service

enumerator ESP_BT_COD_SRVC_INFORMATION
Information, e.g., WEB-server, WAP-server

enum esp_bt_pin_type_t
Values:

enumerator ESP_BT_PIN_TYPE_VARIABLE
Refer to BTM_PIN_TYPE_VARIABLE

Espressif Systems 404 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BT_PIN_TYPE_FIXED
Refer to BTM_PIN_TYPE_FIXED

enum esp_bt_sp_param_t
Values:

enumerator ESP_BT_SP_IOCAP_MODE
Set IO mode

enum esp_bt_cod_major_dev_t
Major device class field of Class of Device.
Values:

enumerator ESP_BT_COD_MAJOR_DEV_MISC
Miscellaneous

enumerator ESP_BT_COD_MAJOR_DEV_COMPUTER
Computer

enumerator ESP_BT_COD_MAJOR_DEV_PHONE
Phone(cellular, cordless, pay phone, modem

enumerator ESP_BT_COD_MAJOR_DEV_LAN_NAP
LAN, Network Access Point

enumerator ESP_BT_COD_MAJOR_DEV_AV
Audio/Video(headset, speaker, stereo, video display, VCR

enumerator ESP_BT_COD_MAJOR_DEV_PERIPHERAL
Peripheral(mouse, joystick, keyboard)

enumerator ESP_BT_COD_MAJOR_DEV_IMAGING
Imaging(printer, scanner, camera, display

enumerator ESP_BT_COD_MAJOR_DEV_WEARABLE
Wearable

enumerator ESP_BT_COD_MAJOR_DEV_TOY
Toy

enumerator ESP_BT_COD_MAJOR_DEV_HEALTH
Health

enumerator ESP_BT_COD_MAJOR_DEV_UNCATEGORIZED
Uncategorized: device not specified

enum esp_bt_gap_discovery_state_t
Bluetooth Device Discovery state
Values:

Espressif Systems 405 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BT_GAP_DISCOVERY_STOPPED
Device discovery stopped

enumerator ESP_BT_GAP_DISCOVERY_STARTED
Device discovery started

enum esp_bt_gap_cb_event_t
BT GAP callback events.
Values:

enumerator ESP_BT_GAP_DISC_RES_EVT
Device discovery result event

enumerator ESP_BT_GAP_DISC_STATE_CHANGED_EVT
Discovery state changed event

enumerator ESP_BT_GAP_RMT_SRVCS_EVT
Get remote services event

enumerator ESP_BT_GAP_RMT_SRVC_REC_EVT
Get remote service record event

enumerator ESP_BT_GAP_AUTH_CMPL_EVT
Authentication complete event

enumerator ESP_BT_GAP_PIN_REQ_EVT
Legacy Pairing Pin code request

enumerator ESP_BT_GAP_CFM_REQ_EVT
Security Simple Pairing User Confirmation request.

enumerator ESP_BT_GAP_KEY_NOTIF_EVT
Security Simple Pairing Passkey Notification

enumerator ESP_BT_GAP_KEY_REQ_EVT
Security Simple Pairing Passkey request

enumerator ESP_BT_GAP_READ_RSSI_DELTA_EVT
Read rssi event

enumerator ESP_BT_GAP_CONFIG_EIR_DATA_EVT
Config EIR data event

enumerator ESP_BT_GAP_SET_AFH_CHANNELS_EVT
Set AFH channels event

enumerator ESP_BT_GAP_READ_REMOTE_NAME_EVT
Read Remote Name event

Espressif Systems 406 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_BT_GAP_MODE_CHG_EVT

enumerator ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT
remove bond device complete event

enumerator ESP_BT_GAP_QOS_CMPL_EVT
QOS complete event

enumerator ESP_BT_GAP_ACL_CONN_CMPL_STAT_EVT
ACL connection complete status event

enumerator ESP_BT_GAP_ACL_DISCONN_CMPL_STAT_EVT
ACL disconnection complete status event

enumerator ESP_BT_GAP_SET_PAGE_TO_EVT
Set page timeout event

enumerator ESP_BT_GAP_GET_PAGE_TO_EVT
Get page timeout event

enumerator ESP_BT_GAP_EVT_MAX

enum esp_bt_inq_mode_t
Inquiry Mode
Values:

enumerator ESP_BT_INQ_MODE_GENERAL_INQUIRY
General inquiry mode

enumerator ESP_BT_INQ_MODE_LIMITED_INQUIRY
Limited inquiry mode

Bluetooth® A2DP API

Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the fol-
lowing application:
• This is a A2DP sink client demo. This demo can be discovered and connected by A2DP source device and
receive the audio stream from remote device - bluetooth/bluedroid/classic_bt/a2dp_sink

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_a2dp_api.h

Espressif Systems 407 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Functions
esp_err_t esp_a2d_register_callback(esp_a2d_cb_t callback)
Register application callback function to A2DP module. This function should be called only after
esp_bluedroid_enable() completes successfully, used by both A2DP source and sink.
Parameters callback –[in] A2DP event callback function
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: if callback is a NULL function pointer
esp_err_t esp_a2d_sink_register_data_callback(esp_a2d_sink_data_cb_t callback)
Register A2DP sink data output function; For now the output is PCM data stream decoded from SBC format.
This function should be called only after esp_bluedroid_enable() completes successfully, used only by A2DP
sink. The callback is invoked in the context of A2DP sink task whose stack size is configurable through
menuconfig.
Parameters callback –[in] A2DP sink data callback function
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: if callback is a NULL function pointer
esp_err_t esp_a2d_sink_init(void)
Initialize the bluetooth A2DP sink module. This function should be called after esp_bluedroid_enable() com-
pletes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_INIT_SUCCESS will reported to
the APP layer. Note: A2DP can work independently. If you want to use AVRC together, you should initiate
AVRC first. This function should be called after esp_bluedroid_enable() completes successfully.
Returns
• ESP_OK: if the initialization request is sent successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_sink_deinit(void)
De-initialize for A2DP sink module. This function should be called only after esp_bluedroid_enable() com-
pletes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_DEINIT_SUCCESS will reported
to APP layer.
Returns
• ESP_OK: if the deinitialization request is sent successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_sink_connect(esp_bd_addr_t remote_bda)
Connect to remote bluetooth A2DP source device. This API must be called after esp_a2d_sink_init() and
before esp_a2d_sink_deinit().
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: connect request is sent to lower layer successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_sink_disconnect(esp_bd_addr_t remote_bda)
Disconnect from the remote A2DP source device. This API must be called after esp_a2d_sink_init() and
before esp_a2d_sink_deinit().
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: disconnect request is sent to lower layer successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others

Espressif Systems 408 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_a2d_sink_set_delay_value(uint16_t delay_value)


Set delay reporting value. The delay value of sink is caused by buffering (including protocol stack and appli-
cation layer), decoding and rendering. The default delay value is 120ms, if the set value is less than 120ms,
the setting will fail. This API must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit().
Parameters delay_value –[in] reporting value is in 1/10 millisecond
Returns
• ESP_OK: delay value is sent to lower layer successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_sink_get_delay_value(void)
Get delay reporting value. This API must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit().
Returns
• ESP_OK: if the request is sent successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_media_ctrl(esp_a2d_media_ctrl_t ctrl)
Media control commands. This API can be used for both A2DP sink and source and must be called after
esp_a2d_sink_init() and before esp_a2d_sink_deinit().
Parameters ctrl –[in] control commands for A2DP data channel
Returns
• ESP_OK: control command is sent to lower layer successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_source_init(void)
Initialize the bluetooth A2DP source module. A2DP can work independently. If you want to use AVRC
together, you should initiate AVRC first. This function should be called after esp_bluedroid_enable() completes
successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_INIT_SUCCESS will reported to the APP
layer. Note: A2DP can work independently. If you want to use AVRC together, you should initiate AVRC
first.
Returns
• ESP_OK: if the initialization request is sent to lower layer successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_source_deinit(void)
De-initialize for A2DP source module. This function should be called only after esp_bluedroid_enable() com-
pletes successfully, and ESP_A2D_PROF_STATE_EVT with ESP_A2D_DEINIT_SUCCESS will reported
to APP layer.
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_source_register_data_callback(esp_a2d_source_data_cb_t callback)
Register A2DP source data input function. For now, the input shoule be PCM data stream. This function should
be called only after esp_bluedroid_enable() completes successfully. The callback is invoked in the context of
A2DP source task whose stack size is configurable through menuconfig.
Parameters callback –[in] A2DP source data callback function
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: if callback is a NULL function pointer

Espressif Systems 409 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_a2d_source_connect(esp_bd_addr_t remote_bda)


Connect to remote A2DP sink device. This API must be called after esp_a2d_source_init() and before
esp_a2d_source_deinit().
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: connect request is sent to lower layer successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_a2d_source_disconnect(esp_bd_addr_t remote_bda)
Disconnect from the remote A2DP sink device. This API must be called after esp_a2d_source_init() and
before esp_a2d_source_deinit().
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others

Unions

union esp_a2d_cb_param_t
#include <esp_a2dp_api.h> A2DP state callback parameters.

Public Members

struct esp_a2d_cb_param_t::a2d_conn_stat_param conn_stat


A2DP connection status

struct esp_a2d_cb_param_t::a2d_audio_stat_param audio_stat


audio stream playing state

struct esp_a2d_cb_param_t::a2d_audio_cfg_param audio_cfg


media codec configuration information

struct esp_a2d_cb_param_t::media_ctrl_stat_param media_ctrl_stat


status in acknowledgement to media control commands

struct esp_a2d_cb_param_t::a2d_prof_stat_param a2d_prof_stat


status to indicate a2d prof init or deinit

struct esp_a2d_cb_param_t::a2d_psc_cfg_param a2d_psc_cfg_stat


status to indicate protocol service capabilities configured

struct esp_a2d_cb_param_t::a2d_set_stat_param a2d_set_delay_value_stat


A2DP sink set delay report value status

struct esp_a2d_cb_param_t::a2d_get_stat_param a2d_get_delay_value_stat


A2DP sink get delay report value status

Espressif Systems 410 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_a2d_cb_param_t::a2d_report_delay_stat_param a2d_report_delay_value_stat


A2DP source received sink report value status

struct a2d_audio_cfg_param
#include <esp_a2dp_api.h> ESP_A2D_AUDIO_CFG_EVT.

Public Members

esp_bd_addr_t remote_bda
remote bluetooth device address

esp_a2d_mcc_t mcc
A2DP media codec capability information

struct a2d_audio_stat_param
#include <esp_a2dp_api.h> ESP_A2D_AUDIO_STATE_EVT.

Public Members

esp_a2d_audio_state_t state
one of the values from esp_a2d_audio_state_t

esp_bd_addr_t remote_bda
remote bluetooth device address

struct a2d_conn_stat_param
#include <esp_a2dp_api.h> ESP_A2D_CONNECTION_STATE_EVT.

Public Members

esp_a2d_connection_state_t state
one of values from esp_a2d_connection_state_t

esp_bd_addr_t remote_bda
remote bluetooth device address

esp_a2d_disc_rsn_t disc_rsn
reason of disconnection for “DISCONNECTED”

struct a2d_get_stat_param
#include <esp_a2dp_api.h> ESP_A2D_SNK_GET_DELAY_VALUE_EVT.

Public Members

uint16_t delay_value
delay report value

Espressif Systems 411 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct a2d_prof_stat_param
#include <esp_a2dp_api.h> ESP_A2D_PROF_STATE_EVT.

Public Members

esp_a2d_init_state_t init_state
a2dp profile state param

struct a2d_psc_cfg_param
#include <esp_a2dp_api.h> ESP_A2D_SNK_PSC_CFG_EVT.

Public Members

esp_a2d_psc_t psc_mask
protocol service capabilities configured

struct a2d_report_delay_stat_param
#include <esp_a2dp_api.h> ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT.

Public Members

uint16_t delay_value
delay report value

struct a2d_set_stat_param
#include <esp_a2dp_api.h> ESP_A2D_SNK_SET_DELAY_VALUE_EVT.

Public Members

esp_a2d_set_delay_value_state_t set_state
a2dp profile state param

uint16_t delay_value
delay report value

struct media_ctrl_stat_param
#include <esp_a2dp_api.h> ESP_A2D_MEDIA_CTRL_ACK_EVT.

Public Members

esp_a2d_media_ctrl_t cmd
media control commands to acknowledge

esp_a2d_media_ctrl_ack_t status
acknowledgement to media control commands

Espressif Systems 412 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Structures

struct esp_a2d_mcc_t
A2DP media codec capabilities union.

Public Members

esp_a2d_mct_t type
A2DP media codec type

uint8_t sbc[ESP_A2D_CIE_LEN_SBC]
SBC codec capabilities

uint8_t m12[ESP_A2D_CIE_LEN_M12]
MPEG-1,2 audio codec capabilities

uint8_t m24[ESP_A2D_CIE_LEN_M24]
MPEG-2, 4 AAC audio codec capabilities

uint8_t atrac[ESP_A2D_CIE_LEN_ATRAC]
ATRAC family codec capabilities

union esp_a2d_mcc_t::[anonymous] cie


A2DP codec information element

Macros

ESP_A2D_MCT_SBC
Media codec types supported by A2DP.
SBC

ESP_A2D_MCT_M12
MPEG-1, 2 Audio

ESP_A2D_MCT_M24
MPEG-2, 4 AAC

ESP_A2D_MCT_ATRAC
ATRAC family

ESP_A2D_MCT_NON_A2DP
NON-A2DP

ESP_A2D_PSC_DELAY_RPT
Protocol service capabilities. This value is a mask.
Delay Report

ESP_A2D_CIE_LEN_SBC

Espressif Systems 413 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_A2D_CIE_LEN_M12

ESP_A2D_CIE_LEN_M24

ESP_A2D_CIE_LEN_ATRAC

Type Definitions

typedef uint8_t esp_a2d_mct_t

typedef uint16_t esp_a2d_psc_t

typedef void (*esp_a2d_cb_t)(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param)


A2DP profile callback function type.
Param event : Event type
Param param : Pointer to callback parameter

typedef void (*esp_a2d_sink_data_cb_t)(const uint8_t *buf, uint32_t len)


A2DP sink data callback function.
Param buf [in] : pointer to the data received from A2DP source device and is PCM format de-
coded from SBC decoder; buf references to a static memory block and can be overwritten by
upcoming data
Param len [in] : size(in bytes) in buf

typedef int32_t (*esp_a2d_source_data_cb_t)(uint8_t *buf, int32_t len)


A2DP source data read callback function.
Param buf [in] : buffer to be filled with PCM data stream from higher layer
Param len [in] : size(in bytes) of data block to be copied to buf. -1 is an indication to user that
data buffer shall be flushed
Return size of bytes read successfully, if the argument len is -1, this value is ignored.

Enumerations

enum esp_a2d_connection_state_t
Bluetooth A2DP connection states.
Values:

enumerator ESP_A2D_CONNECTION_STATE_DISCONNECTED
connection released

enumerator ESP_A2D_CONNECTION_STATE_CONNECTING
connecting remote device

enumerator ESP_A2D_CONNECTION_STATE_CONNECTED
connection established

enumerator ESP_A2D_CONNECTION_STATE_DISCONNECTING
disconnecting remote device

Espressif Systems 414 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enum esp_a2d_disc_rsn_t
Bluetooth A2DP disconnection reason.
Values:

enumerator ESP_A2D_DISC_RSN_NORMAL
Finished disconnection that is initiated by local or remote device

enumerator ESP_A2D_DISC_RSN_ABNORMAL
Abnormal disconnection caused by signal loss

enum esp_a2d_audio_state_t
Bluetooth A2DP datapath states.
Values:

enumerator ESP_A2D_AUDIO_STATE_SUSPEND
audio stream datapath suspended by remote device

enumerator ESP_A2D_AUDIO_STATE_STARTED
audio stream datapath started

enumerator ESP_A2D_AUDIO_STATE_STOPPED

Note: Deprecated

enumerator ESP_A2D_AUDIO_STATE_REMOTE_SUSPEND

Note: Deprecated

enum esp_a2d_media_ctrl_ack_t
A2DP media control command acknowledgement code.
Values:

enumerator ESP_A2D_MEDIA_CTRL_ACK_SUCCESS
media control command is acknowledged with success

enumerator ESP_A2D_MEDIA_CTRL_ACK_FAILURE
media control command is acknowledged with failure

enumerator ESP_A2D_MEDIA_CTRL_ACK_BUSY
media control command is rejected, as previous command is not yet acknowledged

enum esp_a2d_media_ctrl_t
A2DP media control commands.
Values:

Espressif Systems 415 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_A2D_MEDIA_CTRL_NONE
Not for application use, use inside stack only.

enumerator ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY
check whether AVDTP is connected, only used in A2DP source

enumerator ESP_A2D_MEDIA_CTRL_START
command to set up media transmission channel

enumerator ESP_A2D_MEDIA_CTRL_SUSPEND
command to suspend media transmission

enumerator ESP_A2D_MEDIA_CTRL_STOP

Note: Deprecated, Please use ESP_A2D_MEDIA_CTRL_SUSPEND

enum esp_a2d_init_state_t
Bluetooth A2DP Initiation states.
Values:

enumerator ESP_A2D_DEINIT_SUCCESS
A2DP profile deinit successful event

enumerator ESP_A2D_INIT_SUCCESS
A2DP profile deinit successful event

enum esp_a2d_set_delay_value_state_t
Bluetooth A2DP set delay report value states.
Values:

enumerator ESP_A2D_SET_SUCCESS
A2DP profile set delay report value successful

enumerator ESP_A2D_SET_INVALID_PARAMS
A2DP profile set delay report value is invalid parameter

enum esp_a2d_cb_event_t
A2DP callback events.
Values:

enumerator ESP_A2D_CONNECTION_STATE_EVT
connection state changed event

enumerator ESP_A2D_AUDIO_STATE_EVT
audio stream transmission state changed event

Espressif Systems 416 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_A2D_AUDIO_CFG_EVT
audio codec is configured, only used for A2DP SINK

enumerator ESP_A2D_MEDIA_CTRL_ACK_EVT
acknowledge event in response to media control commands

enumerator ESP_A2D_PROF_STATE_EVT
indicate a2dp init&deinit complete

enumerator ESP_A2D_SNK_PSC_CFG_EVT
protocol service capabilities configured,only used for A2DP SINK

enumerator ESP_A2D_SNK_SET_DELAY_VALUE_EVT
indicate a2dp sink set delay report value complete, only used for A2DP SINK

enumerator ESP_A2D_SNK_GET_DELAY_VALUE_EVT
indicate a2dp sink get delay report value complete, only used for A2DP SINK

enumerator ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT
report delay value, only used for A2DP SRC

Bluetooth® AVRCP APIs

Overview Bluetooth AVRCP reference APIs.

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_avrc_api.h

Functions
esp_err_t esp_avrc_ct_register_callback(esp_avrc_ct_cb_t callback)
Register application callbacks to AVRCP module. This function should be called after esp_bluedroid_enable()
completes successfully.
Parameters callback –[in] AVRCP controller callback function
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_avrc_ct_init(void)
Initialize the bluetooth AVRCP controller module, This function should be called after esp_bluedroid_enable()
completes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP
and AVRC should be initialized before A2DP.
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others

Espressif Systems 417 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_avrc_ct_deinit(void)
De-initialize AVRCP controller module. This function should be called after after esp_bluedroid_enable()
completes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP
and AVRC should be deinitialized before A2DP.
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_avrc_ct_send_set_player_value_cmd(uint8_t tl, uint8_t attr_id, uint8_t value_id)
Send player application settings command to AVRCP target. This function should be called after
ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established.
Parameters
• tl –[in] : transaction label, 0 to 15, consecutive commands should use different values
• attr_id –[in] : player application setting attribute IDs from one of
esp_avrc_ps_attr_ids_t
• value_id –[in] : attribute value defined for the specific player application setting at-
tribute
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_avrc_ct_send_get_rn_capabilities_cmd(uint8_t tl)
Send GetCapabilities PDU to AVRCP target to retrieve remote device’s supported notification event_ids.
This function should be called after ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP
connection is established.
Parameters tl –[in] : transaction label, 0 to 15, consecutive commands should use different
values
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_avrc_ct_send_register_notification_cmd(uint8_t tl, uint8_t event_id, uint32_t
event_parameter)
Send register notification command to AVRCP target. This function should be called after
ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established.
Parameters
• tl –[in] : transaction label, 0 to 15, consecutive commands should use different values.
• event_id –[in] : id of events, e.g. ESP_AVRC_RN_PLAY_STATUS_CHANGE,
ESP_AVRC_RN_TRACK_CHANGE, etc.
• event_parameter –[in] : playback interval for
ESP_AVRC_RN_PLAY_POS_CHANGED; For other events , value of this parameter
is ignored.
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_ERR_NOT_SUPPORTED: if the event_id is not supported in current implementa-
tion
• ESP_FAIL: others
esp_err_t esp_avrc_ct_send_set_absolute_volume_cmd(uint8_t tl, uint8_t volume)
Send set absolute volume command to AVRCP target. This function should be called after
ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established.
Parameters

Espressif Systems 418 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• tl –[in] : transaction label, 0 to 15, consecutive commands should use different values
• volume –[in] : volume, 0 to 0x7f, means 0% to 100%
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_ERR_NOT_SUPPORTED: if the event_id is not supported in current implementa-
tion
• ESP_FAIL: others
esp_err_t esp_avrc_ct_send_metadata_cmd(uint8_t tl, uint8_t attr_mask)
Send metadata command to AVRCP target. This function should be called after
ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established.
Parameters
• tl –[in] : transaction label, 0 to 15, consecutive commands should use different values.
• attr_mask –[in] : mask of attributes, e.g. ESP_AVRC_MD_ATTR_ID_TITLE |
ESP_AVRC_MD_ATTR_ID_ARTIST.
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_avrc_ct_send_passthrough_cmd(uint8_t tl, uint8_t key_code, uint8_t key_state)
Send passthrough command to AVRCP target. This function should be called after
ESP_AVRC_CT_CONNECTION_STATE_EVT is received and AVRCP connection is established.
Parameters
• tl –[in] : transaction label, 0 to 15, consecutive commands should use different values.
• key_code –[in] : passthrough command code, e.g. ESP_AVRC_PT_CMD_PLAY,
ESP_AVRC_PT_CMD_STOP, etc.
• key_state –[in] : passthrough command key
state, ESP_AVRC_PT_CMD_STATE_PRESSED or
ESP_AVRC_PT_CMD_STATE_RELEASED
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_avrc_tg_register_callback(esp_avrc_tg_cb_t callback)
Register application callbacks to AVRCP target module. This function should be called after
esp_bluedroid_enable() completes successfully.
Parameters callback –[in] AVRCP target callback function
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_avrc_tg_init(void)
Initialize the bluetooth AVRCP target module, This function should be called after esp_bluedroid_enable()
completes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP
and AVRC should be initialized before A2DP.
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_avrc_tg_deinit(void)
De-initialize AVRCP target module. This function should be called after after esp_bluedroid_enable() com-
pletes successfully. Note: AVRC cannot work independently, AVRC should be used along with A2DP and
AVRC should be deinitialized before A2DP.

Espressif Systems 419 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_avrc_tg_get_psth_cmd_filter(esp_avrc_psth_filter_t filter, esp_avrc_psth_bit_mask_t
*cmd_set)
Get the current filter of remote passthrough commands on AVRC target. Filter is given by filter type
and bit mask for the passthrough commands. This function should be called after esp_avrc_tg_init().
For filter type ESP_AVRC_PSTH_FILTER_ALLOWED_CMD, the retrieved command set is constant
and it covers all of the passthrough commands that can possibly be supported. For filter type
ESP_AVRC_PSTH_FILTER_SUPPORT_COMMANDS, the retrieved command set covers the passthrough
commands selected to be supported according to current configuration. The configuration can be changed
using esp_avrc_tg_set_psth_cmd_filter().
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not ini-
tialized
• ESP_ERR_INVALID_ARG: if filter type is invalid or cmd_set is NULL
• ESP_FAIL: otherwise
esp_err_t esp_avrc_tg_set_psth_cmd_filter(esp_avrc_psth_filter_t filter, const
esp_avrc_psth_bit_mask_t *cmd_set)
Set the filter of remote passthrough commands on AVRC target. Filter is given by filter type and bit mask for
the passthrough commands. This function should be called after esp_avrc_tg_init().
If filter type is ESP_AVRC_PSTH_FILTER_SUPPORT_CMD, the passthrough commands which are
set “1”as given in cmd_set will generate ESP_AVRC_CT_PASSTHROUGH_RSP_EVT callback event
and are auto-accepted in the protocol stack, other commands are replied with response type “NOT
IMPLEMENTED”(8). The set of supported commands should be a subset of allowed command
set. The allowed command set can be retrieved using esp_avrc_tg_get_psth_cmd_filter() with filter type
“ESP_AVRC_PSTH_FILTER_ALLOWED_CMD”.
Filter type “ESP_AVRC_PSTH_FILTER_ALLOWED_CMD”does not apply to this function.
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled
• ESP_ERR_INVALID_ARG: if filter type is invalid or cmd_set is NULL
• ESP_ERR_NOT_SUPPORTED:: if filter type is
ESP_AVRC_PSTH_FILTER_ALLOWED_CMD, or cmd_set includes commands
that are not allowed
bool esp_avrc_psth_bit_mask_operation(esp_avrc_bit_mask_op_t op, esp_avrc_psth_bit_mask_t
*psth, esp_avrc_pt_cmd_t cmd)
Operate on the type esp_avrc_psth_bit_mask_t with regard to a specific PASSTHROUGH command.
Parameters
• op –[in] operation requested on the bit mask field
• psth –[in] pointer to passthrough command bit mask structure
• cmd –[in] passthrough command code
Returns For operation ESP_AVRC_BIT_MASK_OP_SET or
ESP_AVRC_BIT_MASK_OP_CLEAR, return true for a successful operation, other-
wise return false. For operation ESP_AVRC_BIT_MASK_OP_TEST, return true if the
corresponding bit is set, otherwise false.
esp_err_t esp_avrc_tg_get_rn_evt_cap(esp_avrc_rn_evt_cap_t cap, esp_avrc_rn_evt_cap_mask_t
*evt_set)
Get the requested event notification capabilies on local AVRC target. The capability is returned in a bit mask
representation in evt_set. This function should be called after esp_avrc_tg_init().

Espressif Systems 420 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

For capability type “ESP_AVRC_RN_CAP_ALLOWED_EVT, the retrieved event set is constant and it
covers all of the notifcation events that can possibly be supported with current implementation.
For capability type ESP_AVRC_RN_CAP_SUPPORTED_EVT, the event set covers the notification
events selected to be supported under current configuration, The configuration can be changed using
esp_avrc_tg_set_rn_evt_cap().
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not ini-
tialized
• ESP_ERR_INVALID_ARG: if cap is invalid or evt_set is NULL
• ESP_FAIL: otherwise
esp_err_t esp_avrc_tg_set_rn_evt_cap(const esp_avrc_rn_evt_cap_mask_t *evt_set)
Set the event notification capabilities on local AVRCP target. The capability is given in a bit mask representation
in evt_set and must be a subset of allowed event IDs with current implementation. This function should be
called after esp_avrc_tg_init().
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled
• ESP_ERR_INVALID_ARG: if evt_set is NULL
bool esp_avrc_rn_evt_bit_mask_operation(esp_avrc_bit_mask_op_t op,
esp_avrc_rn_evt_cap_mask_t *events,
esp_avrc_rn_event_ids_t event_id)
Operate on the type esp_avrc_rn_evt_cap_mask_t with regard to a specific event.

For operation ESP_AVRC_BIT_MASK_OP_TEST, return true if the corresponding bit is set, otherwise false.
Parameters
• op –[in] operation requested on the bit mask field
• events –[in] pointer to event notification capability bit mask structure
• event_id –[in] notification event code
Returns For operation ESP_AVRC_BIT_MASK_OP_SET or
ESP_AVRC_BIT_MASK_OP_CLEAR, return true for a successful operation, other-
wise return false.
esp_err_t esp_avrc_tg_send_rn_rsp(esp_avrc_rn_event_ids_t event_id, esp_avrc_rn_rsp_t rsp,
esp_avrc_rn_param_t *param)
Send RegisterNotification Response to remote AVRCP controller. Local event notification capability can be
set using esp_avrc_tg_set_rn_evt_cap(), in a bit mask representation in evt_set. This function should be called
after esp_avrc_tg_init().
Parameters
• event_id –[in] notification event ID that remote AVRCP CT registers
• rsp –[in] notification response code
• param –[in] parameters included in the specific notification
Returns
• ESP_OK: success
• ESP_ERR_INVALID_STATE: if bluetooth stack is not enabled or AVRC TG is not ini-
tialized
• ESP_ERR_INVALID_ARG: if evt_set is NULL

Unions

union esp_avrc_rn_param_t
#include <esp_avrc_api.h> AVRCP notification parameters.

Espressif Systems 421 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

uint8_t volume
response data for ESP_AVRC_RN_VOLUME_CHANGE, ranges 0..127

esp_avrc_playback_stat_t playback
response data for ESP_AVRC_RN_PLAY_STATUS_CHANGE

uint8_t elm_id[8]
response data for ESP_AVRC_RN_TRACK_CHANGE

uint32_t play_pos
response data for ESP_AVRC_RN_PLAY_POS_CHANGED, in millisecond

esp_avrc_batt_stat_t batt
response data for ESP_AVRC_RN_BATTERY_STATUS_CHANGE

union esp_avrc_ct_cb_param_t
#include <esp_avrc_api.h> AVRC controller callback parameters.

Public Members

struct esp_avrc_ct_cb_param_t::avrc_ct_conn_stat_param conn_stat


AVRC connection status

struct esp_avrc_ct_cb_param_t::avrc_ct_psth_rsp_param psth_rsp


passthrough command response

struct esp_avrc_ct_cb_param_t::avrc_ct_meta_rsp_param meta_rsp


metadata attributes response

struct esp_avrc_ct_cb_param_t::avrc_ct_change_notify_param change_ntf


notifications

struct esp_avrc_ct_cb_param_t::avrc_ct_rmt_feats_param rmt_feats


AVRC features discovered from remote SDP server

struct esp_avrc_ct_cb_param_t::avrc_ct_get_rn_caps_rsp_param get_rn_caps_rsp


get supported event capabilities response from AVRCP target

struct esp_avrc_ct_cb_param_t::avrc_ct_set_volume_rsp_param set_volume_rsp


set absolute volume response event

struct avrc_ct_change_notify_param
#include <esp_avrc_api.h> ESP_AVRC_CT_CHANGE_NOTIFY_EVT.

Espressif Systems 422 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

uint8_t event_id
id of AVRC event notification

esp_avrc_rn_param_t event_parameter
event notification parameter

struct avrc_ct_conn_stat_param
#include <esp_avrc_api.h> ESP_AVRC_CT_CONNECTION_STATE_EVT.

Public Members

bool connected
whether AVRC connection is set up

esp_bd_addr_t remote_bda
remote bluetooth device address

struct avrc_ct_get_rn_caps_rsp_param
#include <esp_avrc_api.h> ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT.

Public Members

uint8_t cap_count
number of items provided in event or company_id according to cap_id used

esp_avrc_rn_evt_cap_mask_t evt_set
supported event_ids represented in bit-mask

struct avrc_ct_meta_rsp_param
#include <esp_avrc_api.h> ESP_AVRC_CT_METADATA_RSP_EVT.

Public Members

uint8_t attr_id
id of metadata attribute

uint8_t *attr_text
attribute itself

int attr_length
attribute character length

struct avrc_ct_psth_rsp_param
#include <esp_avrc_api.h> ESP_AVRC_CT_PASSTHROUGH_RSP_EVT.

Espressif Systems 423 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

uint8_t tl
transaction label, 0 to 15

uint8_t key_code
passthrough command code

uint8_t key_state
0 for PRESSED, 1 for RELEASED

esp_avrc_rsp_t rsp_code
response code

struct avrc_ct_rmt_feats_param
#include <esp_avrc_api.h> ESP_AVRC_CT_REMOTE_FEATURES_EVT.

Public Members

uint32_t feat_mask
AVRC feature mask of remote device

uint16_t tg_feat_flag
feature flag of remote device as TG

esp_bd_addr_t remote_bda
remote bluetooth device address

struct avrc_ct_set_volume_rsp_param
#include <esp_avrc_api.h> ESP_AVRC_CT_SET_ABSOLUTE_VOLUME_RSP_EVT.

Public Members

uint8_t volume
the volume which has actually been set, range is 0 to 0x7f, means 0% to 100%

union esp_avrc_tg_cb_param_t
#include <esp_avrc_api.h> AVRC target callback parameters.

Public Members

struct esp_avrc_tg_cb_param_t::avrc_tg_conn_stat_param conn_stat


AVRC connection status

struct esp_avrc_tg_cb_param_t::avrc_tg_rmt_feats_param rmt_feats


AVRC features discovered through SDP

Espressif Systems 424 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_avrc_tg_cb_param_t::avrc_tg_psth_cmd_param psth_cmd


passthrough command

struct esp_avrc_tg_cb_param_t::avrc_tg_set_abs_vol_param set_abs_vol


set absolute volume command targeted on audio sink

struct esp_avrc_tg_cb_param_t::avrc_tg_reg_ntf_param reg_ntf


register notification

struct esp_avrc_tg_cb_param_t::avrc_tg_set_app_value_param set_app_value


set player application value

struct avrc_tg_conn_stat_param
#include <esp_avrc_api.h> ESP_AVRC_TG_CONNECTION_STATE_EVT.

Public Members

bool connected
whether AVRC connection is set up

esp_bd_addr_t remote_bda
remote bluetooth device address

struct avrc_tg_psth_cmd_param
#include <esp_avrc_api.h> ESP_AVRC_TG_PASSTHROUGH_CMD_EVT.

Public Members

uint8_t key_code
passthrough command code

uint8_t key_state
0 for PRESSED, 1 for RELEASED

struct avrc_tg_reg_ntf_param
#include <esp_avrc_api.h> ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT.

Public Members

uint8_t event_id
event id of AVRC RegisterNotification

uint32_t event_parameter
event notification parameter

struct avrc_tg_rmt_feats_param
#include <esp_avrc_api.h> ESP_AVRC_TG_REMOTE_FEATURES_EVT.

Espressif Systems 425 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

uint32_t feat_mask
AVRC feature mask of remote device

uint16_t ct_feat_flag
feature flag of remote device as CT

esp_bd_addr_t remote_bda
remote bluetooth device address

struct avrc_tg_set_abs_vol_param
#include <esp_avrc_api.h> ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT.

Public Members

uint8_t volume
volume ranges from 0 to 127

struct avrc_tg_set_app_value_param
#include <esp_avrc_api.h> ESP_AVRC_TG_SET_PLAYER_APP_VALUE_EVT.

Public Members

uint8_t num_val
attribute num

esp_avrc_set_app_value_param_t *p_vals
point to the id and value of player application attribute

Structures

struct esp_avrc_psth_bit_mask_t
AVRC passthrough command bit mask.

Public Members

uint16_t bits[8]
bit mask representation of PASSTHROUGH commands

struct esp_avrc_rn_evt_cap_mask_t
AVRC target notification event capability bit mask.

Public Members

Espressif Systems 426 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint16_t bits
bit mask representation of PASSTHROUGH commands

struct esp_avrc_set_app_value_param_t
AVRCP set app value parameters.

Public Members

uint8_t attr_id
player application attribute id

uint8_t attr_val
player application attribute value

Macros

ESP_AVRC_TRANS_LABEL_MAX
max transaction label

Type Definitions

typedef void (*esp_avrc_ct_cb_t)(esp_avrc_ct_cb_event_t event, esp_avrc_ct_cb_param_t *param)


AVRCP controller callback function type.
Param event : Event type
Param param : Pointer to callback parameter union

typedef void (*esp_avrc_tg_cb_t)(esp_avrc_tg_cb_event_t event, esp_avrc_tg_cb_param_t *param)


AVRCP target callback function type.
Param event : Event type
Param param : Pointer to callback parameter union

Enumerations

enum esp_avrc_features_t
AVRC feature bit mask.
Values:

enumerator ESP_AVRC_FEAT_RCTG
remote control target

enumerator ESP_AVRC_FEAT_RCCT
remote control controller

enumerator ESP_AVRC_FEAT_VENDOR
remote control vendor dependent commands

enumerator ESP_AVRC_FEAT_BROWSE
use browsing channel

Espressif Systems 427 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_AVRC_FEAT_META_DATA
remote control metadata transfer command/response

enumerator ESP_AVRC_FEAT_ADV_CTRL
remote control advanced control command/response

enum esp_avrc_feature_flag_t
AVRC supported features flag retrieved in SDP record.
Values:

enumerator ESP_AVRC_FEAT_FLAG_CAT1
category 1

enumerator ESP_AVRC_FEAT_FLAG_CAT2
category 2

enumerator ESP_AVRC_FEAT_FLAG_CAT3
category 3

enumerator ESP_AVRC_FEAT_FLAG_CAT4
category 4

enumerator ESP_AVRC_FEAT_FLAG_BROWSING
browsing

enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_IMAGE_PROP
Cover Art GetImageProperties

enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_IMAGE
Cover Art GetImage

enumerator ESP_AVRC_FEAT_FLAG_COVER_ART_GET_LINKED_THUMBNAIL
Cover Art GetLinkedThumbnail

enum esp_avrc_pt_cmd_t
AVRC passthrough command code.
Values:

enumerator ESP_AVRC_PT_CMD_SELECT
select

enumerator ESP_AVRC_PT_CMD_UP
up

enumerator ESP_AVRC_PT_CMD_DOWN
down

enumerator ESP_AVRC_PT_CMD_LEFT
left

Espressif Systems 428 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_AVRC_PT_CMD_RIGHT
right

enumerator ESP_AVRC_PT_CMD_RIGHT_UP
right-up

enumerator ESP_AVRC_PT_CMD_RIGHT_DOWN
right-down

enumerator ESP_AVRC_PT_CMD_LEFT_UP
left-up

enumerator ESP_AVRC_PT_CMD_LEFT_DOWN
left-down

enumerator ESP_AVRC_PT_CMD_ROOT_MENU
root menu

enumerator ESP_AVRC_PT_CMD_SETUP_MENU
setup menu

enumerator ESP_AVRC_PT_CMD_CONT_MENU
contents menu

enumerator ESP_AVRC_PT_CMD_FAV_MENU
favorite menu

enumerator ESP_AVRC_PT_CMD_EXIT
exit

enumerator ESP_AVRC_PT_CMD_0
0

enumerator ESP_AVRC_PT_CMD_1
1

enumerator ESP_AVRC_PT_CMD_2
2

enumerator ESP_AVRC_PT_CMD_3
3

enumerator ESP_AVRC_PT_CMD_4
4

enumerator ESP_AVRC_PT_CMD_5
5

Espressif Systems 429 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_AVRC_PT_CMD_6
6

enumerator ESP_AVRC_PT_CMD_7
7

enumerator ESP_AVRC_PT_CMD_8
8

enumerator ESP_AVRC_PT_CMD_9
9

enumerator ESP_AVRC_PT_CMD_DOT
dot

enumerator ESP_AVRC_PT_CMD_ENTER
enter

enumerator ESP_AVRC_PT_CMD_CLEAR
clear

enumerator ESP_AVRC_PT_CMD_CHAN_UP
channel up

enumerator ESP_AVRC_PT_CMD_CHAN_DOWN
channel down

enumerator ESP_AVRC_PT_CMD_PREV_CHAN
previous channel

enumerator ESP_AVRC_PT_CMD_SOUND_SEL
sound select

enumerator ESP_AVRC_PT_CMD_INPUT_SEL
input select

enumerator ESP_AVRC_PT_CMD_DISP_INFO
display information

enumerator ESP_AVRC_PT_CMD_HELP
help

enumerator ESP_AVRC_PT_CMD_PAGE_UP
page up

enumerator ESP_AVRC_PT_CMD_PAGE_DOWN
page down

Espressif Systems 430 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_AVRC_PT_CMD_POWER
power

enumerator ESP_AVRC_PT_CMD_VOL_UP
volume up

enumerator ESP_AVRC_PT_CMD_VOL_DOWN
volume down

enumerator ESP_AVRC_PT_CMD_MUTE
mute

enumerator ESP_AVRC_PT_CMD_PLAY
play

enumerator ESP_AVRC_PT_CMD_STOP
stop

enumerator ESP_AVRC_PT_CMD_PAUSE
pause

enumerator ESP_AVRC_PT_CMD_RECORD
record

enumerator ESP_AVRC_PT_CMD_REWIND
rewind

enumerator ESP_AVRC_PT_CMD_FAST_FORWARD
fast forward

enumerator ESP_AVRC_PT_CMD_EJECT
eject

enumerator ESP_AVRC_PT_CMD_FORWARD
forward

enumerator ESP_AVRC_PT_CMD_BACKWARD
backward

enumerator ESP_AVRC_PT_CMD_ANGLE
angle

enumerator ESP_AVRC_PT_CMD_SUBPICT
subpicture

enumerator ESP_AVRC_PT_CMD_F1
F1

Espressif Systems 431 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_AVRC_PT_CMD_F2
F2

enumerator ESP_AVRC_PT_CMD_F3
F3

enumerator ESP_AVRC_PT_CMD_F4
F4

enumerator ESP_AVRC_PT_CMD_F5
F5

enumerator ESP_AVRC_PT_CMD_VENDOR
vendor unique

enum esp_avrc_psth_filter_t
AVRC passthrough command filter.
Values:

enumerator ESP_AVRC_PSTH_FILTER_ALLOWED_CMD
all of the PASSTHROUGH commands that can possibly be used, immutable

enumerator ESP_AVRC_PSTH_FILTER_SUPPORTED_CMD
PASSTHROUGH commands selectively supported according to the current configuration

enumerator ESP_AVRC_PSTH_FILTER_SUPPORT_MAX

enum esp_avrc_bit_mask_op_t
Values:

enumerator ESP_AVRC_BIT_MASK_OP_TEST
operation code to test a specific bit

enumerator ESP_AVRC_BIT_MASK_OP_SET
operation code to set a specific bit

enumerator ESP_AVRC_BIT_MASK_OP_CLEAR
operation code to clear a specific bit

enum esp_avrc_pt_cmd_state_t
AVRC passthrough command state.
Values:

enumerator ESP_AVRC_PT_CMD_STATE_PRESSED
key pressed

enumerator ESP_AVRC_PT_CMD_STATE_RELEASED
key released

Espressif Systems 432 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enum esp_avrc_ct_cb_event_t
AVRC Controller callback events.
Values:

enumerator ESP_AVRC_CT_CONNECTION_STATE_EVT
connection state changed event

enumerator ESP_AVRC_CT_PASSTHROUGH_RSP_EVT
passthrough response event

enumerator ESP_AVRC_CT_METADATA_RSP_EVT
metadata response event

enumerator ESP_AVRC_CT_PLAY_STATUS_RSP_EVT
play status response event

enumerator ESP_AVRC_CT_CHANGE_NOTIFY_EVT
notification event

enumerator ESP_AVRC_CT_REMOTE_FEATURES_EVT
feature of remote device indication event

enumerator ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT
supported notification events capability of peer device

enumerator ESP_AVRC_CT_SET_ABSOLUTE_VOLUME_RSP_EVT
set absolute volume response event

enum esp_avrc_tg_cb_event_t
AVRC Target callback events.
Values:

enumerator ESP_AVRC_TG_CONNECTION_STATE_EVT
connection state changed event

enumerator ESP_AVRC_TG_REMOTE_FEATURES_EVT
feature of remote device indication event

enumerator ESP_AVRC_TG_PASSTHROUGH_CMD_EVT
passthrough command event

enumerator ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT
set absolute volume command from remote device

enumerator ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT
register notification event

Espressif Systems 433 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_AVRC_TG_SET_PLAYER_APP_VALUE_EVT
set application attribute value, attribute refer to esp_avrc_ps_attr_ids_t

enum esp_avrc_md_attr_mask_t
AVRC metadata attribute mask.
Values:

enumerator ESP_AVRC_MD_ATTR_TITLE
title of the playing track

enumerator ESP_AVRC_MD_ATTR_ARTIST
track artist

enumerator ESP_AVRC_MD_ATTR_ALBUM
album name

enumerator ESP_AVRC_MD_ATTR_TRACK_NUM
track position on the album

enumerator ESP_AVRC_MD_ATTR_NUM_TRACKS
number of tracks on the album

enumerator ESP_AVRC_MD_ATTR_GENRE
track genre

enumerator ESP_AVRC_MD_ATTR_PLAYING_TIME
total album playing time in miliseconds

enum esp_avrc_rn_event_ids_t
AVRC event notification ids.
Values:

enumerator ESP_AVRC_RN_PLAY_STATUS_CHANGE
track status change, eg. from playing to paused

enumerator ESP_AVRC_RN_TRACK_CHANGE
new track is loaded

enumerator ESP_AVRC_RN_TRACK_REACHED_END
current track reached end

enumerator ESP_AVRC_RN_TRACK_REACHED_START
current track reached start position

enumerator ESP_AVRC_RN_PLAY_POS_CHANGED
track playing position changed

Espressif Systems 434 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_AVRC_RN_BATTERY_STATUS_CHANGE
battery status changed

enumerator ESP_AVRC_RN_SYSTEM_STATUS_CHANGE
system status changed

enumerator ESP_AVRC_RN_APP_SETTING_CHANGE
application settings changed

enumerator ESP_AVRC_RN_NOW_PLAYING_CHANGE
now playing content changed

enumerator ESP_AVRC_RN_AVAILABLE_PLAYERS_CHANGE
available players changed

enumerator ESP_AVRC_RN_ADDRESSED_PLAYER_CHANGE
the addressed player changed

enumerator ESP_AVRC_RN_UIDS_CHANGE
UIDs changed

enumerator ESP_AVRC_RN_VOLUME_CHANGE
volume changed locally on TG

enumerator ESP_AVRC_RN_MAX_EVT

enum esp_avrc_rn_evt_cap_t
AVRC target notification event notification capability.
Values:

enumerator ESP_AVRC_RN_CAP_ALLOWED_EVT
all of the notification events that can possibly be supported, immutable

enumerator ESP_AVRC_RN_CAP_SUPPORTED_EVT
notification events selectively supported according to the current configuration

enumerator ESP_AVRC_RN_CAP_MAX

enum esp_avrc_rn_rsp_t
AVRC notification response type.
Values:

enumerator ESP_AVRC_RN_RSP_INTERIM
initial response to RegisterNotification, should be sent T_mtp(1000ms) from receiving the command

enumerator ESP_AVRC_RN_RSP_CHANGED
final response to RegisterNotification command

Espressif Systems 435 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enum esp_avrc_ps_attr_ids_t
AVRC player setting ids.
Values:

enumerator ESP_AVRC_PS_EQUALIZER
equalizer, on or off

enumerator ESP_AVRC_PS_REPEAT_MODE
repeat mode

enumerator ESP_AVRC_PS_SHUFFLE_MODE
shuffle mode

enumerator ESP_AVRC_PS_SCAN_MODE
scan mode on or off

enumerator ESP_AVRC_PS_MAX_ATTR

enum esp_avrc_ps_eq_value_ids_t
AVRC equalizer modes.
Values:

enumerator ESP_AVRC_PS_EQUALIZER_OFF
equalizer OFF

enumerator ESP_AVRC_PS_EQUALIZER_ON
equalizer ON

enum esp_avrc_ps_rpt_value_ids_t
AVRC repeat modes.
Values:

enumerator ESP_AVRC_PS_REPEAT_OFF
repeat mode off

enumerator ESP_AVRC_PS_REPEAT_SINGLE
single track repeat

enumerator ESP_AVRC_PS_REPEAT_GROUP
group repeat

enum esp_avrc_ps_shf_value_ids_t
AVRC shuffle modes.
Values:

enumerator ESP_AVRC_PS_SHUFFLE_OFF

Espressif Systems 436 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_AVRC_PS_SHUFFLE_ALL

enumerator ESP_AVRC_PS_SHUFFLE_GROUP

enum esp_avrc_ps_scn_value_ids_t
AVRC scan modes.
Values:

enumerator ESP_AVRC_PS_SCAN_OFF
scan off

enumerator ESP_AVRC_PS_SCAN_ALL
all tracks scan

enumerator ESP_AVRC_PS_SCAN_GROUP
group scan

enum esp_avrc_rsp_t
AVCTP response codes.
Values:

enumerator ESP_AVRC_RSP_NOT_IMPL
not implemented

enumerator ESP_AVRC_RSP_ACCEPT
accept

enumerator ESP_AVRC_RSP_REJECT
reject

enumerator ESP_AVRC_RSP_IN_TRANS
in transition

enumerator ESP_AVRC_RSP_IMPL_STBL
implemented/stable

enumerator ESP_AVRC_RSP_CHANGED
changed

enumerator ESP_AVRC_RSP_INTERIM
interim

enum esp_avrc_batt_stat_t
AVRCP battery status.
Values:

enumerator ESP_AVRC_BATT_NORMAL
normal state

Espressif Systems 437 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_AVRC_BATT_WARNING
unable to operate soon

enumerator ESP_AVRC_BATT_CRITICAL
cannot operate any more

enumerator ESP_AVRC_BATT_EXTERNAL
plugged to external power supply

enumerator ESP_AVRC_BATT_FULL_CHARGE
when completely charged from external power supply

enum esp_avrc_playback_stat_t
AVRCP current status of playback.
Values:

enumerator ESP_AVRC_PLAYBACK_STOPPED
stopped

enumerator ESP_AVRC_PLAYBACK_PLAYING
playing

enumerator ESP_AVRC_PLAYBACK_PAUSED
paused

enumerator ESP_AVRC_PLAYBACK_FWD_SEEK
forward seek

enumerator ESP_AVRC_PLAYBACK_REV_SEEK
reverse seek

enumerator ESP_AVRC_PLAYBACK_ERROR
error

SPP API

Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the fol-
lowing application:
• This is a SPP demo. This demo can discover the service, connect, send and recive SPP data blue-
tooth/bluedroid/classic_bt/bt_spp_acceptor, bluetooth/bluedroid/classic_bt/bt_spp_initiator

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_spp_api.h

Espressif Systems 438 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Functions
esp_err_t esp_spp_register_callback(esp_spp_cb_t callback)
This function is called to init callbacks with SPP module.
Parameters callback –[in] pointer to the init callback function.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_init(esp_spp_mode_t mode)
This function is called to init SPP module. When the operation is completed, the callback function will be called
with ESP_SPP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes success-
fully.
Parameters mode –[in] Choose the mode of SPP, ESP_SPP_MODE_CB or
ESP_SPP_MODE_VFS.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_enhanced_init(const esp_spp_cfg_t *cfg)
This function is called to init SPP module. When the operation is completed, the callback function will be called
with ESP_SPP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes success-
fully.

Note: The member variable enable_l2cap_etrm in esp_spp_cfg_t can affect all L2CAP channel configurations
of the upper layer RFCOMM protocol.

Parameters cfg –[in] SPP configuration.


Returns
• ESP_OK: success
• other: failed

esp_err_t esp_spp_deinit(void)
This function is called to uninit SPP module. The operation will close all active SPP connection first, then the
callback function will be called with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT
is equal to the number of connection. When the operation is completed, the callback function will be called
with ESP_SPP_UNINIT_EVT. This function should be called after esp_spp_init()/esp_spp_enhanced_init()
completes successfully.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_start_discovery(esp_bd_addr_t bd_addr)
This function is called to performs service discovery for the services provided by the given peer device. When
the operation is completed, the callback function will be called with ESP_SPP_DISCOVERY_COMP_EVT.
This function must be called after esp_spp_init()/esp_spp_enhanced_init() successful and before
esp_spp_deinit().
Parameters bd_addr –[in] Remote device bluetooth device address.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_connect(esp_spp_sec_t sec_mask, esp_spp_role_t role, uint8_t remote_scn,
esp_bd_addr_t peer_bd_addr)
This function makes an SPP connection to a remote BD Address. When the connection is initiated or

Espressif Systems 439 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

failed to initiate, the callback is called with ESP_SPP_CL_INIT_EVT. When the connection is estab-
lished or failed, the callback is called with ESP_SPP_OPEN_EVT. This function must be called after
esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit().
Parameters
• sec_mask –[in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE,
ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only.
• role –[in] Master or slave.
• remote_scn –[in] Remote device bluetooth device SCN.
• peer_bd_addr –[in] Remote device bluetooth device address.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_disconnect(uint32_t handle)
This function closes an SPP connection. When the operation is completed, the callback function will be called
with ESP_SPP_CLOSE_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() suc-
cessful and before esp_spp_deinit().
Parameters handle –[in] The connection handle.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_start_srv(esp_spp_sec_t sec_mask, esp_spp_role_t role, uint8_t local_scn, const char
*name)
This function create a SPP server and starts listening for an SPP connection request from a remote Bluetooth
device. When the server is started successfully, the callback is called with ESP_SPP_START_EVT. When
the connection is established, the callback is called with ESP_SPP_SRV_OPEN_EVT. This function must be
called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit().
Parameters
• sec_mask –[in] Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE,
ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only.
• role –[in] Master or slave.
• local_scn –[in] The specific channel you want to get. If channel is 0, means get any
channel.
• name –[in] Server’s name.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_stop_srv(void)
This function stops all SPP servers. The operation will close all active SPP connection first, then the call-
back function will be called with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT
is equal to the number of connection. When the operation is completed, the callback is called with
ESP_SPP_SRV_STOP_EVT. This function must be called after esp_spp_init()/esp_spp_enhanced_init() suc-
cessful and before esp_spp_deinit().
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_stop_srv_scn(uint8_t scn)
This function stops a specific SPP server. The operation will close all active SPP connection first on
the specific SPP server, then the callback function will be called with ESP_SPP_CLOSE_EVT, and
the number of ESP_SPP_CLOSE_EVT is equal to the number of connection. When the operation is
completed, the callback is called with ESP_SPP_SRV_STOP_EVT. This function must be called after
esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit().
Parameters scn –[in] Server channel number.
Returns

Espressif Systems 440 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• ESP_OK: success
• other: failed
esp_err_t esp_spp_write(uint32_t handle, int len, uint8_t *p_data)
This function is used to write data, only for ESP_SPP_MODE_CB. When this function need to
be called repeatedly, it is strongly recommended to call this function again after the previous event
ESP_SPP_WRITE_EVT is received and the parameter ‘cong’is equal to false. If the previous event
ESP_SPP_WRITE_EVT with parameter ‘cong’is equal to true, the function can only be called again when
the event ESP_SPP_CONG_EVT with parameter ‘cong’equal to false is received. This function must be
called after an connection between initiator and acceptor has been established.
Parameters
• handle –[in] The connection handle.
• len –[in] The length of the data written.
• p_data –[in] The data written.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_vfs_register(void)
This function is used to register VFS. For now, SPP only supports write, read and close. When the operation
is completed, the callback function will be called with ESP_SPP_VFS_REGISTER_EVT. This function must
be called after esp_spp_init()/esp_spp_enhanced_init() successful and before esp_spp_deinit().
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_spp_vfs_unregister(void)
This function is used to unregister VFS. When the operation is completed, the callback function will be called
with ESP_SPP_VFS_UNREGISTER_EVT. This function must be called after esp_spp_vfs_register() suc-
cessful and before esp_spp_deinit().
Returns
• ESP_OK: success
• other: failed

Unions

union esp_spp_cb_param_t
#include <esp_spp_api.h> SPP callback parameters union.

Public Members

struct esp_spp_cb_param_t::spp_init_evt_param init


SPP callback param of SPP_INIT_EVT

struct esp_spp_cb_param_t::spp_uninit_evt_param uninit


SPP callback param of SPP_UNINIT_EVT

struct esp_spp_cb_param_t::spp_discovery_comp_evt_param disc_comp


SPP callback param of SPP_DISCOVERY_COMP_EVT

struct esp_spp_cb_param_t::spp_open_evt_param open


SPP callback param of ESP_SPP_OPEN_EVT

Espressif Systems 441 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_spp_cb_param_t::spp_srv_open_evt_param srv_open


SPP callback param of ESP_SPP_SRV_OPEN_EVT

struct esp_spp_cb_param_t::spp_close_evt_param close


SPP callback param of ESP_SPP_CLOSE_EVT

struct esp_spp_cb_param_t::spp_start_evt_param start


SPP callback param of ESP_SPP_START_EVT

struct esp_spp_cb_param_t::spp_srv_stop_evt_param srv_stop


SPP callback param of ESP_SPP_SRV_STOP_EVT

struct esp_spp_cb_param_t::spp_cl_init_evt_param cl_init


SPP callback param of ESP_SPP_CL_INIT_EVT

struct esp_spp_cb_param_t::spp_write_evt_param write


SPP callback param of ESP_SPP_WRITE_EVT

struct esp_spp_cb_param_t::spp_data_ind_evt_param data_ind


SPP callback param of ESP_SPP_DATA_IND_EVT

struct esp_spp_cb_param_t::spp_cong_evt_param cong


SPP callback param of ESP_SPP_CONG_EVT

struct esp_spp_cb_param_t::spp_vfs_register_evt_param vfs_register


SPP callback param of ESP_SPP_VFS_REGISTER_EVT

struct esp_spp_cb_param_t::spp_vfs_unregister_evt_param vfs_unregister


SPP callback param of ESP_SPP_VFS_UNREGISTER_EVT

struct spp_cl_init_evt_param
#include <esp_spp_api.h> ESP_SPP_CL_INIT_EVT.

Public Members

esp_spp_status_t status
status

uint32_t handle
The connection handle

uint8_t sec_id
security ID used by this server

bool use_co
TRUE to use co_rfc_data

struct spp_close_evt_param
#include <esp_spp_api.h> ESP_SPP_CLOSE_EVT.

Espressif Systems 442 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_spp_status_t status
status

uint32_t port_status
PORT status

uint32_t handle
The connection handle

bool async
FALSE, if local initiates disconnect

struct spp_cong_evt_param
#include <esp_spp_api.h> ESP_SPP_CONG_EVT.

Public Members

esp_spp_status_t status
status

uint32_t handle
The connection handle

bool cong
TRUE, congested. FALSE, uncongested

struct spp_data_ind_evt_param
#include <esp_spp_api.h> ESP_SPP_DATA_IND_EVT.

Public Members

esp_spp_status_t status
status

uint32_t handle
The connection handle

uint16_t len
The length of data

uint8_t *data
The data received

struct spp_discovery_comp_evt_param
#include <esp_spp_api.h> SPP_DISCOVERY_COMP_EVT.

Espressif Systems 443 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_spp_status_t status
status

uint8_t scn_num
The num of scn_num

uint8_t scn[ESP_SPP_MAX_SCN]
channel #

const char *service_name[ESP_SPP_MAX_SCN]


service_name

struct spp_init_evt_param
#include <esp_spp_api.h> SPP_INIT_EVT.

Public Members

esp_spp_status_t status
status

struct spp_open_evt_param
#include <esp_spp_api.h> ESP_SPP_OPEN_EVT.

Public Members

esp_spp_status_t status
status

uint32_t handle
The connection handle

int fd
The file descriptor only for ESP_SPP_MODE_VFS

esp_bd_addr_t rem_bda
The peer address

struct spp_srv_open_evt_param
#include <esp_spp_api.h> ESP_SPP_SRV_OPEN_EVT.

Public Members

esp_spp_status_t status
status

Espressif Systems 444 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint32_t handle
The connection handle

uint32_t new_listen_handle
The new listen handle

int fd
The file descriptor only for ESP_SPP_MODE_VFS

esp_bd_addr_t rem_bda
The peer address

struct spp_srv_stop_evt_param
#include <esp_spp_api.h> ESP_SPP_SRV_STOP_EVT.

Public Members

esp_spp_status_t status
status

uint8_t scn
Server channel number

struct spp_start_evt_param
#include <esp_spp_api.h> ESP_SPP_START_EVT.

Public Members

esp_spp_status_t status
status

uint32_t handle
The connection handle

uint8_t sec_id
security ID used by this server

uint8_t scn
Server channel number

bool use_co
TRUE to use co_rfc_data

struct spp_uninit_evt_param
#include <esp_spp_api.h> SPP_UNINIT_EVT.

Espressif Systems 445 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_spp_status_t status
status

struct spp_vfs_register_evt_param
#include <esp_spp_api.h> ESP_SPP_VFS_REGISTER_EVT.

Public Members

esp_spp_status_t status
status

struct spp_vfs_unregister_evt_param
#include <esp_spp_api.h> ESP_SPP_VFS_UNREGISTER_EVT.

Public Members

esp_spp_status_t status
status

struct spp_write_evt_param
#include <esp_spp_api.h> ESP_SPP_WRITE_EVT.

Public Members

esp_spp_status_t status
status

uint32_t handle
The connection handle

int len
The length of the data written.

bool cong
congestion status

Structures

struct esp_spp_cfg_t
SPP configuration parameters.

Espressif Systems 446 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_spp_mode_t mode
Choose the mode of SPP, ESP_SPP_MODE_CB or ESP_SPP_MODE_VFS.

bool enable_l2cap_ertm
Enable/disable Logical Link Control and Adaptation Layer Protocol enhanced retransmission mode.

uint16_t tx_buffer_size
Tx buffer size for a new SPP channel. A smaller setting can save memory, but may incur a decrease in
throughput. Only for ESP_SPP_MODE_VFS mode.

Macros

ESP_SPP_MAX_MTU
SPP max MTU

ESP_SPP_MAX_SCN
SPP max SCN

ESP_SPP_MIN_TX_BUFFER_SIZE
SPP min tx buffer

ESP_SPP_MAX_TX_BUFFER_SIZE
SPP max tx buffer size
BT_SPP_DEFAULT_CONFIG()
SPP default configuration.

ESP_SPP_SEC_NONE
No security. relate to BTA_SEC_NONE in bta/bta_api.h

ESP_SPP_SEC_AUTHORIZE
Authorization required (only needed for out going connection ) relate to BTA_SEC_AUTHORIZE in
bta/bta_api.h

ESP_SPP_SEC_AUTHENTICATE
Authentication required. relate to BTA_SEC_AUTHENTICATE in bta/bta_api.h

ESP_SPP_SEC_ENCRYPT
Encryption required. relate to BTA_SEC_ENCRYPT in bta/bta_api.h

ESP_SPP_SEC_MODE4_LEVEL4
Mode 4 level 4 service, i.e. incoming/outgoing MITM and P-256 encryption relate to
BTA_SEC_MODE4_LEVEL4 in bta/bta_api.h

ESP_SPP_SEC_MITM
Man-In-The_Middle protection relate to BTA_SEC_MITM in bta/bta_api.h

ESP_SPP_SEC_IN_16_DIGITS
Min 16 digit for pin code relate to BTA_SEC_IN_16_DIGITS in bta/bta_api.h

Espressif Systems 447 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Type Definitions

typedef uint16_t esp_spp_sec_t

typedef void (*esp_spp_cb_t)(esp_spp_cb_event_t event, esp_spp_cb_param_t *param)


SPP callback function type. When handle ESP_SPP_DATA_IND_EVT, it is strongly recommended to cache
incoming data, and process them in other lower priority application task rather than in this callback directly.
Param event Event type
Param param Point to callback parameter, currently is union type

Enumerations

enum esp_spp_status_t
Values:

enumerator ESP_SPP_SUCCESS
Successful operation.

enumerator ESP_SPP_FAILURE
Generic failure.

enumerator ESP_SPP_BUSY
Temporarily can not handle this request.

enumerator ESP_SPP_NO_DATA
No data

enumerator ESP_SPP_NO_RESOURCE
No more resource

enumerator ESP_SPP_NEED_INIT
SPP module shall init first

enumerator ESP_SPP_NEED_DEINIT
SPP module shall deinit first

enumerator ESP_SPP_NO_CONNECTION
Connection may have been closed

enumerator ESP_SPP_NO_SERVER
No SPP server

enum esp_spp_role_t
Values:

enumerator ESP_SPP_ROLE_MASTER
Role: master

enumerator ESP_SPP_ROLE_SLAVE
Role: slave

Espressif Systems 448 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enum esp_spp_mode_t
Values:

enumerator ESP_SPP_MODE_CB
When data is coming, a callback will come with data

enumerator ESP_SPP_MODE_VFS
Use VFS to write/read data

enum esp_spp_cb_event_t
SPP callback function events.
Values:

enumerator ESP_SPP_INIT_EVT
When SPP is initialized, the event comes

enumerator ESP_SPP_UNINIT_EVT
When SPP is deinitialized, the event comes

enumerator ESP_SPP_DISCOVERY_COMP_EVT
When SDP discovery complete, the event comes

enumerator ESP_SPP_OPEN_EVT
When SPP Client connection open, the event comes

enumerator ESP_SPP_CLOSE_EVT
When SPP connection closed, the event comes

enumerator ESP_SPP_START_EVT
When SPP server started, the event comes

enumerator ESP_SPP_CL_INIT_EVT
When SPP client initiated a connection, the event comes

enumerator ESP_SPP_DATA_IND_EVT
When SPP connection received data, the event comes, only for ESP_SPP_MODE_CB

enumerator ESP_SPP_CONG_EVT
When SPP connection congestion status changed, the event comes, only for ESP_SPP_MODE_CB

enumerator ESP_SPP_WRITE_EVT
When SPP write operation completes, the event comes, only for ESP_SPP_MODE_CB

enumerator ESP_SPP_SRV_OPEN_EVT
When SPP Server connection open, the event comes

enumerator ESP_SPP_SRV_STOP_EVT
When SPP server stopped, the event comes

Espressif Systems 449 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_SPP_VFS_REGISTER_EVT
When SPP VFS register, the event comes

enumerator ESP_SPP_VFS_UNREGISTER_EVT
When SPP VFS unregister, the event comes

HFP Defines

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_hf_defs.h

Enumerations

enum esp_hf_in_band_ring_state_t
in-band ring tone state
Values:

enumerator ESP_HF_IN_BAND_RINGTONE_NOT_PROVIDED

enumerator ESP_HF_IN_BAND_RINGTONE_PROVIDED

enum esp_hf_vr_state_t
voice recognition state
Values:

enumerator ESP_HF_VR_STATE_DISABLED
voice recognition disabled

enumerator ESP_HF_VR_STATE_ENABLED
voice recognition enabled

enum esp_hf_volume_control_target_t
Bluetooth HFP audio volume control target.
Values:

enumerator ESP_HF_VOLUME_CONTROL_TARGET_SPK
speaker

enumerator ESP_HF_VOLUME_CONTROL_TARGET_MIC
microphone

enum esp_hf_audio_state_t
Bluetooth HFP audio connection status.
Values:

Espressif Systems 450 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HF_AUDIO_STATE_DISCONNECTED
audio connection released

enumerator ESP_HF_AUDIO_STATE_CONNECTING
audio connection has been initiated

enumerator ESP_HF_AUDIO_STATE_CONNECTED
audio connection is established

enumerator ESP_HF_AUDIO_STATE_CONNECTED_MSBC
mSBC audio connection is established

enum esp_hf_volume_type_t
Values:

enumerator ESP_HF_VOLUME_TYPE_SPK

enumerator ESP_HF_VOLUME_TYPE_MIC

enum esp_hf_network_state_t
+CIND network service availability status
Values:

enumerator ESP_HF_NETWORK_STATE_NOT_AVAILABLE

enumerator ESP_HF_NETWORK_STATE_AVAILABLE

enum esp_hf_service_type_t
+CIEV Service type
Values:

enumerator ESP_HF_SERVICE_TYPE_HOME

enumerator ESP_HF_SERVICE_TYPE_ROAMING

enum esp_hf_call_status_t
+CIND call status indicator values
Values:

enumerator ESP_HF_CALL_STATUS_NO_CALLS
no call in progress

enumerator ESP_HF_CALL_STATUS_CALL_IN_PROGRESS
call is present(active or held)

Espressif Systems 451 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enum esp_hf_call_setup_status_t
+CIND call setup status indicator values
Values:

enumerator ESP_HF_CALL_SETUP_STATUS_IDLE
no call setup in progress

enumerator ESP_HF_CALL_SETUP_STATUS_INCOMING
incoming call setup in progress

enumerator ESP_HF_CALL_SETUP_STATUS_OUTGOING_DIALING
outgoing call setup in dialing state

enumerator ESP_HF_CALL_SETUP_STATUS_OUTGOING_ALERTING
outgoing call setup in alerting state

enum esp_hf_roaming_status_t
+CIND roaming status indicator values
Values:

enumerator ESP_HF_ROAMING_STATUS_INACTIVE
roaming is not active

enumerator ESP_HF_ROAMING_STATUS_ACTIVE
a roaming is active

enum esp_hf_call_held_status_t
+CIND call held indicator values
Values:

enumerator ESP_HF_CALL_HELD_STATUS_NONE
no calls held

enumerator ESP_HF_CALL_HELD_STATUS_HELD_AND_ACTIVE
both active and held call

enumerator ESP_HF_CALL_HELD_STATUS_HELD
call on hold, no active call

enum esp_hf_current_call_status_t
+CLCC status of the call
Values:

enumerator ESP_HF_CURRENT_CALL_STATUS_ACTIVE
active

enumerator ESP_HF_CURRENT_CALL_STATUS_HELD
held

Espressif Systems 452 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HF_CURRENT_CALL_STATUS_DIALING
dialing (outgoing calls only)

enumerator ESP_HF_CURRENT_CALL_STATUS_ALERTING
alerting (outgoing calls only)

enumerator ESP_HF_CURRENT_CALL_STATUS_INCOMING
incoming (incoming calls only)

enumerator ESP_HF_CURRENT_CALL_STATUS_WAITING
waiting (incoming calls only)

enumerator ESP_HF_CURRENT_CALL_STATUS_HELD_BY_RESP_HOLD
call held by response and hold

enum esp_hf_current_call_direction_t
+CLCC direction of the call
Values:

enumerator ESP_HF_CURRENT_CALL_DIRECTION_OUTGOING
outgoing

enumerator ESP_HF_CURRENT_CALL_DIRECTION_INCOMING
incoming

enum esp_hf_current_call_mpty_type_t
+CLCC multi-party call flag
Values:

enumerator ESP_HF_CURRENT_CALL_MPTY_TYPE_SINGLE
not a member of a multi-party call

enumerator ESP_HF_CURRENT_CALL_MPTY_TYPE_MULTI
member of a multi-party call

enum esp_hf_current_call_mode_t
+CLCC call mode
Values:

enumerator ESP_HF_CURRENT_CALL_MODE_VOICE

enumerator ESP_HF_CURRENT_CALL_MODE_DATA

enumerator ESP_HF_CURRENT_CALL_MODE_FAX

enum esp_hf_call_addr_type_t
+CLCC address type
Values:

Espressif Systems 453 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HF_CALL_ADDR_TYPE_UNKNOWN
unkown address type

enumerator ESP_HF_CALL_ADDR_TYPE_INTERNATIONAL
international address

enum esp_hf_subscriber_service_type_t
+CNUM service type of the phone number
Values:

enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_UNKNOWN
unknown

enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_VOICE
voice service

enumerator ESP_HF_SUBSCRIBER_SERVICE_TYPE_FAX
fax service

enum esp_hf_btrh_status_t
+BTRH response and hold result code
Values:

enumerator ESP_HF_BTRH_STATUS_HELD
incoming call is put on held in AG

enumerator ESP_HF_BTRH_STATUS_ACCEPTED
held incoming call is accepted in AG

enumerator ESP_HF_BTRH_STATUS_REJECTED
held incoming call is rejected in AG

enum esp_hf_btrh_cmd_t
AT+BTRH response and hold action code.
Values:

enumerator ESP_HF_BTRH_CMD_HOLD
put the incoming call on hold

enumerator ESP_HF_BTRH_CMD_ACCEPT
accept a held incoming call

enumerator ESP_HF_BTRH_CMD_REJECT
reject a held incoming call

enum esp_hf_nrec_t
Values:

Espressif Systems 454 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HF_NREC_STOP

enumerator ESP_HF_NREC_START

enum esp_hf_call_waiting_status_t
+CCWA resposne status
Values:

enumerator ESP_HF_CALL_WAITING_INACTIVE

enumerator ESP_HF_CALL_WAITING_ACTIVE

enum esp_hf_wbs_config_t
Values:

enumerator ESP_HF_WBS_NONE

enumerator ESP_HF_WBS_NO

enumerator ESP_HF_WBS_YES

enum esp_hf_connection_state_t
Bluetooth HFP RFCOMM connection and service level connection status.
Values:

enumerator ESP_HF_CONNECTION_STATE_DISCONNECTED
RFCOMM data link channel released

enumerator ESP_HF_CONNECTION_STATE_CONNECTING
connecting remote device on the RFCOMM data link

enumerator ESP_HF_CONNECTION_STATE_CONNECTED
RFCOMM connection established

enumerator ESP_HF_CONNECTION_STATE_SLC_CONNECTED
service level connection established

enumerator ESP_HF_CONNECTION_STATE_DISCONNECTING
disconnecting with remote device on the RFCOMM data link

enum esp_hf_chld_type_t
AT+CHLD command values.
Values:

enumerator ESP_HF_CHLD_TYPE_REL
<0>, Terminate all held or set UDUB(“busy”) to a waiting call

Espressif Systems 455 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HF_CHLD_TYPE_REL_ACC
<1>, Terminate all active calls and accepts a waiting/held call

enumerator ESP_HF_CHLD_TYPE_HOLD_ACC
<2>, Hold all active calls and accepts a waiting/held call

enumerator ESP_HF_CHLD_TYPE_MERGE
<3>, Add all held calls to a conference

enumerator ESP_HF_CHLD_TYPE_MERGE_DETACH
<4>, connect the two calls and disconnects the subscriber from both calls

enumerator ESP_HF_CHLD_TYPE_REL_X
<1x>, releases specified calls only

enumerator ESP_HF_CHLD_TYPE_PRIV_X
<2x>, request private consultation mode with specified call

enum esp_hf_at_response_code_t
Values:

enumerator ESP_HF_AT_RESPONSE_CODE_OK
acknowledges execution of a command line

enumerator ESP_HF_AT_RESPONSE_CODE_ERR
command not accepted

enumerator ESP_HF_AT_RESPONSE_CODE_NO_CARRIER
connection terminated

enumerator ESP_HF_AT_RESPONSE_CODE_BUSY
busy signal detected

enumerator ESP_HF_AT_RESPONSE_CODE_NO_ANSWER
connection completion timeout

enumerator ESP_HF_AT_RESPONSE_CODE_DELAYED
delayed

enumerator ESP_HF_AT_RESPONSE_CODE_BLACKLISTED
blacklisted

enumerator ESP_HF_AT_RESPONSE_CODE_CME
CME error

enum esp_hf_at_response_t
Values:

Espressif Systems 456 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HF_AT_RESPONSE_ERROR

enumerator ESP_HF_AT_RESPONSE_OK

enum esp_hf_cme_err_t
Extended Audio Gateway Error Result Code Response.
Values:

enumerator ESP_HF_CME_AG_FAILURE
ag failure

enumerator ESP_HF_CME_NO_CONNECTION_TO_PHONE
no connection to phone

enumerator ESP_HF_CME_OPERATION_NOT_ALLOWED
operation not allowed

enumerator ESP_HF_CME_OPERATION_NOT_SUPPORTED
operation not supported

enumerator ESP_HF_CME_PH_SIM_PIN_REQUIRED
PH-SIM PIN Required

enumerator ESP_HF_CME_SIM_NOT_INSERTED
SIM not inserted

enumerator ESP_HF_CME_SIM_PIN_REQUIRED
SIM PIN required

enumerator ESP_HF_CME_SIM_PUK_REQUIRED
SIM PUK required

enumerator ESP_HF_CME_SIM_FAILURE
SIM failure

enumerator ESP_HF_CME_SIM_BUSY
SIM busy

enumerator ESP_HF_CME_INCORRECT_PASSWORD
incorrect password

enumerator ESP_HF_CME_SIM_PIN2_REQUIRED
SIM PIN2 required

enumerator ESP_HF_CME_SIM_PUK2_REQUIRED
SIM PUK2 required

Espressif Systems 457 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HF_CME_MEMORY_FULL
memory full

enumerator ESP_HF_CME_INVALID_INDEX
invalid index

enumerator ESP_HF_CME_MEMORY_FAILURE
memory failure

enumerator ESP_HF_CME_TEXT_STRING_TOO_LONG
test string too long

enumerator ESP_HF_CME_INVALID_CHARACTERS_IN_TEXT_STRING
invalid characters in text string

enumerator ESP_HF_CME_DIAL_STRING_TOO_LONG
dial string too long

enumerator ESP_HF_CME_INVALID_CHARACTERS_IN_DIAL_STRING
invalid characters in dial string

enumerator ESP_HF_CME_NO_NETWORK_SERVICE
no network service

enumerator ESP_HF_CME_NETWORK_TIMEOUT
network timeout

enumerator ESP_HF_CME_NETWORK_NOT_ALLOWED
network not allowed &#8212;emergency calls only

HFP Client API

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_hf_client_api.h

Functions
esp_err_t esp_hf_client_register_callback(esp_hf_client_cb_t callback)
Register application callback function to HFP client module. This function should be called only after
esp_bluedroid_enable() completes successfully.
Parameters callback –[in] HFP client event callback function
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: if callback is a NULL function pointer

Espressif Systems 458 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_hf_client_init(void)
Initialize the bluetooth HFP client module. This function should be called after esp_bluedroid_enable() com-
pletes successfully.
Returns
• ESP_OK: if the initialization request is sent successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_deinit(void)
De-initialize for HFP client module. This function should be called only after esp_bluedroid_enable() com-
pletes successfully.
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_connect(esp_bd_addr_t remote_bda)
Establish a Service Level Connection to remote bluetooth HFP audio gateway(AG) device. This function must
be called after esp_hf_client_init() and before esp_hf_client_deinit().
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: connect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_disconnect(esp_bd_addr_t remote_bda)
Disconnect from the remote HFP audio gateway. This function must be called after esp_hf_client_init() and
before esp_hf_client_deinit().
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_connect_audio(esp_bd_addr_t remote_bda)
Create audio connection with remote HFP AG. As a precondition to use this API, Service Level Connection
shall exist with AG.
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_disconnect_audio(esp_bd_addr_t remote_bda)
Release the established audio connection with remote HFP AG. As a precondition to use this API, Service
Level Connection shall exist with AG.
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_start_voice_recognition(void)
Enable voice recognition in the AG. As a precondition to use this API, Service Level Connection shall exist
with AG.
Returns

Espressif Systems 459 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• ESP_OK: disconnect request is sent to lower layer


• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_stop_voice_recognition(void)
Disable voice recognition in the AG. As a precondition to use this API, Service Level Connection shall exist
with AG.
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_volume_update(esp_hf_volume_control_target_t type, int volume)
Volume synchronization with AG. As a precondition to use this API, Service Level Connection shall exist with
AG.
Parameters
• type –[in] volume control target, speaker or microphone
• volume –[in] gain of the speaker of microphone, ranges 0 to 15
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_dial(const char *number)
Place a call with a specified number, if number is NULL, last called number is called. As a precondition to
use this API, Service Level Connection shall exist with AG.
Parameters number –[in] number string of the call. If NULL, the last number is called(aka
re-dial)
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_dial_memory(int location)
Place a call with number specified by location(speed dial). As a precondition to use this API, Service Level
Connection shall exist with AG.
Parameters location –[in] location of the number in the memory
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_send_chld_cmd(esp_hf_chld_type_t chld, int idx)
Send call hold and multiparty commands, or enhanced call control commands(Use AT+CHLD). As a precon-
dition to use this API, Service Level Connection shall exist with AG.
Parameters
• chld –[in] AT+CHLD call hold and multiparty handling AT command.
• idx –[in] used in Enhanced Call Control Mechanisms, used if chld is
ESP_HF_CHLD_TYPE_REL_X or ESP_HF_CHLD_TYPE_PRIV_X
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_send_btrh_cmd(esp_hf_btrh_cmd_t btrh)
Send response and hold action command(Send AT+BTRH command) As a precondition to use this API, Ser-
vice Level Connection shall exist with AG.

Espressif Systems 460 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters btrh –[in] response and hold action to send


Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_answer_call(void)
Answer an incoming call(send ATA command). As a precondition to use this API, Service Level Connection
shall exist with AG.
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_reject_call(void)
Reject an incoming call or terminate an ongoing call(send AT+CHUP command). As a precondition to use
this API, Service Level Connection shall exist with AG.
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_query_current_calls(void)
Query list of current calls in AG(send AT+CLCC command). As a precondition to use this API, Service Level
Connection shall exist with AG.
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_query_current_operator_name(void)
Query the name of currently selected network operator in AG(use AT+COPS commands). As a precondition
to use this API, Service Level Connection shall exist with AG.
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_retrieve_subscriber_info(void)
Get subscriber information number from AG(send AT+CNUM command) As a precondition to use this API,
Service Level Connection shall exist with AG.
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_send_dtmf(char code)
Transmit DTMF codes during an ongoing call(use AT+VTS commands) As a precondition to use this API,
Service Level Connection shall exist with AG.
Parameters code –[in] dtmf code, single ascii character in the set 0-9, #, *, A-D
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others

Espressif Systems 461 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_hf_client_send_xapl(char *information, uint32_t features)


Send command to enable Vendor specific feature to indicate battery level and docker status This is Apple-
specific commands, but used by most device, including Android and Windows.
Parameters
• information –[in] XAPL vendorID-productID-version, such as “0505-1995-0610”
vendorID: A string representation of the hex value of the vendor ID from the manufacturer,
without the 0x prefix. productID: A string representation of the hex value of the product
ID from the manufacturer, without the 0x prefix. version: The revision of the software
• features –[in] A base-10 representation of a bit field. such as
ESP_HF_CLIENT_XAPL_FEAT_BATTERY_REPORT
Returns
• ESP_OK: Feature enable request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_send_iphoneaccev(uint32_t bat_level, bool docked)
Send Battery level and docker status Enable this feature using XAPL command first This is Apple-specific
commands, but used by most device, including Android and Windows.
Parameters
• bat_level –[in] Battery Level: value between 0 and 9
• docked –[in] Dock State: false = undocked, true = docked
Returns
• ESP_OK: battery level is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_request_last_voice_tag_number(void)
Request a phone number from AG corresponding to last voice tag recorded (send AT+BINP command). As a
precondition to use this API, Service Level Connection shall exist with AG.
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_send_nrec(void)
Disable echo cancellation and noise reduction in the AG (use AT+NREC=0 command). As a precondition to
use this API, Service Level Connection shall exist with AG.
Returns
• ESP_OK: NREC=0 request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_client_register_data_callback(esp_hf_client_incoming_data_cb_t recv,
esp_hf_client_outgoing_data_cb_t send)
Register HFP client data output function; the callback is only used in the case that Voice Over HCI is enabled.
Parameters
• recv –[in] HFP client incoming data callback function
• send –[in] HFP client outgoing data callback function
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: if callback is a NULL function pointer
esp_err_t esp_hf_client_pkt_stat_nums_get(uint16_t sync_conn_handle)
Get the number of packets received and sent This function is only used in the case that Voice Over HCI is
enabled and the audio state is connected. When the operation is completed, the callback function will be called
with ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT.

Espressif Systems 462 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters sync_conn_handle –[in] the (e)SCO connection handle


Returns
• ESP_OK: if the request is sent successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
void esp_hf_client_outgoing_data_ready(void)
Trigger the lower-layer to fetch and send audio data. This function is only only used in the case that Voice
Over HCI is enabled. After this function is called, lower layer will invoke esp_hf_client_outgoing_data_cb_t
to fetch data.
As a precondition to use this API, Service Level Connection shall exist with AG.
void esp_hf_client_pcm_resample_init(uint32_t src_sps, uint32_t bits, uint32_t channels)
Initialize the down sampling converter. This is a utility function that can only be used in the case that Voice
Over HCI is enabled.
Parameters
• src_sps –[in] original samples per second(source audio data, i.e. 48000, 32000, 16000,
44100, 22050, 11025)
• bits –[in] number of bits per pcm sample (16)
• channels –[in] number of channels (i.e. mono(1), stereo(2)…)
void esp_hf_client_pcm_resample_deinit(void)
Deinitialize the down sampling converter.
int32_t esp_hf_client_pcm_resample(void *src, uint32_t in_bytes, void *dst)
Down sampling utility to convert high sampling rate into 8K/16bits 1-channel mode PCM samples. This can
only be used in the case that Voice Over HCI is enabled.
Parameters
• src –[in] pointer to the buffer where the original sampling PCM are stored
• in_bytes –[in] length of the input PCM sample buffer in byte
• dst –[in] pointer to the buffer which is to be used to store the converted PCM samples
Returns number of samples converted

Unions

union esp_hf_client_cb_param_t
#include <esp_hf_client_api.h> HFP client callback parameters.

Public Members

struct esp_hf_client_cb_param_t::hf_client_conn_stat_param conn_stat


HF callback param of ESP_HF_CLIENT_CONNECTION_STATE_EVT

struct esp_hf_client_cb_param_t::hf_client_audio_stat_param audio_stat


HF callback param of ESP_HF_CLIENT_AUDIO_STATE_EVT

struct esp_hf_client_cb_param_t::hf_client_bvra_param bvra


HF callback param of ESP_HF_CLIENT_BVRA_EVT

struct esp_hf_client_cb_param_t::hf_client_service_availability_param service_availability


HF callback param of ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT

Espressif Systems 463 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_hf_client_cb_param_t::hf_client_network_roaming_param roaming


HF callback param of ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT

struct esp_hf_client_cb_param_t::hf_client_signal_strength_ind_param signal_strength


HF callback param of ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT

struct esp_hf_client_cb_param_t::hf_client_battery_level_ind_param battery_level


HF callback param of ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT

struct esp_hf_client_cb_param_t::hf_client_current_operator_param cops


HF callback param of ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT

struct esp_hf_client_cb_param_t::hf_client_call_ind_param call


HF callback param of ESP_HF_CLIENT_CIND_CALL_EVT

struct esp_hf_client_cb_param_t::hf_client_call_setup_ind_param call_setup


HF callback param of ESP_HF_CLIENT_BVRA_EVT

struct esp_hf_client_cb_param_t::hf_client_call_held_ind_param call_held


HF callback param of ESP_HF_CLIENT_CIND_CALL_HELD_EVT

struct esp_hf_client_cb_param_t::hf_client_btrh_param btrh


HF callback param of ESP_HF_CLIENT_BRTH_EVT

struct esp_hf_client_cb_param_t::hf_client_clip_param clip


HF callback param of ESP_HF_CLIENT_CLIP_EVT

struct esp_hf_client_cb_param_t::hf_client_ccwa_param ccwa


HF callback param of ESP_HF_CLIENT_BVRA_EVT

struct esp_hf_client_cb_param_t::hf_client_clcc_param clcc


HF callback param of ESP_HF_CLIENT_CLCC_EVT

struct esp_hf_client_cb_param_t::hf_client_volume_control_param volume_control


HF callback param of ESP_HF_CLIENT_VOLUME_CONTROL_EVT

struct esp_hf_client_cb_param_t::hf_client_at_response_param at_response


HF callback param of ESP_HF_CLIENT_AT_RESPONSE_EVT

struct esp_hf_client_cb_param_t::hf_client_cnum_param cnum


HF callback param of ESP_HF_CLIENT_CNUM_EVT

struct esp_hf_client_cb_param_t::hf_client_bsirparam bsir


HF callback param of ESP_HF_CLIENT_BSIR_EVT

struct esp_hf_client_cb_param_t::hf_client_binp_param binp


HF callback param of ESP_HF_CLIENT_BINP_EVT

Espressif Systems 464 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_hf_client_cb_param_t::hf_client_pkt_status_nums pkt_nums


HF callback param of ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT

struct hf_client_at_response_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_AT_RESPONSE_EVT.

Public Members

esp_hf_at_response_code_t code
AT response code

esp_hf_cme_err_t cme
Extended Audio Gateway Error Result Code

struct hf_client_audio_stat_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_AUDIO_STATE_EVT.

Public Members

esp_hf_client_audio_state_t state
audio connection state

esp_bd_addr_t remote_bda
remote bluetooth device address

uint16_t sync_conn_handle
(e)SCO connection handle

struct hf_client_battery_level_ind_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT.

Public Members

int value
battery charge value, ranges from 0 to 5

struct hf_client_binp_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_BINP_EVT.

Public Members

const char *number


phone number corresponding to the last voice tag in the HF

struct hf_client_bsirparam
#include <esp_hf_client_api.h> ESP_HF_CLIENT_BSIR_EVT.

Espressif Systems 465 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_hf_client_in_band_ring_state_t state
setting state of in-band ring tone

struct hf_client_btrh_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_BTRH_EVT.

Public Members

esp_hf_btrh_status_t status
call hold and response status result code

struct hf_client_bvra_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_BVRA_EVT.

Public Members

esp_hf_vr_state_t value
voice recognition state

struct hf_client_call_held_ind_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_HELD_EVT.

Public Members

esp_hf_call_held_status_t status
bluetooth proprietary call hold status indicator

struct hf_client_call_ind_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_EVT.

Public Members

esp_hf_call_status_t status
call status indicator

struct hf_client_call_setup_ind_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_CALL_SETUP_EVT.

Public Members

esp_hf_call_setup_status_t status
call setup status indicator

Espressif Systems 466 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct hf_client_ccwa_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CCWA_EVT.

Public Members

const char *number


phone number string of waiting call

struct hf_client_clcc_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CLCC_EVT.

Public Members

int idx
numbering(starting with 1) of the call

esp_hf_current_call_direction_t dir
direction of the call

esp_hf_current_call_status_t status
status of the call

esp_hf_current_call_mpty_type_t mpty
multi-party flag

char *number
phone number(optional)

struct hf_client_clip_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CLIP_EVT.

Public Members

const char *number


phone number string of call

struct hf_client_cnum_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CNUM_EVT.

Public Members

const char *number


phone number string

esp_hf_subscriber_service_type_t type
service type that the phone number relates to

Espressif Systems 467 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct hf_client_conn_stat_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CONNECTION_STATE_EVT.

Public Members

esp_hf_client_connection_state_t state
HF connection state

uint32_t peer_feat
AG supported features

uint32_t chld_feat
AG supported features on call hold and multiparty services

esp_bd_addr_t remote_bda
remote bluetooth device address

struct hf_client_current_operator_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT.

Public Members

const char *name


name of the network operator

struct hf_client_network_roaming_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT.

Public Members

esp_hf_roaming_status_t status
roaming status

struct hf_client_pkt_status_nums
#include <esp_hf_client_api.h> ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT.

Public Members

uint32_t rx_total
the total number of packets received

uint32_t rx_correct
the total number of packets data correctly received

uint32_t rx_err
the total number of packets data with possible invalid

Espressif Systems 468 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint32_t rx_none
the total number of packets data no received

uint32_t rx_lost
the total number of packets data partially lost

uint32_t tx_total
the total number of packets send

uint32_t tx_discarded
the total number of packets send lost

struct hf_client_service_availability_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT.

Public Members

esp_hf_network_state_t status
service availability status

struct hf_client_signal_strength_ind_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT.

Public Members

int value
signal strength value, ranges from 0 to 5

struct hf_client_volume_control_param
#include <esp_hf_client_api.h> ESP_HF_CLIENT_VOLUME_CONTROL_EVT.

Public Members

esp_hf_volume_control_target_t type
volume control target, speaker or microphone

int volume
gain, ranges from 0 to 15

Macros

ESP_BT_HF_CLIENT_NUMBER_LEN

ESP_BT_HF_CLIENT_OPERATOR_NAME_LEN

ESP_BT_HF_AT_SEND_XAPL_LEN

Espressif Systems 469 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_HF_CLIENT_PEER_FEAT_3WAY

ESP_HF_CLIENT_PEER_FEAT_ECNR

ESP_HF_CLIENT_PEER_FEAT_VREC

ESP_HF_CLIENT_PEER_FEAT_INBAND

ESP_HF_CLIENT_PEER_FEAT_VTAG

ESP_HF_CLIENT_PEER_FEAT_REJECT

ESP_HF_CLIENT_PEER_FEAT_ECS

ESP_HF_CLIENT_PEER_FEAT_ECC

ESP_HF_CLIENT_PEER_FEAT_EXTERR

ESP_HF_CLIENT_PEER_FEAT_CODEC

ESP_HF_CLIENT_PEER_FEAT_HF_IND

ESP_HF_CLIENT_PEER_FEAT_ESCO_S4

ESP_HF_CLIENT_CHLD_FEAT_REL

ESP_HF_CLIENT_CHLD_FEAT_REL_ACC

ESP_HF_CLIENT_CHLD_FEAT_REL_X

ESP_HF_CLIENT_CHLD_FEAT_HOLD_ACC

ESP_HF_CLIENT_CHLD_FEAT_PRIV_X

ESP_HF_CLIENT_CHLD_FEAT_MERGE

ESP_HF_CLIENT_CHLD_FEAT_MERGE_DETACH

ESP_HF_CLIENT_XAPL_FEAT_RESERVED

ESP_HF_CLIENT_XAPL_FEAT_BATTERY_REPORT

ESP_HF_CLIENT_XAPL_FEAT_DOCKED

ESP_HF_CLIENT_XAPL_FEAT_SIRI_STATUS_REPORT

Espressif Systems 470 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_HF_CLIENT_XAPL_NR_STATUS_REPORT

Type Definitions

typedef void (*esp_hf_client_incoming_data_cb_t)(const uint8_t *buf, uint32_t len)


HFP client incoming data callback function, the callback is useful in case of Voice Over HCI.
Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer
is allocated inside bluetooth protocol stack and will be released after invoke of the callback is
finished.
Param len [in] : size(in bytes) in buf

typedef uint32_t (*esp_hf_client_outgoing_data_cb_t)(uint8_t *buf, uint32_t len)


HFP client outgoing data callback function, the callback is useful in case of Voice Over HCI. Once audio
connection is set up and the application layer has prepared data to send, the lower layer will call this function
to read data and then send. This callback is supposed to be implemented as non-blocking, and if data is not
enough, return value 0 is supposed.
Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer
is allocated inside bluetooth protocol stack and will be released after invoke of the callback is
finished.
Param len [in] : size(in bytes) in buf
Return length of data successfully read

typedef void (*esp_hf_client_cb_t)(esp_hf_client_cb_event_t event, esp_hf_client_cb_param_t *param)


HFP client callback function type.
Param event : Event type
Param param : Pointer to callback parameter

Enumerations

enum esp_hf_client_connection_state_t
Bluetooth HFP RFCOMM connection and service level connection status.
Values:

enumerator ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTED
RFCOMM data link channel released

enumerator ESP_HF_CLIENT_CONNECTION_STATE_CONNECTING
connecting remote device on the RFCOMM data link

enumerator ESP_HF_CLIENT_CONNECTION_STATE_CONNECTED
RFCOMM connection established

enumerator ESP_HF_CLIENT_CONNECTION_STATE_SLC_CONNECTED
service level connection established

enumerator ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTING
disconnecting with remote device on the RFCOMM dat link

enum esp_hf_client_audio_state_t
Bluetooth HFP audio connection status.
Values:

Espressif Systems 471 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HF_CLIENT_AUDIO_STATE_DISCONNECTED
audio connection released

enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTING
audio connection has been initiated

enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTED
audio connection is established

enumerator ESP_HF_CLIENT_AUDIO_STATE_CONNECTED_MSBC
mSBC audio connection is established

enum esp_hf_client_in_band_ring_state_t
in-band ring tone state
Values:

enumerator ESP_HF_CLIENT_IN_BAND_RINGTONE_NOT_PROVIDED

enumerator ESP_HF_CLIENT_IN_BAND_RINGTONE_PROVIDED

enum esp_hf_client_cb_event_t
HF CLIENT callback events.
Values:

enumerator ESP_HF_CLIENT_CONNECTION_STATE_EVT
connection state changed event

enumerator ESP_HF_CLIENT_AUDIO_STATE_EVT
audio connection state change event

enumerator ESP_HF_CLIENT_BVRA_EVT
voice recognition state change event

enumerator ESP_HF_CLIENT_CIND_CALL_EVT
call indication

enumerator ESP_HF_CLIENT_CIND_CALL_SETUP_EVT
call setup indication

enumerator ESP_HF_CLIENT_CIND_CALL_HELD_EVT
call held indication

enumerator ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT
network service availability indication

enumerator ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT
signal strength indication

Espressif Systems 472 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT
roaming status indication

enumerator ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT
battery level indication

enumerator ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT
current operator information

enumerator ESP_HF_CLIENT_BTRH_EVT
call response and hold event

enumerator ESP_HF_CLIENT_CLIP_EVT
Calling Line Identification notification

enumerator ESP_HF_CLIENT_CCWA_EVT
call waiting notification

enumerator ESP_HF_CLIENT_CLCC_EVT
list of current calls notification

enumerator ESP_HF_CLIENT_VOLUME_CONTROL_EVT
audio volume control command from AG, provided by +VGM or +VGS message

enumerator ESP_HF_CLIENT_AT_RESPONSE_EVT
AT command response event

enumerator ESP_HF_CLIENT_CNUM_EVT
subscriber information response from AG

enumerator ESP_HF_CLIENT_BSIR_EVT
setting of in-band ring tone

enumerator ESP_HF_CLIENT_BINP_EVT
requested number of last voice tag from AG

enumerator ESP_HF_CLIENT_RING_IND_EVT
ring indication event

enumerator ESP_HF_CLIENT_PKT_STAT_NUMS_GET_EVT
requested number of packet different status

HFP AG API

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_hf_ag_api.h

Espressif Systems 473 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Functions
esp_err_t esp_hf_ag_register_callback(esp_hf_cb_t callback)
Register application callback function to HFP AG module. This function should be called only after
esp_bluedroid_enable() completes successfully.
Parameters callback –[in] HFP AG event callback function
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: if callback is a NULL function pointer
esp_err_t esp_hf_ag_init(void)
Initialize the bluetooth HF AG module. This function should be called after esp_bluedroid_enable() completes
successfully.
Returns
• ESP_OK: if the initialization request is sent successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_deinit(void)
De-initialize for HF AG module. This function should be called only after esp_bluedroid_enable() completes
successfully.
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_slc_connect(esp_bd_addr_t remote_bda)
To establish a Service Level Connection to remote bluetooth HFP client device. This function must be called
after esp_hf_ag_init() and before esp_hf_ag_deinit().
Parameters remote_bda –[in] remote bluetooth HFP client device address
Returns
• ESP_OK: connect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_slc_disconnect(esp_bd_addr_t remote_bda)
Disconnect from the remote HFP client. This function must be called after esp_hf_ag_init() and before
esp_hf_ag_deinit().
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_audio_connect(esp_bd_addr_t remote_bda)
Create audio connection with remote HFP client. As a precondition to use this API, Service Level Connection
shall exist with HFP client.
Parameters remote_bda –[in] remote bluetooth device address
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_audio_disconnect(esp_bd_addr_t remote_bda)
Release the established audio connection with remote HFP client. As a precondition to use this API, Service
Level Connection shall exist with HFP client.
Parameters remote_bda –[in] remote bluetooth device address

Espressif Systems 474 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_vra_control(esp_bd_addr_t remote_bda, esp_hf_vr_state_t value)
Response of Volume Recognition Command(AT+VRA) from HFP client. As a precondition to use this API,
Service Level Connection shall exist with HFP client.
Parameters
• remote_bda –[in] the device address of voice recognition initiator
• value –[in] 0 - voice recognition disabled, 1- voice recognition enabled
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_volume_control(esp_bd_addr_t remote_bda, esp_hf_volume_control_target_t type,
int volume)
Volume synchronization with HFP client. As a precondition to use this API, Service Level Connection shall
exist with HFP client.
Parameters
• remote_bda –[in] remote bluetooth device address
• type –[in] volume control target, speaker or microphone
• volume –[in] gain of the speaker of microphone, ranges 0 to 15
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_unknown_at_send(esp_bd_addr_t remote_addr, char *unat)
Handle Unknown AT command from HFP Client. As a precondition to use this API, Service Level Connection
shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• unat –[in] User AT command response to HF Client. It will response “ERROR”by
default if unat is NULL.
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_cmee_send(esp_bd_addr_t remote_bda, esp_hf_at_response_code_t response_code,
esp_hf_cme_err_t error_code)
Unsolicited send extend AT error code to HFP Client. As a precondition to use this API, Service Level Con-
nection shall exist with HFP client.
Parameters
• remote_bda –[in] remote bluetooth device address
• response_code –[in] AT command response code
• error_code –[in] CME error code
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_devices_status_indchange(esp_bd_addr_t remote_addr, esp_hf_call_status_t
call_state, esp_hf_call_setup_status_t
call_setup_state, esp_hf_network_state_t ntk_state,
int signal)

Espressif Systems 475 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Unsolicited send device status notification to HFP Client. As a precondition to use this API, Service Level
Connection shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• call_state –[in] call state
• call_setup_state –[in] call setup state
• ntk_state –[in] network service state
• signal –[in] signal strength from 0 to 5
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_cind_response(esp_bd_addr_t remote_addr, esp_hf_call_status_t call_state,
esp_hf_call_setup_status_t call_setup_state, esp_hf_network_state_t
ntk_state, int signal, esp_hf_roaming_status_t roam, int batt_lev,
esp_hf_call_held_status_t call_held_status)
Response to device individual indicators to HFP Client. As a precondition to use this API, Service Level
Connection shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• call_state –[in] call state
• call_setup_state –[in] call setup state
• ntk_state –[in] network service state
• signal –[in] signal strength from 0 to 5
• roam –[in] roam state
• batt_lev –[in] battery level from 0 to 5
• call_held_status –[in] call held status
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_cops_response(esp_bd_addr_t remote_addr, char *name)
Reponse for AT+COPS command from HF Client. As a precondition to use this API, Service Level Connection
shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• name –[in] current operator name
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_clcc_response(esp_bd_addr_t remote_addr, int index,
esp_hf_current_call_direction_t dir, esp_hf_current_call_status_t
current_call_state, esp_hf_current_call_mode_t mode,
esp_hf_current_call_mpty_type_t mpty, char *number,
esp_hf_call_addr_type_t type)
Response to AT+CLCC command from HFP Client. As a precondition to use this API, Service Level Con-
nection shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• index –[in] the index of current call
• dir –[in] call direction (incoming/outgoing)
• current_call_state –[in] current call state

Espressif Systems 476 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• mode –[in] current call mode (voice/data/fax)


• mpty –[in] single or multi type
• number –[in] current call number
• type –[in] international type or unknow
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_cnum_response(esp_bd_addr_t remote_addr, char *number,
esp_hf_subscriber_service_type_t type)
Response for AT+CNUM command from HF Client. As a precondition to use this API, Service Level Con-
nection shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• number –[in] registration number
• type –[in] service type (unknown/voice/fax)
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_bsir(esp_bd_addr_t remote_addr, esp_hf_in_band_ring_state_t state)
Inform HF Client that AG Provided in-band ring tone or not. As a precondition to use this API, Service Level
Connection shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• state –[in] in-band ring tone state
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_answer_call(esp_bd_addr_t remote_addr, int num_active, int num_held,
esp_hf_call_status_t call_state, esp_hf_call_setup_status_t
call_setup_state, char *number, esp_hf_call_addr_type_t
call_addr_type)
Answer Incoming Call from AG. As a precondition to use this API, Service Level Connection shall exist with
HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• num_active –[in] the number of active call
• num_held –[in] the number of held call
• call_state –[in] call state
• call_setup_state –[in] call setup state
• number –[in] number of the incoming call
• call_addr_type –[in] call address type
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_reject_call(esp_bd_addr_t remote_addr, int num_active, int num_held,
esp_hf_call_status_t call_state, esp_hf_call_setup_status_t
call_setup_state, char *number, esp_hf_call_addr_type_t
call_addr_type)
Reject Incoming Call from AG. As a precondition to use this API, Service Level Connection shall exist with
HFP client.

Espressif Systems 477 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters
• remote_addr –[in] remote bluetooth device address
• num_active –[in] the number of active call
• num_held –[in] the number of held call
• call_state –[in] call state
• call_setup_state –[in] call setup state
• number –[in] number of the incoming call
• call_addr_type –[in] call address type
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_out_call(esp_bd_addr_t remote_addr, int num_active, int num_held,
esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state,
char *number, esp_hf_call_addr_type_t call_addr_type)
Initiate a call from AG. As a precondition to use this API, Service Level Connection shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• num_active –[in] the number of active call
• num_held –[in] the number of held call
• call_state –[in] call state
• call_setup_state –[in] call setup state
• number –[in] number of the outgoing call
• call_addr_type –[in] call address type
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_end_call(esp_bd_addr_t remote_addr, int num_active, int num_held,
esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state,
char *number, esp_hf_call_addr_type_t call_addr_type)
End an ongoing call. As a precondition to use this API, Service Level Connection shall exist with HFP client.
Parameters
• remote_addr –[in] remote bluetooth device address
• num_active –[in] the number of active call
• num_held –[in] the number of held call
• call_state –[in] call state
• call_setup_state –[in] call setup state
• number –[in] number of the call
• call_addr_type –[in] call address type
Returns
• ESP_OK: disconnect request is sent to lower layer
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others
esp_err_t esp_hf_ag_register_data_callback(esp_hf_incoming_data_cb_t recv,
esp_hf_outgoing_data_cb_t send)
Register AG data output function. The callback is only used in the case that Voice Over HCI is enabled.
Parameters
• recv –[in] HFP client incoming data callback function
• send –[in] HFP client outgoing data callback function
Returns
• ESP_OK: success
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: if callback is a NULL function pointer

Espressif Systems 478 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_hf_ag_pkt_stat_nums_get(uint16_t sync_conn_handle)


Get the number of packets received and sent.

This function is only used in the case that Voice Over HCI is␣
,→enabled and the audio state is connected.
When the operation is completed, the callback function will be␣
,→called with ESP_HF_PKT_STAT_NUMS_GET_EVT.

Parameters sync_conn_handle –[in] the (e)SCO connection handle


Returns
• ESP_OK: if the request is sent successfully
• ESP_INVALID_STATE: if bluetooth stack is not yet enabled
• ESP_FAIL: others

void esp_hf_ag_outgoing_data_ready(void)
Trigger the lower-layer to fetch and send audio data.

This function is only used in the case that Voice Over HCI is␣
,→ enabled.
As a precondition to use this API, Service Level Connection shall␣
,→exist with HFP client.
After this function is called, lower layer will invoke esp_hf_
,→client_outgoing_data_cb_t to fetch data

Unions

union esp_hf_cb_param_t
#include <esp_hf_ag_api.h> HFP AG callback parameters.

Public Members

struct esp_hf_cb_param_t::hf_conn_stat_param conn_stat


AG callback param of ESP_HF_CONNECTION_STATE_EVT

struct esp_hf_cb_param_t::hf_audio_stat_param audio_stat


AG callback param of ESP_HF_AUDIO_STATE_EVT

struct esp_hf_cb_param_t::hf_vra_rep_param vra_rep


AG callback param of ESP_HF_BVRA_RESPONSE_EVT

struct esp_hf_cb_param_t::hf_volume_control_param volume_control


AG callback param of ESP_HF_VOLUME_CONTROL_EVT

struct esp_hf_cb_param_t::hf_unat_rep_param unat_rep


AG callback param of ESP_HF_UNAT_RESPONSE_EVT

struct esp_hf_cb_param_t::hf_out_call_param out_call


AG callback param of ESP_HF_DIAL_EVT

Espressif Systems 479 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_hf_cb_param_t::hf_ind_upd_param ind_upd


AG callback param of ESP_HF_IND_UPDATE_EVT

struct esp_hf_cb_param_t::hf_cind_rep_param cind_rep


AG callback param of ESP_HF_CIND_RESPONSE_EVT

struct esp_hf_cb_param_t::hf_cops_rep_param cops_rep


AG callback param of ESP_HF_COPS_RESPONSE_EVT

struct esp_hf_cb_param_t::hf_clcc_rep_param clcc_rep


AG callback param of ESP_HF_CLCC_RESPONSE_EVT

struct esp_hf_cb_param_t::hf_cnum_rep_param cnum_rep


AG callback param of ESP_HF_CNUM_RESPONSE_EVT

struct esp_hf_cb_param_t::hf_vts_rep_param vts_rep


AG callback param of ESP_HF_VTS_RESPONSE_EVT

struct esp_hf_cb_param_t::hf_nrec_param nrec


AG callback param of ESP_HF_NREC_RESPONSE_EVT

struct esp_hf_cb_param_t::hf_ata_rep_param ata_rep


AG callback param of ESP_HF_ATA_RESPONSE_EVT

struct esp_hf_cb_param_t::hf_chup_rep_param chup_rep


AG callback param of ESP_HF_CHUP_RESPONSE_EVT

struct esp_hf_cb_param_t::hf_wbs_rep_param wbs_rep


AG callback param of ESP_HF_WBS_RESPONSE_EVT

struct esp_hf_cb_param_t::hf_bcs_rep_param bcs_rep


AG callback param of ESP_HF_BCS_RESPONSE_EVT

struct esp_hf_cb_param_t::ag_pkt_status_nums pkt_nums


AG callback param of ESP_HF_PKT_STAT_NUMS_GET_EVT

struct ag_pkt_status_nums
#include <esp_hf_ag_api.h> ESP_HF_PKT_STAT_NUMS_GET_EVT.

Public Members

uint32_t rx_total
the total number of packets received

uint32_t rx_correct
the total number of packets data correctly received

Espressif Systems 480 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint32_t rx_err
the total number of packets data with possible invalid

uint32_t rx_none
the total number of packets data no received

uint32_t rx_lost
the total number of packets data partially lost

uint32_t tx_total
the total number of packets send

uint32_t tx_discarded
the total number of packets send lost

struct hf_ata_rep_param
#include <esp_hf_ag_api.h> ESP_HF_ATA_RESPONSE_EVT.

Public Members

esp_bd_addr_t remote_addr
remote bluetooth device address

struct hf_audio_stat_param
#include <esp_hf_ag_api.h> ESP_HF_AUDIO_STATE_EVT.

Public Members

esp_bd_addr_t remote_addr
Remote bluetooth device address

esp_hf_audio_state_t state
Audio connection state

uint16_t sync_conn_handle
(e)SCO connection handle

struct hf_bcs_rep_param
#include <esp_hf_ag_api.h> ESP_HF_BCS_RESPONSE_EVT.

Public Members

esp_bd_addr_t remote_addr
Remote bluetooth device address

Espressif Systems 481 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_hf_wbs_config_t mode
codec mode CVSD or mSBC

struct hf_chup_rep_param
#include <esp_hf_ag_api.h> ESP_HF_CHUP_RESPONSE_EVT.

Public Members

esp_bd_addr_t remote_addr
remote bluetooth device address

struct hf_cind_rep_param
#include <esp_hf_ag_api.h> ESP_HF_CIND_RESPONSE_EVT.

Public Members

esp_bd_addr_t remote_addr
remote bluetooth device address

struct hf_clcc_rep_param
#include <esp_hf_ag_api.h> ESP_HF_CLCC_RESPONSE_EVT.

Public Members

esp_bd_addr_t remote_addr
remote bluetooth device address

struct hf_cnum_rep_param
#include <esp_hf_ag_api.h> ESP_HF_CNUM_RESPONSE_EVT.

Public Members

esp_bd_addr_t remote_addr
remote bluetooth device address

struct hf_conn_stat_param
#include <esp_hf_ag_api.h> ESP_HF_CONNECTION_STATE_EVT.

Public Members

esp_bd_addr_t remote_bda
Remote bluetooth device address

esp_hf_connection_state_t state
Connection state

Espressif Systems 482 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint32_t peer_feat
HF supported features

uint32_t chld_feat
AG supported features on call hold and multiparty services

struct hf_cops_rep_param
#include <esp_hf_ag_api.h> ESP_HF_COPS_RESPONSE_EVT.

Public Members

esp_bd_addr_t remote_addr
remote bluetooth device address

struct hf_ind_upd_param
#include <esp_hf_ag_api.h> ESP_HF_IND_UPDATE_EVT.

Public Members

esp_bd_addr_t remote_addr
remote bluetooth device address

struct hf_nrec_param
#include <esp_hf_ag_api.h> ESP_HF_NREC_RESPONSE_EVT.

Public Members

esp_bd_addr_t remote_addr
Remote bluetooth device address

esp_hf_nrec_t state
NREC enabled or disabled

struct hf_out_call_param
#include <esp_hf_ag_api.h> ESP_HF_DIAL_EVT.

Public Members

esp_bd_addr_t remote_addr
remote bluetooth device address

esp_hf_dial_type_t type
dial type

char *num_or_loc
location in phone memory

Espressif Systems 483 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct hf_unat_rep_param
#include <esp_hf_ag_api.h> ESP_HF_UNAT_RESPONSE_EVT.

Public Members

esp_bd_addr_t remote_addr
Remote bluetooth device address

char *unat
Unknown AT command string

struct hf_volume_control_param
#include <esp_hf_ag_api.h> ESP_HF_VOLUME_CONTROL_EVT.

Public Members

esp_bd_addr_t remote_addr
Remote bluetooth device address

esp_hf_volume_type_t type
Volume control target, speaker or microphone

int volume
Gain, ranges from 0 to 15

struct hf_vra_rep_param
#include <esp_hf_ag_api.h> ESP_HF_BVRA_RESPONSE_EVT.

Public Members

esp_bd_addr_t remote_addr
Remote bluetooth device address

esp_hf_vr_state_t value
Voice recognition state

struct hf_vts_rep_param
#include <esp_hf_ag_api.h> ESP_HF_VTS_RESPONSE_EVT.

Public Members

esp_bd_addr_t remote_addr
Remote bluetooth device address

char *code
MTF code from HF Client

Espressif Systems 484 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct hf_wbs_rep_param
#include <esp_hf_ag_api.h> ESP_HF_WBS_RESPONSE_EVT.

Public Members

esp_bd_addr_t remote_addr
Remote bluetooth device address

esp_hf_wbs_config_t codec
codec mode CVSD or mSBC

Macros

ESP_HF_PEER_FEAT_3WAY

ESP_HF_PEER_FEAT_ECNR

ESP_HF_PEER_FEAT_VREC

ESP_HF_PEER_FEAT_INBAND

ESP_HF_PEER_FEAT_VTAG

ESP_HF_PEER_FEAT_REJECT

ESP_HF_PEER_FEAT_ECS

ESP_HF_PEER_FEAT_ECC

ESP_HF_PEER_FEAT_EXTERR

ESP_HF_PEER_FEAT_CODEC

ESP_HF_PEER_FEAT_HF_IND

ESP_HF_PEER_FEAT_ESCO_S4

ESP_HF_CHLD_FEAT_REL

ESP_HF_CHLD_FEAT_REL_ACC

ESP_HF_CHLD_FEAT_REL_X

ESP_HF_CHLD_FEAT_HOLD_ACC

ESP_HF_CHLD_FEAT_PRIV_X

Espressif Systems 485 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_HF_CHLD_FEAT_MERGE

ESP_HF_CHLD_FEAT_MERGE_DETACH

Type Definitions

typedef void (*esp_hf_incoming_data_cb_t)(const uint8_t *buf, uint32_t len)


AG incoming data callback function, the callback is useful in case of Voice Over HCI.
Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer
is allocated inside bluetooth protocol stack and will be released after invoke of the callback is
finished.
Param len [in] : size(in bytes) in buf

typedef uint32_t (*esp_hf_outgoing_data_cb_t)(uint8_t *buf, uint32_t len)


AG outgoing data callback function, the callback is useful in case of Voice Over HCI. Once audio connection
is set up and the application layer has prepared data to send, the lower layer will call this function to read data
and then send. This callback is supposed to be implemented as non-blocking, and if data is not enough, return
value 0 is supposed.
Param buf [in] : pointer to incoming data(payload of HCI synchronous data packet), the buffer
is allocated inside bluetooth protocol stack and will be released after invoke of the callback is
finished.
Param len [in] : size(in bytes) in buf
Return length of data successfully read

typedef void (*esp_hf_cb_t)(esp_hf_cb_event_t event, esp_hf_cb_param_t *param)


HF AG callback function type.
Param event : Event type
Param param : Pointer to callback parameter

Enumerations

enum esp_hf_cb_event_t
HF callback events.
Values:

enumerator ESP_HF_CONNECTION_STATE_EVT
Connection state changed event

enumerator ESP_HF_AUDIO_STATE_EVT
Audio connection state change event

enumerator ESP_HF_BVRA_RESPONSE_EVT
Voice recognition state change event

enumerator ESP_HF_VOLUME_CONTROL_EVT
Audio volume control command from HF Client, provided by +VGM or +VGS message

enumerator ESP_HF_UNAT_RESPONSE_EVT
Unknown AT cmd Response

Espressif Systems 486 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HF_IND_UPDATE_EVT
Indicator Update Event

enumerator ESP_HF_CIND_RESPONSE_EVT
Call And Device Indicator Response

enumerator ESP_HF_COPS_RESPONSE_EVT
Current operator information

enumerator ESP_HF_CLCC_RESPONSE_EVT
List of current calls notification

enumerator ESP_HF_CNUM_RESPONSE_EVT
Subscriber information response from HF Client

enumerator ESP_HF_VTS_RESPONSE_EVT
Enable or not DTMF

enumerator ESP_HF_NREC_RESPONSE_EVT
Enable or not NREC

enumerator ESP_HF_ATA_RESPONSE_EVT
Answer an Incoming Call

enumerator ESP_HF_CHUP_RESPONSE_EVT
Reject an Incoming Call

enumerator ESP_HF_DIAL_EVT
Origin an outgoing call with specific number or the dial the last number

enumerator ESP_HF_WBS_RESPONSE_EVT
Codec Status

enumerator ESP_HF_BCS_RESPONSE_EVT
Final Codec Choice

enumerator ESP_HF_PKT_STAT_NUMS_GET_EVT
Request number of packet different status

enum esp_hf_dial_type_t
Dial type of ESP_HF_DIAL_EVT.
Values:

enumerator ESP_HF_DIAL_NUM
Dial with a phone number

enumerator ESP_HF_DIAL_VOIP
Dial with VoIP

Espressif Systems 487 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HF_DIAL_MEM
Dial with a memory position

Bluetooth® HID Device API

Overview A Bluetooth HID device is a device providing the service of human or other data input and output to and
from a Bluetooth HID Host. Users can use the Bluetooth HID Device APIs to make devices like keyboards, mice,
joysticks and so on.

Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the fol-
lowing application:
• This is an example of Bluetooth HID mouse device. The device running this example can be discovered and
connected by a Bluetooth HID Host device such as a PC, and the pointer will move left and right after HID
connection is established - bluetooth/bluedroid/classic_bt/bt_hid_mouse_device

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_hidd_api.h

Functions
esp_err_t esp_bt_hid_device_register_callback(esp_hd_cb_t callback)
This function is called to init callbacks with HID device module.
Parameters callback –[in] pointer to the init callback function.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_init(void)
Initializes HIDD interface. This function should be called after
esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be
called after esp_bt_hid_device_register_callback. When the operation is complete, the callback function will
be called with ESP_HIDD_INIT_EVT.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_deinit(void)
De-initializes HIDD interface. This function should be called after
esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be
called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called
with ESP_HIDD_DEINIT_EVT.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_register_app(esp_hidd_app_param_t *app_param,
esp_hidd_qos_param_t *in_qos, esp_hidd_qos_param_t
*out_qos)
Registers HIDD parameters with SDP and sets l2cap Quality of Service. This function should be called after
esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called

Espressif Systems 488 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with
ESP_HIDD_REGISTER_APP_EVT.
Parameters
• app_param –[in] HIDD parameters
• in_qos –[in] incoming QoS parameters
• out_qos –[in] outgoing QoS parameters
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_unregister_app(void)
Removes HIDD parameters from SDP and resets l2cap Quality of Service. This function should be called
after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be
called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called
with ESP_HIDD_UNREGISTER_APP_EVT.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_connect(esp_bd_addr_t bd_addr)
Connects to the peer HID Host with virtual cable. This function should be called after
esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be
called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called
with ESP_HIDD_OPEN_EVT.
Parameters bd_addr –[in] Remote host bluetooth device address.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_disconnect(void)
Disconnects from the currently connected HID Host. This function should be called after
esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be
called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called
with ESP_HIDD_CLOSE_EVT.

Note: The disconnect operation will not remove the virtually cabled device. If the connect request from the
different HID Host, it will reject the request.

Returns
• ESP_OK: success
• other: failed

esp_err_t esp_bt_hid_device_send_report(esp_hidd_report_type_t type, uint8_t id, uint16_t len,


uint8_t *data)
Sends HID report to the currently connected HID Host. This function should be called after
esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be called
after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called with
ESP_HIDD_SEND_REPORT_EVT.
Parameters
• type –[in] type of report
• id –[in] report id as defined by descriptor
• len –[in] length of report
• data –[in] report data
Returns
• ESP_OK: success

Espressif Systems 489 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

• other: failed
esp_err_t esp_bt_hid_device_report_error(esp_hidd_handshake_error_t error)
Sends HID Handshake with error info for invalid set_report to the currently connected HID Host. This function
should be called after esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success,
and should be called after esp_bt_hid_device_init(). When the operation is complete, the callback function
will be called with ESP_HIDD_REPORT_ERR_EVT.
Parameters error –[in] type of error
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_device_virtual_cable_unplug(void)
Remove the virtually cabled device. This function should be called after
esp_bluedroid_init()/esp_bluedroid_init_with_cfg() and esp_bluedroid_enable() success, and should be
called after esp_bt_hid_device_init(). When the operation is complete, the callback function will be called
with ESP_HIDD_VC_UNPLUG_EVT.

Note: If the connection exists, then HID Device will send a VIRTUAL_CABLE_UNPLUG control command
to the peer HID Host, and the connection will be destroyed. If the connection does not exist, then HID Device
will only unplug on it’s single side. Once the unplug operation is success, the related pairing and bonding
information will be removed, then the HID Device can accept connection request from the different HID Host,

Returns - ESP_OK: success


• other: failed

Unions

union esp_hidd_cb_param_t
#include <esp_hidd_api.h> HID device callback parameters union.

Public Members

struct esp_hidd_cb_param_t::hidd_init_evt_param init


HIDD callback param of ESP_HIDD_INIT_EVT

struct esp_hidd_cb_param_t::hidd_deinit_evt_param deinit


HIDD callback param of ESP_HIDD_DEINIT_EVT

struct esp_hidd_cb_param_t::hidd_register_app_evt_param register_app


HIDD callback param of ESP_HIDD_REGISTER_APP_EVT

struct esp_hidd_cb_param_t::hidd_unregister_app_evt_param unregister_app


HIDD callback param of ESP_HIDD_UNREGISTER_APP_EVT

struct esp_hidd_cb_param_t::hidd_open_evt_param open


HIDD callback param of ESP_HIDD_OPEN_EVT

struct esp_hidd_cb_param_t::hidd_close_evt_param close


HIDD callback param of ESP_HIDD_CLOSE_EVT

Espressif Systems 490 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_hidd_cb_param_t::hidd_send_report_evt_param send_report


HIDD callback param of ESP_HIDD_SEND_REPORT_EVT

struct esp_hidd_cb_param_t::hidd_report_err_evt_param report_err


HIDD callback param of ESP_HIDD_REPORT_ERR_EVT

struct esp_hidd_cb_param_t::hidd_get_report_evt_param get_report


HIDD callback param of ESP_HIDD_GET_REPORT_EVT

struct esp_hidd_cb_param_t::hidd_set_report_evt_param set_report


HIDD callback param of ESP_HIDD_SET_REPORT_EVT

struct esp_hidd_cb_param_t::hidd_set_protocol_evt_param set_protocol


HIDD callback param of ESP_HIDD_SET_PROTOCOL_EVT

struct esp_hidd_cb_param_t::hidd_intr_data_evt_param intr_data


HIDD callback param of ESP_HIDD_INTR_DATA_EVT

struct esp_hidd_cb_param_t::hidd_vc_unplug_param vc_unplug


HIDD callback param of ESP_HIDD_VC_UNPLUG_EVT

struct hidd_close_evt_param
#include <esp_hidd_api.h> ESP_HIDD_CLOSE_EVT.

Public Members

esp_hidd_status_t status
operation status

esp_hidd_connection_state_t conn_status
connection status

struct hidd_deinit_evt_param
#include <esp_hidd_api.h> ESP_HIDD_DEINIT_EVT.

Public Members

esp_hidd_status_t status
operation status

struct hidd_get_report_evt_param
#include <esp_hidd_api.h> ESP_HIDD_GET_REPORT_EVT.

Public Members

Espressif Systems 491 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_hidd_report_type_t report_type
report type

uint8_t report_id
report id

uint16_t buffer_size
buffer size

struct hidd_init_evt_param
#include <esp_hidd_api.h> ESP_HIDD_INIT_EVT.

Public Members

esp_hidd_status_t status
operation status

struct hidd_intr_data_evt_param
#include <esp_hidd_api.h> ESP_HIDD_INTR_DATA_EVT.

Public Members

uint8_t report_id
interrupt channel report id

uint16_t len
interrupt channel report data length

uint8_t *data
interrupt channel report data pointer

struct hidd_open_evt_param
#include <esp_hidd_api.h> ESP_HIDD_OPEN_EVT.

Public Members

esp_hidd_status_t status
operation status

esp_hidd_connection_state_t conn_status
connection status

esp_bd_addr_t bd_addr
host address

struct hidd_register_app_evt_param
#include <esp_hidd_api.h> ESP_HIDD_REGISTER_APP_EVT.

Espressif Systems 492 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_hidd_status_t status
operation status

bool in_use
indicate whether use virtual cable plug host address

esp_bd_addr_t bd_addr
host address

struct hidd_report_err_evt_param
#include <esp_hidd_api.h> ESP_HIDD_REPORT_ERR_EVT.

Public Members

esp_hidd_status_t status
operation status

uint8_t reason
lower layer failed reason(ref hiddefs.h)

struct hidd_send_report_evt_param
#include <esp_hidd_api.h> ESP_HIDD_SEND_REPORT_EVT.

Public Members

esp_hidd_status_t status
operation status

uint8_t reason
lower layer failed reason(ref hiddefs.h)

esp_hidd_report_type_t report_type
report type

uint8_t report_id
report id

struct hidd_set_protocol_evt_param
#include <esp_hidd_api.h> ESP_HIDD_SET_PROTOCOL_EVT.

Public Members

esp_hidd_protocol_mode_t protocol_mode
protocol mode

Espressif Systems 493 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct hidd_set_report_evt_param
#include <esp_hidd_api.h> ESP_HIDD_SET_REPORT_EVT.

Public Members

esp_hidd_report_type_t report_type
report type

uint8_t report_id
report id

uint16_t len
set_report data length

uint8_t *data
set_report data pointer

struct hidd_unregister_app_evt_param
#include <esp_hidd_api.h> ESP_HIDD_UNREGISTER_APP_EVT.

Public Members

esp_hidd_status_t status
operation status

struct hidd_vc_unplug_param
#include <esp_hidd_api.h> ESP_HIDD_VC_UNPLUG_EVT.

Public Members

esp_hidd_status_t status
operation status

esp_hidd_connection_state_t conn_status
connection status

Structures

struct esp_hidd_app_param_t
HID device characteristics for SDP server.

Public Members

const char *name


service name

Espressif Systems 494 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

const char *description


service description

const char *provider


provider name

uint8_t subclass
HID device subclass

uint8_t *desc_list
HID descriptor list

int desc_list_len
size in bytes of HID descriptor list

struct esp_hidd_qos_param_t
HIDD Quality of Service parameters negotiated over L2CAP.

Public Members

uint8_t service_type
the level of service, 0 indicates no traffic

uint32_t token_rate
token rate in bytes per second, 0 indicates “don’t care”

uint32_t token_bucket_size
limit on the burstness of the application data

uint32_t peak_bandwidth
bytes per second, value 0 indicates “don’t care”

uint32_t access_latency
maximum acceptable delay in microseconds

uint32_t delay_variation
the difference in microseconds between the max and min delay

Macros

ESP_HID_CLASS_UNKNOWN
subclass of hid device
unknown HID device subclass

ESP_HID_CLASS_JOS
joystick

ESP_HID_CLASS_GPD
game pad

Espressif Systems 495 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_HID_CLASS_RMC
remote control

ESP_HID_CLASS_SED
sensing device

ESP_HID_CLASS_DGT
digitizer tablet

ESP_HID_CLASS_CDR
card reader

ESP_HID_CLASS_KBD
keyboard

ESP_HID_CLASS_MIC
pointing device

ESP_HID_CLASS_COM
combo keyboard/pointing

Type Definitions

typedef void (*esp_hd_cb_t)(esp_hidd_cb_event_t event, esp_hidd_cb_param_t *param)


HID device callback function type.
Param event Event type
Param param Point to callback parameter, currently is union type

Enumerations

enum esp_hidd_handshake_error_t
HIDD handshake result code.
Values:

enumerator ESP_HID_PAR_HANDSHAKE_RSP_SUCCESS
successful

enumerator ESP_HID_PAR_HANDSHAKE_RSP_NOT_READY
not ready, device is too busy to accept data

enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_INVALID_REP_ID
invalid report ID

enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_UNSUPPORTED_REQ
device does not support the request

enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_INVALID_PARAM
parameter value is out of range or inappropriate

Espressif Systems 496 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_UNKNOWN
device could not identify the error condition

enumerator ESP_HID_PAR_HANDSHAKE_RSP_ERR_FATAL
restart is essential to resume functionality

enum esp_hidd_report_type_t
HIDD report types.
Values:

enumerator ESP_HIDD_REPORT_TYPE_OTHER
unknown report type

enumerator ESP_HIDD_REPORT_TYPE_INPUT
input report

enumerator ESP_HIDD_REPORT_TYPE_OUTPUT
output report

enumerator ESP_HIDD_REPORT_TYPE_FEATURE
feature report

enumerator ESP_HIDD_REPORT_TYPE_INTRDATA
special value for reports to be sent on interrupt channel, INPUT is assumed

enum esp_hidd_connection_state_t
HIDD connection state.
Values:

enumerator ESP_HIDD_CONN_STATE_CONNECTED
HID connection established

enumerator ESP_HIDD_CONN_STATE_CONNECTING
connection to remote Bluetooth device

enumerator ESP_HIDD_CONN_STATE_DISCONNECTED
connection released

enumerator ESP_HIDD_CONN_STATE_DISCONNECTING
disconnecting to remote Bluetooth device

enumerator ESP_HIDD_CONN_STATE_UNKNOWN
unknown connection state

enum esp_hidd_protocol_mode_t
HID device protocol modes.
Values:

Espressif Systems 497 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HIDD_REPORT_MODE
Report Protocol Mode

enumerator ESP_HIDD_BOOT_MODE
Boot Protocol Mode

enumerator ESP_HIDD_UNSUPPORTED_MODE
unsupported

enum esp_hidd_boot_report_id_t
HID Boot Protocol report IDs.
Values:

enumerator ESP_HIDD_BOOT_REPORT_ID_KEYBOARD
report ID of Boot Protocol keyboard report

enumerator ESP_HIDD_BOOT_REPORT_ID_MOUSE
report ID of Boot Protocol mouse report

enum [anonymous]
HID Boot Protocol report size including report ID.
Values:

enumerator ESP_HIDD_BOOT_REPORT_SIZE_KEYBOARD
report size of Boot Protocol keyboard report

enumerator ESP_HIDD_BOOT_REPORT_SIZE_MOUSE
report size of Boot Protocol mouse report

enum esp_hidd_cb_event_t
HID device callback function events.
Values:

enumerator ESP_HIDD_INIT_EVT
When HID device is initialized, the event comes

enumerator ESP_HIDD_DEINIT_EVT
When HID device is deinitialized, the event comes

enumerator ESP_HIDD_REGISTER_APP_EVT
When HID device application registered, the event comes

enumerator ESP_HIDD_UNREGISTER_APP_EVT
When HID device application unregistered, the event comes

enumerator ESP_HIDD_OPEN_EVT
When HID device connection to host opened, the event comes

Espressif Systems 498 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HIDD_CLOSE_EVT
When HID device connection to host closed, the event comes

enumerator ESP_HIDD_SEND_REPORT_EVT
When HID device send report to lower layer, the event comes

enumerator ESP_HIDD_REPORT_ERR_EVT
When HID device report handshanke error to lower layer, the event comes

enumerator ESP_HIDD_GET_REPORT_EVT
When HID device receives GET_REPORT request from host, the event comes

enumerator ESP_HIDD_SET_REPORT_EVT
When HID device receives SET_REPORT request from host, the event comes

enumerator ESP_HIDD_SET_PROTOCOL_EVT
When HID device receives SET_PROTOCOL request from host, the event comes

enumerator ESP_HIDD_INTR_DATA_EVT
When HID device receives DATA from host on intr, the event comes

enumerator ESP_HIDD_VC_UNPLUG_EVT
When HID device initiates Virtual Cable Unplug, the event comes

enumerator ESP_HIDD_API_ERR_EVT
When HID device has API error, the event comes

enum esp_hidd_status_t
Values:

enumerator ESP_HIDD_SUCCESS

enumerator ESP_HIDD_ERROR
general ESP HD error

enumerator ESP_HIDD_NO_RES
out of system resources

enumerator ESP_HIDD_BUSY
Temporarily can not handle this request.

enumerator ESP_HIDD_NO_DATA
No data.

enumerator ESP_HIDD_NEED_INIT
HIDD module shall init first

enumerator ESP_HIDD_NEED_DEINIT
HIDD module shall deinit first

Espressif Systems 499 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HIDD_NEED_REG
HIDD module shall register first

enumerator ESP_HIDD_NEED_DEREG
HIDD module shall deregister first

enumerator ESP_HIDD_NO_CONNECTION
connection may have been closed

Bluetooth® HID Host API

Overview A Bluetooth HID host is a device or software that is capable of connecting and communicating with
Bluetooth HID devices, such as keyboards, mice. Users can use the Bluetooth HID Host APIs to send output data or
control commands to the HID devices, enabling them to control the behavior or settings of the devices.

Application Example Check bluetooth folder in ESP-IDF examples, which contains the following application:
• Example bluetooth/esp_hid_host is implemented using the generic esp_hid APIs. esp_hid APIs are build upon
the Bluetooth HID APIs and can be a reference.

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_hidh_api.h

Functions
esp_err_t esp_bt_hid_host_register_callback(esp_hh_cb_t callback)
This function is called to init callbacks with HID host module.
Parameters callback –[in] pointer to the init callback function.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_host_init(void)
This function initializes HID host. This function should be called after esp_bluedroid_enable()
and esp_bluedroid_init()/esp_bluedroid_init_with_cfg() success, and should be called after
esp_bt_hid_host_register_callback(). When the operation is complete the callback function will be
called with ESP_HIDH_INIT_EVT.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_host_deinit(void)
Closes the interface. This function should be called after esp_bluedroid_enable() and
esp_bluedroid_init()/esp_bluedroid_init_with_cfg() success, and should be called after esp_bt_hid_host_init().
When the operation is complete the callback function will be called with ESP_HIDH_DEINIT_EVT.
Returns - ESP_OK: success
• other: failed

Espressif Systems 500 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_bt_hid_host_connect(esp_bd_addr_t bd_addr)


Connect to HID device. When the operation is complete the callback function will be called with
ESP_HIDH_OPEN_EVT.
Parameters bd_addr –[in] Remote device bluetooth device address.
Returns - ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_host_disconnect(esp_bd_addr_t bd_addr)
Disconnect from HID device. When the operation is complete the callback function will be called with
ESP_HIDH_CLOSE_EVT.
Parameters bd_addr –[in] Remote device bluetooth device address.
Returns - ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_host_virtual_cable_unplug(esp_bd_addr_t bd_addr)
Virtual UnPlug (VUP) the specified HID device. When the operation is complete the callback function will be
called with ESP_HIDH_VC_UNPLUG_EVT.
Parameters bd_addr –[in] Remote device bluetooth device address.
Returns - ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_host_set_info(esp_bd_addr_t bd_addr, esp_hidh_hid_info_t *hid_info)
Set the HID device descriptor for the specified HID device. When the operation is complete the callback
function will be called with ESP_HIDH_SET_INFO_EVT.
Parameters
• bd_addr –[in] Remote device bluetooth device address.
• hid_info –[in] HID device descriptor structure.
Returns - ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_host_get_protocol(esp_bd_addr_t bd_addr)
Get the HID proto mode. When the operation is complete the callback function will be called with
ESP_HIDH_GET_PROTO_EVT.
Parameters bd_addr –[in] Remote device bluetooth device address.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_host_set_protocol(esp_bd_addr_t bd_addr, esp_hidh_protocol_mode_t
protocol_mode)
Set the HID proto mode. When the operation is complete the callback function will be called with
ESP_HIDH_SET_PROTO_EVT.
Parameters
• bd_addr –[in] Remote device bluetooth device address.
• protocol_mode –[in] Protocol mode type.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_host_get_idle(esp_bd_addr_t bd_addr)
Get the HID Idle Time. When the operation is complete the callback function will be called with
ESP_HIDH_GET_IDLE_EVT.
Parameters bd_addr –[in] Remote device bluetooth device address.
Returns
• ESP_OK: success
• other: failed

Espressif Systems 501 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_bt_hid_host_set_idle(esp_bd_addr_t bd_addr, uint16_t idle_time)


Set the HID Idle Time. When the operation is complete the callback function will be called with
ESP_HIDH_SET_IDLE_EVT.
Parameters
• bd_addr –[in] Remote device bluetooth device address.
• idle_time –[in] Idle time rate
Returns - ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_host_get_report(esp_bd_addr_t bd_addr, esp_hidh_report_type_t report_type,
uint8_t report_id, int buffer_size)
Send a GET_REPORT to HID device. When the operation is complete the callback function will be called
with ESP_HIDH_GET_RPT_EVT.
Parameters
• bd_addr –[in] Remote device bluetooth device address.
• report_type –[in] Report type
• report_id –[in] Report id
• buffer_size –[in] Buffer size
Returns - ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_host_set_report(esp_bd_addr_t bd_addr, esp_hidh_report_type_t report_type,
uint8_t *report, size_t len)
Send a SET_REPORT to HID device. When the operation is complete the callback function will be called
with ESP_HIDH_SET_RPT_EVT.
Parameters
• bd_addr –[in] Remote device bluetooth device address.
• report_type –[in] Report type
• report –[in] Report data pointer
• len –[in] Report data length
Returns - ESP_OK: success
• other: failed
esp_err_t esp_bt_hid_host_send_data(esp_bd_addr_t bd_addr, uint8_t *data, size_t len)
Send data to HID device. When the operation is complete the callback function will be called with
ESP_HIDH_DATA_EVT.
Parameters
• bd_addr –[in] Remote device bluetooth device address.
• data –[in] Data pointer
• len –[in] Data length
Returns - ESP_OK: success
• other: failed

Unions

union esp_hidh_cb_param_t
#include <esp_hidh_api.h> HID host callback parameters union.

Public Members

struct esp_hidh_cb_param_t::hidh_init_evt_param init


HIDH callback param of ESP_HIDH_INIT_EVT

Espressif Systems 502 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct esp_hidh_cb_param_t::hidh_uninit_evt_param deinit


HIDH callback param of ESP_HIDH_DEINIT_EVT

struct esp_hidh_cb_param_t::hidh_open_evt_param open


HIDH callback param of ESP_HIDH_OPEN_EVT

struct esp_hidh_cb_param_t::hidh_close_evt_param close


HIDH callback param of ESP_HIDH_CLOSE_EVT

struct esp_hidh_cb_param_t::hidh_unplug_evt_param unplug


HIDH callback param of ESP_HIDH_VC_UNPLUG_EVT

struct esp_hidh_cb_param_t::hidh_get_proto_evt_param get_proto


HIDH callback param of ESP_HIDH_GET_PROTO_EVT

struct esp_hidh_cb_param_t::hidh_set_proto_evt_param set_proto


HIDH callback param of ESP_HIDH_SET_PROTO_EVT

struct esp_hidh_cb_param_t::hidh_get_rpt_evt_param get_rpt


HIDH callback param of ESP_HIDH_GET_RPT_EVT

struct esp_hidh_cb_param_t::hidh_set_rpt_evt_param set_rpt


HIDH callback param of ESP_HIDH_SET_RPT_EVT

struct esp_hidh_cb_param_t::hidh_send_data_evt_param send_data


HIDH callback param of ESP_HIDH_DATA_EVT

struct esp_hidh_cb_param_t::hidh_get_idle_evt_param get_idle


HIDH callback param of ESP_HIDH_GET_IDLE_EVT

struct esp_hidh_cb_param_t::hidh_set_idle_evt_param set_idle


HIDH callback param of ESP_HIDH_SET_IDLE_EVT

struct esp_hidh_cb_param_t::hidh_data_ind_evt_param data_ind


HIDH callback param of ESP_HIDH_DATA_IND_EVT

struct esp_hidh_cb_param_t::hidh_add_dev_evt_param add_dev


HIDH callback param of ESP_HIDH_ADD_DEV_EVT

struct esp_hidh_cb_param_t::hidh_rmv_dev_evt_param rmv_dev


HIDH callback param of ESP_HIDH_RMV_DEV_EVT

struct esp_hidh_cb_param_t::hidh_get_dscp_evt_param dscp


HIDH callback param of ESP_HIDH_GET_DSCP_EVT

struct esp_hidh_cb_param_t::hidh_set_info_evt_param set_info


HIDH callback param of ESP_HIDH_SET_INFO_EVT

struct hidh_add_dev_evt_param
#include <esp_hidh_api.h> ESP_HIDH_ADD_DEV_EVT.

Espressif Systems 503 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_hidh_status_t status
operation status

uint8_t handle
device handle

esp_bd_addr_t bd_addr
device address

struct hidh_close_evt_param
#include <esp_hidh_api.h> ESP_HIDH_CLOSE_EVT.

Public Members

esp_hidh_status_t status
operation status

uint8_t reason
lower layer failed reason(ref hiddefs.h)

esp_hidh_connection_state_t conn_status
connection status

uint8_t handle
device handle

struct hidh_data_ind_evt_param
#include <esp_hidh_api.h> ESP_HIDH_DATA_IND_EVT.

Public Members

esp_hidh_status_t status
operation status

uint8_t handle
device handle

esp_hidh_protocol_mode_t proto_mode
protocol mode

uint16_t len
data length

uint8_t *data
data pointer

Espressif Systems 504 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

struct hidh_get_dscp_evt_param
#include <esp_hidh_api.h> ESP_HIDH_GET_DSCP_EVT.

Public Members

esp_hidh_status_t status
operation status

uint8_t handle
device handle

bool added
Indicate if added

uint16_t vendor_id
Vendor ID

uint16_t product_id
Product ID

uint16_t version
Version

uint16_t ssr_max_latency
SSR max latency in slots

uint16_t ssr_min_tout
SSR min timeout in slots

uint8_t ctry_code
Country Code

uint16_t dl_len
Device descriptor length

uint8_t *dsc_list
Device descriptor pointer

struct hidh_get_idle_evt_param
#include <esp_hidh_api.h> ESP_HIDH_GET_IDLE_EVT.

Public Members

esp_hidh_status_t status
operation status

Espressif Systems 505 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint8_t handle
device handle

uint8_t idle_rate
idle rate

struct hidh_get_proto_evt_param
#include <esp_hidh_api.h> ESP_HIDH_GET_PROTO_EVT.

Public Members

esp_hidh_status_t status
operation status

uint8_t handle
device handle

esp_hidh_protocol_mode_t proto_mode
protocol mode

struct hidh_get_rpt_evt_param
#include <esp_hidh_api.h> ESP_HIDH_GET_RPT_EVT.

Public Members

esp_hidh_status_t status
operation status

uint8_t handle
device handle

uint16_t len
data length

uint8_t *data
data pointer

struct hidh_init_evt_param
#include <esp_hidh_api.h> ESP_HIDH_INIT_EVT.

Public Members

esp_hidh_status_t status
status

struct hidh_open_evt_param
#include <esp_hidh_api.h> ESP_HIDH_OPEN_EVT.

Espressif Systems 506 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_hidh_status_t status
operation status

esp_hidh_connection_state_t conn_status
connection status

bool is_orig
indicate if host intiate the connection

uint8_t handle
device handle

esp_bd_addr_t bd_addr
device address

struct hidh_rmv_dev_evt_param
#include <esp_hidh_api.h> ESP_HIDH_RMV_DEV_EVT.

Public Members

esp_hidh_status_t status
operation status

uint8_t handle
device handle

esp_bd_addr_t bd_addr
device address

struct hidh_send_data_evt_param
#include <esp_hidh_api.h> ESP_HIDH_DATA_EVT.

Public Members

esp_hidh_status_t status
operation status

uint8_t handle
device handle

uint8_t reason
lower layer failed reason(ref hiddefs.h)

struct hidh_set_idle_evt_param
#include <esp_hidh_api.h> ESP_HIDH_SET_IDLE_EVT.

Espressif Systems 507 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_hidh_status_t status
operation status

uint8_t handle
device handle

struct hidh_set_info_evt_param
#include <esp_hidh_api.h> ESP_HIDH_SET_INFO_EVT.

Public Members

esp_hidh_status_t status
operation status

uint8_t handle
device handle

esp_bd_addr_t bd_addr
device address

struct hidh_set_proto_evt_param
#include <esp_hidh_api.h> ESP_HIDH_SET_PROTO_EVT.

Public Members

esp_hidh_status_t status
operation status

uint8_t handle
device handle

struct hidh_set_rpt_evt_param
#include <esp_hidh_api.h> ESP_HIDH_SET_RPT_EVT.

Public Members

esp_hidh_status_t status
operation status

uint8_t handle
device handle

struct hidh_uninit_evt_param
#include <esp_hidh_api.h> ESP_HIDH_DEINIT_EVT.

Espressif Systems 508 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_hidh_status_t status
status

struct hidh_unplug_evt_param
#include <esp_hidh_api.h> ESP_HIDH_VC_UNPLUG_EVT.

Public Members

esp_hidh_status_t status
operation status

esp_hidh_connection_state_t conn_status
connection status

uint8_t handle
device handle

Structures

struct esp_hidh_hid_info_t
HID device information from HID Device Service Record and Device ID Service Record.

Public Members

int attr_mask
device attribute bit mask, refer to esp_hidh_dev_attr_t

uint8_t sub_class
HID device subclass

uint8_t app_id
application ID, refer to esp_hidh_dev_app_id_t

int vendor_id
Device ID information: vendor ID

int product_id
Device ID information: product ID

int version
Device ID information: version

uint8_t ctry_code
SDP attrbutes of HID devices: HID country code (https://www.usb.org/sites/default/files/hid1_11.pdf)

Espressif Systems 509 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

int dl_len
SDP attrbutes of HID devices: HID device descriptor length

uint8_t dsc_list[BTHH_MAX_DSC_LEN]
SDP attrbutes of HID devices: HID device descriptor definition

Macros

BTHH_MAX_DSC_LEN
maximum size of HID Device report descriptor

Type Definitions

typedef void (*esp_hh_cb_t)(esp_hidh_cb_event_t event, esp_hidh_cb_param_t *param)


HID host callback function type.
Param event Event type
Param param Point to callback parameter, currently is union type

Enumerations

enum esp_hidh_connection_state_t
HID host connection state.
Values:

enumerator ESP_HIDH_CONN_STATE_CONNECTED
connected state

enumerator ESP_HIDH_CONN_STATE_CONNECTING
connecting state

enumerator ESP_HIDH_CONN_STATE_DISCONNECTED
disconnected state

enumerator ESP_HIDH_CONN_STATE_DISCONNECTING
disconnecting state

enumerator ESP_HIDH_CONN_STATE_UNKNOWN
unknown state (initial state)

enum esp_hidh_status_t
HID handshake error code and vendor-defined result code.
Values:

enumerator ESP_HIDH_OK
successful

enumerator ESP_HIDH_HS_HID_NOT_READY
handshake error: device not ready

Espressif Systems 510 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HIDH_HS_INVALID_RPT_ID
handshake error: invalid report ID

enumerator ESP_HIDH_HS_TRANS_NOT_SPT
handshake error: HID device does not support the request

enumerator ESP_HIDH_HS_INVALID_PARAM
handshake error: parameter value does not meet the expected criteria of called function or API

enumerator ESP_HIDH_HS_ERROR
handshake error: HID device could not identify the error condition

enumerator ESP_HIDH_ERR
general ESP HID Host error

enumerator ESP_HIDH_ERR_SDP
SDP error

enumerator ESP_HIDH_ERR_PROTO
SET_PROTOCOL error, only used in ESP_HIDH_OPEN_EVT callback

enumerator ESP_HIDH_ERR_DB_FULL
device database full, used in ESP_HIDH_OPEN_EVT/ESP_HIDH_ADD_DEV_EVT

enumerator ESP_HIDH_ERR_TOD_UNSPT
type of device not supported

enumerator ESP_HIDH_ERR_NO_RES
out of system resources

enumerator ESP_HIDH_ERR_AUTH_FAILED
authentication fail

enumerator ESP_HIDH_ERR_HDL
connection handle error

enumerator ESP_HIDH_ERR_SEC
encryption error

enumerator ESP_HIDH_BUSY
vendor-defined: temporarily can not handle this request

enumerator ESP_HIDH_NO_DATA
vendor-defined: no data.

enumerator ESP_HIDH_NEED_INIT
vendor-defined: HIDH module shall initialize first

Espressif Systems 511 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HIDH_NEED_DEINIT
vendor-defined: HIDH module shall de-deinitialize first

enumerator ESP_HIDH_NO_CONNECTION
vendor-defined: connection may have been closed

enum esp_hidh_protocol_mode_t
HID host protocol modes.
Values:

enumerator ESP_HIDH_BOOT_MODE
boot protocol mode

enumerator ESP_HIDH_REPORT_MODE
report protocol mode

enumerator ESP_HIDH_UNSUPPORTED_MODE
unsupported protocol mode

enum esp_hidh_report_type_t
HID host report types.
Values:

enumerator ESP_HIDH_REPORT_TYPE_OTHER
unsupported report type

enumerator ESP_HIDH_REPORT_TYPE_INPUT
input report type

enumerator ESP_HIDH_REPORT_TYPE_OUTPUT
output report type

enumerator ESP_HIDH_REPORT_TYPE_FEATURE
feature report type

enum esp_hidh_cb_event_t
HID host callback function events.
Values:

enumerator ESP_HIDH_INIT_EVT
when HID host is initialized, the event comes

enumerator ESP_HIDH_DEINIT_EVT
when HID host is deinitialized, the event comes

enumerator ESP_HIDH_OPEN_EVT
when HID host connection opened, the event comes

Espressif Systems 512 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HIDH_CLOSE_EVT
when HID host connection closed, the event comes

enumerator ESP_HIDH_GET_RPT_EVT
when Get_Report command is called, the event comes

enumerator ESP_HIDH_SET_RPT_EVT
when Set_Report command is called, the event comes

enumerator ESP_HIDH_GET_PROTO_EVT
when Get_Protocol command is called, the event comes

enumerator ESP_HIDH_SET_PROTO_EVT
when Set_Protocol command is called, the event comes

enumerator ESP_HIDH_GET_IDLE_EVT
when Get_Idle command is called, the event comes

enumerator ESP_HIDH_SET_IDLE_EVT
when Set_Idle command is called, the event comes

enumerator ESP_HIDH_GET_DSCP_EVT
when HIDH is initialized, the event comes

enumerator ESP_HIDH_ADD_DEV_EVT
when a device is added, the event comes

enumerator ESP_HIDH_RMV_DEV_EVT
when a device is removed, the event comes

enumerator ESP_HIDH_VC_UNPLUG_EVT
when virtually unplugged, the event comes

enumerator ESP_HIDH_DATA_EVT
when send data on interrupt channel, the event comes

enumerator ESP_HIDH_DATA_IND_EVT
when receive data on interrupt channel, the event comes

enumerator ESP_HIDH_SET_INFO_EVT
when set the HID device descriptor, the event comes

enum esp_hidh_dev_attr_t
HID device information from HID Device Service Record and Device ID Service Record.
Values:

enumerator ESP_HIDH_DEV_ATTR_VIRTUAL_CABLE
whether Virtual Cables is supported

Espressif Systems 513 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enumerator ESP_HIDH_DEV_ATTR_NORMALLY_CONNECTABLE
whether device is in Page Scan mode when there is no active connection

enumerator ESP_HIDH_DEV_ATTR_RECONNECT_INITIATE
whether the HID device inititates the reconnection process

enum esp_hidh_dev_app_id_t
application ID(non-zero) for each type of device
Values:

enumerator ESP_HIDH_APP_ID_MOUSE
pointing device

enumerator ESP_HIDH_APP_ID_KEYBOARD
keyboard

enumerator ESP_HIDH_APP_ID_REMOTE_CONTROL
remote control

enumerator ESP_HIDH_APP_ID_JOYSTICK
joystick

enumerator ESP_HIDH_APP_ID_GAMEPAD
gamepad

Classic Bluetooth® L2CAP API

Application Example Check bluetooth/bluedroid/classic_bt folder in ESP-IDF examples, which contains the fol-
lowing application:
• This is a BT_L2CAP demo. This demo can connect, send and receive L2CAP data blue-
tooth/bluedroid/classic_bt/bt_l2cap_client, bluetooth/bluedroid/classic_bt/bt_l2cap_server

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_l2cap_bt_api.h

Functions
esp_err_t esp_bt_l2cap_register_callback(esp_bt_l2cap_cb_t callback)
This function is called to init callbacks with L2CAP module.
Parameters callback –[in] pointer to the init callback function.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_l2cap_init(void)
This function is called to init L2CAP module. When the operation is completed, the callback function will be
called with ESP_BT_L2CAP_INIT_EVT. This function should be called after esp_bluedroid_enable() com-
pletes successfully.

Espressif Systems 514 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_l2cap_deinit(void)
This function is called to uninit l2cap module. The operation will close all active L2CAP connection
first, then the callback function will be called with ESP_BT_L2CAP_CLOSE_EVT, and the number of
ESP_BT_L2CAP_CLOSE_EVT is equal to the number of connection. When the operation is completed,
the callback function will be called with ESP_BT_L2CAP_UNINIT_EVT. This function should be called
after esp_bt_l2cap_init() completes successfully.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_l2cap_connect(esp_bt_l2cap_cntl_flags_t cntl_flag, uint16_t remote_psm,
esp_bd_addr_t peer_bd_addr)
This function makes an L2CAP connection to a remote BD Address. When the connection is initiated or
failed to initiate, the callback is called with ESP_BT_L2CAP_CL_INIT_EVT. When the connection is estab-
lished or failed, the callback is called with ESP_BT_L2CAP_OPEN_EVT. This function must be called after
esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit().
Parameters
• cntl_flag –[in] Lower 16-bit security settings mask.
• remote_psm –[in] Remote device bluetooth Profile PSM.
• peer_bd_addr –[in] Remote device bluetooth device address.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_l2cap_start_srv(esp_bt_l2cap_cntl_flags_t cntl_flag, uint16_t local_psm)
This function create a L2CAP server and starts listening for an L2CAP connection request from
a remote Bluetooth device. When the server is started successfully, the callback is called with
ESP_BT_L2CAP_START_EVT. When the connection is established, the callback is called with
ESP_BT_L2CAP_OPEN_EVT. This function must be called after esp_bt_l2cap_init() successful and before
esp_bt_l2cap_deinit().
Parameters
• cntl_flag –[in] Lower 16-bit security settings mask.
• local_psm –[in] Dynamic PSM.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_l2cap_stop_all_srv(void)
This function stops all L2CAP servers. The operation will close all active L2CAP connection first,
then the callback function will be called with ESP_BT_L2CAP_CLOSE_EVT, and the number of
ESP_BT_L2CAP_CLOSE_EVT is equal to the number of connection. When the operation is com-
pleted, the callback is called with ESP_BT_L2CAP_SRV_STOP_EVT. This function must be called after
esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit().
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_l2cap_stop_srv(uint16_t local_psm)
This function stops a specific L2CAP server. The operation will close all active L2CAP connection first on the
specific L2CAP server, then the callback function will be called with ESP_BT_L2CAP_CLOSE_EVT, and
the number of ESP_BT_L2CAP_CLOSE_EVT is equal to the number of connection. When the operation
is completed, the callback is called with ESP_BT_L2CAP_SRV_STOP_EVT. This function must be called
after esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit().

Espressif Systems 515 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Parameters local_psm –[in] Dynamic PSM.


Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_l2cap_vfs_register(void)
This function is used to register VFS. Only supports write, read and close. This function must be called after
esp_bt_l2cap_init() successful and before esp_bt_l2cap_deinit().
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_bt_l2cap_vfs_unregister(void)
This function is used to unregister VFS. This function must be called after esp_bt_l2cap_init() successful and
before esp_bt_l2cap_deinit().
Returns
• ESP_OK: success
• other: failed

Unions

union esp_bt_l2cap_cb_param_t
#include <esp_l2cap_bt_api.h> L2CAP callback parameters union.

Public Members

struct esp_bt_l2cap_cb_param_t::l2cap_init_evt_param init


L2CAP callback param of ESP_BT_L2CAP_INIT_EVT

struct esp_bt_l2cap_cb_param_t::l2cap_uninit_evt_param uninit


L2CAP callback param of ESP_BT_L2CAP_UNINIT_EVT

struct esp_bt_l2cap_cb_param_t::l2cap_open_evt_param open


L2CAP callback param of ESP_BT_L2CAP_OPEN_EVT

struct esp_bt_l2cap_cb_param_t::l2cap_close_evt_param close


L2CAP callback param of ESP_BT_L2CAP_CLOSE_EVT

struct esp_bt_l2cap_cb_param_t::l2cap_start_evt_param start


L2CAP callback param of ESP_BT_L2CAP_START_EVT

struct esp_bt_l2cap_cb_param_t::l2cap_cl_init_evt_param cl_init


L2CAP callback param of ESP_BT_L2CAP_CL_INIT_EVT

struct esp_bt_l2cap_cb_param_t::l2cap_srv_stop_evt_param srv_stop


L2CAP callback param of ESP_BT_L2CAP_SRV_STOP_EVT

struct l2cap_cl_init_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_CL_INIT_EVT.

Espressif Systems 516 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_bt_l2cap_status_t status
status

uint32_t handle
The connection handle

uint8_t sec_id
security ID used by this server

struct l2cap_close_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_CLOSE_EVT.

Public Members

esp_bt_l2cap_status_t status
status

uint32_t handle
The connection handle

bool async
FALSE, if local initiates disconnect

struct l2cap_init_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_INIT_EVT.

Public Members

esp_bt_l2cap_status_t status
status

struct l2cap_open_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_OPEN_EVT.

Public Members

esp_bt_l2cap_status_t status
status

uint32_t handle
The connection handle

int fd
File descriptor

Espressif Systems 517 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_bd_addr_t rem_bda
The peer address

int32_t tx_mtu
The transmit MTU

struct l2cap_srv_stop_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_SRV_STOP_EVT.

Public Members

esp_bt_l2cap_status_t status
status

uint8_t psm
local psm

struct l2cap_start_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_START_EVT.

Public Members

esp_bt_l2cap_status_t status
status

uint32_t handle
The connection handle

uint8_t sec_id
security ID used by this server

struct l2cap_uninit_evt_param
#include <esp_l2cap_bt_api.h> ESP_BT_L2CAP_UNINIT_EVT.

Public Members

esp_bt_l2cap_status_t status
status

Macros

ESP_BT_L2CAP_SEC_NONE
Security Setting Mask. Use these three mask mode:

a. ESP_BT_L2CAP_SEC_NONE
b. ESP_BT_L2CAP_SEC_AUTHENTICATE
c. (ESP_BT_L2CAP_SEC_ENCRYPT|ESP_BT_L2CAP_SEC_AUTHENTICATE) No security

Espressif Systems 518 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

ESP_BT_L2CAP_SEC_AUTHORIZE
Authorization required

ESP_BT_L2CAP_SEC_AUTHENTICATE
Authentication required

ESP_BT_L2CAP_SEC_ENCRYPT
Encryption required

Type Definitions

typedef uint32_t esp_bt_l2cap_cntl_flags_t

typedef void (*esp_bt_l2cap_cb_t)(esp_bt_l2cap_cb_event_t event, esp_bt_l2cap_cb_param_t *param)


L2CAP callback function type.
Param event Event type
Param param Point to callback parameter, currently is union type

Enumerations

enum esp_bt_l2cap_status_t
L2CAP operation success and failure codes.
Values:

enumerator ESP_BT_L2CAP_SUCCESS
Successful operation.

enumerator ESP_BT_L2CAP_FAILURE
Generic failure.

enumerator ESP_BT_L2CAP_BUSY
Temporarily can not handle this request.

enumerator ESP_BT_L2CAP_NO_RESOURCE
No more resource

enumerator ESP_BT_L2CAP_NEED_INIT
L2CAP module shall init first

enumerator ESP_BT_L2CAP_NEED_DEINIT
L2CAP module shall deinit first

enumerator ESP_BT_L2CAP_NO_CONNECTION
Connection may have been closed

enumerator ESP_BT_L2CAP_NO_SERVER
No server

Espressif Systems 519 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

enum esp_bt_l2cap_cb_event_t
L2CAP callback function events.
Values:

enumerator ESP_BT_L2CAP_INIT_EVT
When L2CAP is initialized, the event comes

enumerator ESP_BT_L2CAP_UNINIT_EVT
When L2CAP is deinitialized, the event comes

enumerator ESP_BT_L2CAP_OPEN_EVT
When L2CAP Client connection open, the event comes

enumerator ESP_BT_L2CAP_CLOSE_EVT
When L2CAP connection closed, the event comes

enumerator ESP_BT_L2CAP_START_EVT
When L2CAP server started, the event comes

enumerator ESP_BT_L2CAP_CL_INIT_EVT
When L2CAP client initiated a connection, the event comes

enumerator ESP_BT_L2CAP_SRV_STOP_EVT
When L2CAP server stopped, the event comes

Bluetooth® SDP APIs

Overview Bluetooth SDP reference APIs.

API Reference

Header File
• components/bt/host/bluedroid/api/include/api/esp_sdp_api.h

Functions
esp_err_t esp_sdp_register_callback(esp_sdp_cb_t callback)
This function is called to init callbacks with SDP module.
Parameters callback –[in] pointer to the init callback function.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_sdp_init(void)
This function is called to init SDP module. When the operation is completed, the callback function will be
called with ESP_SDP_INIT_EVT. This function should be called after esp_bluedroid_enable() completes suc-
cessfully.
Returns
• ESP_OK: success
• other: failed

Espressif Systems 520 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_err_t esp_sdp_deinit(void)
This function is called to de-initialize SDP module. The operation will remove all SDP records, then the
callback function will be called with ESP_SDP_REMOVE_RECORD_COMP_EVT, and the number of
ESP_SDP_REMOVE_RECORD_COMP_EVT is equal to the number of SDP records.When the operation is
completed, the callback function will be called with ESP_SDP_DEINIT_EVT. This function should be called
after esp_sdp_init() completes successfully.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_sdp_search_record(esp_bd_addr_t bd_addr, esp_bt_uuid_t uuid)
This function is called to performs service discovery for the services provided by the given peer device. When
the operation is completed, the callback function will be called with ESP_SDP_SEARCH_COMP_EVT. This
function must be called after esp_sdp_init() successful and before esp_sdp_deinit().
Parameters
• bd_addr –[in] Remote device bluetooth device address.
• uuid –[in] Service UUID of the remote device.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_sdp_create_record(esp_bluetooth_sdp_record_t *record)
This function is called to create SDP records. When the operation is completed, the callback function will be
called with ESP_SDP_CREATE_RECORD_COMP_EVT. This function must be called after esp_sdp_init()
successful and before esp_sdp_deinit().
Parameters record –[in] The SDP record to create.
Returns
• ESP_OK: success
• other: failed
esp_err_t esp_sdp_remove_record(int record_handle)
This function is called to remove a SDP record. When the operation is completed, the callback function will be
called with ESP_SDP_REMOVE_RECORD_COMP_EVT. This function must be called after esp_sdp_init()
successful and before esp_sdp_deinit().
Parameters record_handle –[in] The SDP record handle.
Returns
• ESP_OK: success
• other: failed

Unions

union esp_bluetooth_sdp_record_t
#include <esp_sdp_api.h> SDP record parameters union.

Public Members

esp_bluetooth_sdp_hdr_overlay_t hdr
General info

esp_bluetooth_sdp_mas_record_t mas
Message Access Profile - Server

Espressif Systems 521 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

esp_bluetooth_sdp_mns_record_t mns
Message Access Profile - Client (Notification Server)

esp_bluetooth_sdp_pse_record_t pse
Phone Book Profile - Server

esp_bluetooth_sdp_pce_record_t pce
Phone Book Profile - Client

esp_bluetooth_sdp_ops_record_t ops
Object Push Profile

esp_bluetooth_sdp_sap_record_t sap
SIM Access Profile

union esp_sdp_cb_param_t
#include <esp_sdp_api.h> SDP callback parameters union.

Public Members

struct esp_sdp_cb_param_t::sdp_init_evt_param init


SDP callback param of ESP_SDP_INIT_EVT

struct esp_sdp_cb_param_t::sdp_deinit_evt_param deinit


SDP callback param of ESP_SDP_DEINIT_EVT

struct esp_sdp_cb_param_t::sdp_search_evt_param search


SDP callback param of ESP_SDP_SEARCH_COMP_EVT

struct esp_sdp_cb_param_t::sdp_crate_record_evt_param create_record


SDP callback param of ESP_SDP_CREATE_RECORD_COMP_EVT

struct esp_sdp_cb_param_t::sdp_remove_record_evt_param remove_record


SDP callback param of ESP_SDP_REMOVE_RECORD_COMP_EVT

struct sdp_crate_record_evt_param
#include <esp_sdp_api.h> ESP_SDP_CREATE_RECORD_COMP_EVT.

Public Members

esp_sdp_status_t status
status

int record_handle
SDP record handle

struct sdp_deinit_evt_param
#include <esp_sdp_api.h> ESP_SDP_DEINIT_EVT.

Espressif Systems 522 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_sdp_status_t status
status

struct sdp_init_evt_param
#include <esp_sdp_api.h> ESP_SDP_INIT_EVT.

Public Members

esp_sdp_status_t status
status

struct sdp_remove_record_evt_param
#include <esp_sdp_api.h> ESP_SDP_REMOVE_RECORD_COMP_EVT.

Public Members

esp_sdp_status_t status
status

struct sdp_search_evt_param
#include <esp_sdp_api.h> ESP_SDP_SEARCH_COMP_EVT.

Public Members

esp_sdp_status_t status
status

esp_bd_addr_t remote_addr
remote device address

esp_bt_uuid_t sdp_uuid
service uuid

int record_count
Number of SDP records

esp_bluetooth_sdp_record_t *records
SDP records

Structures

struct bluetooth_sdp_hdr_overlay
Some signals need additional pointers, hence we introduce a generic way to handle these pointers.

Espressif Systems 523 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

Public Members

esp_bluetooth_sdp_types_t type
SDP type

esp_bt_uuid_t uuid
UUID type,include uuid and uuid length

uint32_t service_name_length
Service name length

char *service_name
service name

int32_t rfcomm_channel_number
rfcomm channel number, if not used set to -1

int32_t l2cap_psm
l2cap psm, if not used set to -1

int32_t profile_version
profile version

int user1_ptr_len
see esp_bluetooth_sdp_ops_record_t

uint8_t *user1_ptr
see esp_bluetooth_sdp_ops_record_t

int user2_ptr_len
see esp_bluetooth_sdp_ops_record_t

uint8_t *user2_ptr
see esp_bluetooth_sdp_ops_record_t

struct bluetooth_sdp_mas_record
Message Access Profile - Server parameters.

Public Members

esp_bluetooth_sdp_hdr_overlay_t hdr
General info

uint32_t mas_instance_id
MAS Instance ID

uint32_t supported_features
Map supported features

Espressif Systems 524 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint32_t supported_message_types
Supported message types

struct bluetooth_sdp_mns_record
Message Access Profile - Client (Notification Server) parameters.

Public Members

esp_bluetooth_sdp_hdr_overlay_t hdr
General info

uint32_t supported_features
Supported features

struct bluetooth_sdp_pse_record
Phone Book Profile - Server parameters.

Public Members

esp_bluetooth_sdp_hdr_overlay_t hdr
General info

uint32_t supported_features
Pbap Supported Features

uint32_t supported_repositories
Supported Repositories

struct bluetooth_sdp_pce_record
Phone Book Profile - Client parameters.

Public Members

esp_bluetooth_sdp_hdr_overlay_t hdr
General info

struct bluetooth_sdp_ops_record
Object Push Profile parameters.

Public Members

esp_bluetooth_sdp_hdr_overlay_t hdr
General info

int supported_formats_list_len
Supported formats list length

Espressif Systems 525 Release v5.2-dev-3065-g272b4091f1


Submit Document Feedback
Chapter 2. API Reference

uint8_t supported_formats_list[SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH]
Supported formats list

struct bluetooth_sdp_sap_record
SIM Access Profile parameters.

Public Members

esp_bluetooth_sdp_hdr_overlay_t hdr
General info

Macros

ESP_SDP_SERVER_NAME_MAX
Service name max length

SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH
OPP supported format list maximum length

Type Definitions

typedef struct bluetooth_sdp_hdr_overlay esp_bluetooth_sdp_hdr_overlay_t


Some signals need additional pointers, hence we introduce a generic way to handle these pointers.

typedef struct bluetooth_sdp_mas_record esp_bluetooth_sdp_mas_record_t


Message Access Profile - Server parameters.

typedef struct bluetooth_sdp_mns_record esp_bluetooth_sdp_mns_record_t


Message Access Profile - Client (Notification Server) parameters.

typedef struct bluetooth_sdp_pse_record esp_bluetooth_sdp_pse_record_t


Phone Book Profile - Server parameters.

typedef struct bluetooth_sdp_pce_record esp_bluetooth_