From 88cda9ff59d3ca4a8a227e7b6039597ccfa58d34 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Tue, 21 Jan 2025 17:14:16 +0200
Subject: [PATCH 001/105] feat(idf): Add initial support for IDF v5.5 and
 ESP32-C5

---
 CMakeLists.txt                    |   2 +-
 boards.txt                        | 212 ++++++++++++++++++++++++++++++
 cores/esp32/Esp.cpp               |   3 +
 cores/esp32/HardwareSerial.h      |   8 ++
 cores/esp32/esp32-hal-cpu.c       |   8 +-
 cores/esp32/esp32-hal-i2c-slave.c |   7 +-
 cores/esp32/esp32-hal-matrix.c    |   2 +
 cores/esp32/esp32-hal-misc.c      |   4 +-
 cores/esp32/esp32-hal-spi.c       |  83 ++++++------
 cores/esp32/esp32-hal-uart.c      |  22 +++-
 idf_component.yml                 |   6 +-
 libraries/SPI/src/SPI.cpp         |   2 +-
 platform.txt                      |   9 ++
 variants/esp32c5/pins_arduino.h   |  42 ++++++
 14 files changed, 357 insertions(+), 53 deletions(-)
 create mode 100644 variants/esp32c5/pins_arduino.h

diff --git a/CMakeLists.txt b/CMakeLists.txt
index d2a9162a9ba..dd9544f13e7 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -6,7 +6,7 @@
 #   idf.py build
 
 set(min_supported_idf_version "5.3.0")
-set(max_supported_idf_version "5.4.99")
+set(max_supported_idf_version "5.5.99")
 set(idf_version "${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR}.${IDF_VERSION_PATCH}")
 
 if ("${idf_version}" AND NOT "$ENV{ARDUINO_SKIP_IDF_VERSION_CHECK}")
diff --git a/boards.txt b/boards.txt
index 2afe45f50a6..ea520e60fde 100644
--- a/boards.txt
+++ b/boards.txt
@@ -161,6 +161,218 @@ esp32c2.menu.EraseFlash.all.upload.erase_cmd=-e
 
 ##############################################################
 
+esp32c5.name=ESP32C5 Dev Module
+
+esp32c5.bootloader.tool=esptool_py
+esp32c5.bootloader.tool.default=esptool_py
+
+esp32c5.upload.tool=esptool_py
+esp32c5.upload.tool.default=esptool_py
+esp32c5.upload.tool.network=esp_ota
+
+esp32c5.upload.maximum_size=1310720
+esp32c5.upload.maximum_data_size=327680
+esp32c5.upload.flags=
+esp32c5.upload.extra_flags=
+esp32c5.upload.use_1200bps_touch=false
+esp32c5.upload.wait_for_upload_port=false
+
+esp32c5.serial.disableDTR=false
+esp32c5.serial.disableRTS=false
+
+esp32c5.build.tarch=riscv32
+esp32c5.build.target=esp
+esp32c5.build.mcu=esp32c5
+esp32c5.build.core=esp32
+esp32c5.build.variant=esp32c5
+esp32c5.build.board=ESP32C5_DEV
+esp32c5.build.bootloader_addr=0x0
+
+esp32c5.build.cdc_on_boot=0
+esp32c5.build.f_cpu=240000000L
+esp32c5.build.flash_size=4MB
+esp32c5.build.flash_freq=80m
+esp32c5.build.flash_mode=qio
+esp32c5.build.boot=qio
+esp32c5.build.partitions=default
+esp32c5.build.defines=
+
+## IDE 2.0 Seems to not update the value
+esp32c5.menu.JTAGAdapter.default=Disabled
+esp32c5.menu.JTAGAdapter.default.build.copy_jtag_files=0
+esp32c5.menu.JTAGAdapter.builtin=Integrated USB JTAG
+esp32c5.menu.JTAGAdapter.builtin.build.openocdscript=esp32c5-builtin.cfg
+esp32c5.menu.JTAGAdapter.builtin.build.copy_jtag_files=1
+esp32c5.menu.JTAGAdapter.external=FTDI Adapter
+esp32c5.menu.JTAGAdapter.external.build.openocdscript=esp32c5-ftdi.cfg
+esp32c5.menu.JTAGAdapter.external.build.copy_jtag_files=1
+esp32c5.menu.JTAGAdapter.bridge=ESP USB Bridge
+esp32c5.menu.JTAGAdapter.bridge.build.openocdscript=esp32c5-bridge.cfg
+esp32c5.menu.JTAGAdapter.bridge.build.copy_jtag_files=1
+
+esp32c5.menu.CDCOnBoot.default=Disabled
+esp32c5.menu.CDCOnBoot.default.build.cdc_on_boot=0
+esp32c5.menu.CDCOnBoot.cdc=Enabled
+esp32c5.menu.CDCOnBoot.cdc.build.cdc_on_boot=1
+
+esp32c5.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)
+esp32c5.menu.PartitionScheme.default.build.partitions=default
+esp32c5.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS)
+esp32c5.menu.PartitionScheme.defaultffat.build.partitions=default_ffat
+esp32c5.menu.PartitionScheme.default_8MB=8M with spiffs (3MB APP/1.5MB SPIFFS)
+esp32c5.menu.PartitionScheme.default_8MB.build.partitions=default_8MB
+esp32c5.menu.PartitionScheme.default_8MB.upload.maximum_size=3342336
+esp32c5.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS)
+esp32c5.menu.PartitionScheme.minimal.build.partitions=minimal
+esp32c5.menu.PartitionScheme.no_fs=No FS 4MB (2MB APP x2)
+esp32c5.menu.PartitionScheme.no_fs.build.partitions=no_fs
+esp32c5.menu.PartitionScheme.no_fs.upload.maximum_size=2031616
+esp32c5.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS)
+esp32c5.menu.PartitionScheme.no_ota.build.partitions=no_ota
+esp32c5.menu.PartitionScheme.no_ota.upload.maximum_size=2097152
+esp32c5.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS)
+esp32c5.menu.PartitionScheme.noota_3g.build.partitions=noota_3g
+esp32c5.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576
+esp32c5.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS)
+esp32c5.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat
+esp32c5.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152
+esp32c5.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS)
+esp32c5.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat
+esp32c5.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576
+esp32c5.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
+esp32c5.menu.PartitionScheme.huge_app.build.partitions=huge_app
+esp32c5.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
+esp32c5.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS)
+esp32c5.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs
+esp32c5.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080
+esp32c5.menu.PartitionScheme.fatflash=16M Flash (2MB APP/12.5MB FATFS)
+esp32c5.menu.PartitionScheme.fatflash.build.partitions=ffat
+esp32c5.menu.PartitionScheme.fatflash.upload.maximum_size=2097152
+esp32c5.menu.PartitionScheme.app3M_fat9M_16MB=16M Flash (3MB APP/9.9MB FATFS)
+esp32c5.menu.PartitionScheme.app3M_fat9M_16MB.build.partitions=app3M_fat9M_16MB
+esp32c5.menu.PartitionScheme.app3M_fat9M_16MB.upload.maximum_size=3145728
+esp32c5.menu.PartitionScheme.rainmaker=RainMaker 4MB
+esp32c5.menu.PartitionScheme.rainmaker.build.partitions=rainmaker
+esp32c5.menu.PartitionScheme.rainmaker.upload.maximum_size=1966080
+esp32c5.menu.PartitionScheme.rainmaker_4MB=RainMaker 4MB No OTA
+esp32c5.menu.PartitionScheme.rainmaker_4MB.build.partitions=rainmaker_4MB_no_ota
+esp32c5.menu.PartitionScheme.rainmaker_4MB.upload.maximum_size=4038656
+esp32c5.menu.PartitionScheme.rainmaker_8MB=RainMaker 8MB
+esp32c5.menu.PartitionScheme.rainmaker_8MB.build.partitions=rainmaker_8MB
+esp32c5.menu.PartitionScheme.rainmaker_8MB.upload.maximum_size=4116480
+esp32c5.menu.PartitionScheme.zigbee_2MB=Zigbee 2MB with spiffs
+esp32c5.menu.PartitionScheme.zigbee_2MB.build.partitions=zigbee_2MB
+esp32c5.menu.PartitionScheme.zigbee_2MB.upload.maximum_size=1310720
+esp32c5.menu.PartitionScheme.zigbee=Zigbee 4MB with spiffs
+esp32c5.menu.PartitionScheme.zigbee.build.partitions=zigbee
+esp32c5.menu.PartitionScheme.zigbee.upload.maximum_size=1310720
+esp32c5.menu.PartitionScheme.zigbee_8MB=Zigbee 8MB with spiffs
+esp32c5.menu.PartitionScheme.zigbee_8MB.build.partitions=zigbee_8MB
+esp32c5.menu.PartitionScheme.zigbee_8MB.upload.maximum_size=3407872
+esp32c5.menu.PartitionScheme.zigbee_zczr_2MB=Zigbee ZCZR 2MB with spiffs
+esp32c5.menu.PartitionScheme.zigbee_zczr_2MB.build.partitions=zigbee_zczr_2MB
+esp32c5.menu.PartitionScheme.zigbee_zczr_2MB.upload.maximum_size=1310720
+esp32c5.menu.PartitionScheme.zigbee_zczr=Zigbee ZCZR 4MB with spiffs
+esp32c5.menu.PartitionScheme.zigbee_zczr.build.partitions=zigbee_zczr
+esp32c5.menu.PartitionScheme.zigbee_zczr.upload.maximum_size=1310720
+esp32c5.menu.PartitionScheme.zigbee_zczr_8MB=Zigbee ZCZR 8MB with spiffs
+esp32c5.menu.PartitionScheme.zigbee_zczr_8MB.build.partitions=zigbee_zczr_8MB
+esp32c5.menu.PartitionScheme.zigbee_zczr_8MB.upload.maximum_size=3407872
+esp32c5.menu.PartitionScheme.custom=Custom
+esp32c5.menu.PartitionScheme.custom.build.partitions=
+esp32c5.menu.PartitionScheme.custom.upload.maximum_size=16777216
+
+esp32c5.menu.CPUFreq.240=240MHz (WiFi)
+esp32c5.menu.CPUFreq.240.build.f_cpu=240000000L
+esp32c5.menu.CPUFreq.120=120MHz (WiFi)
+esp32c5.menu.CPUFreq.120.build.f_cpu=120000000L
+esp32c5.menu.CPUFreq.80=80MHz (WiFi)
+esp32c5.menu.CPUFreq.80.build.f_cpu=80000000L
+esp32c5.menu.CPUFreq.40=40MHz
+esp32c5.menu.CPUFreq.40.build.f_cpu=40000000L
+esp32c5.menu.CPUFreq.20=20MHz
+esp32c5.menu.CPUFreq.20.build.f_cpu=20000000L
+esp32c5.menu.CPUFreq.10=10MHz
+esp32c5.menu.CPUFreq.10.build.f_cpu=10000000L
+
+esp32c5.menu.FlashMode.qio=QIO
+esp32c5.menu.FlashMode.qio.build.flash_mode=dio
+esp32c5.menu.FlashMode.qio.build.boot=qio
+esp32c5.menu.FlashMode.dio=DIO
+esp32c5.menu.FlashMode.dio.build.flash_mode=dio
+esp32c5.menu.FlashMode.dio.build.boot=dio
+
+esp32c5.menu.FlashFreq.80=80MHz
+esp32c5.menu.FlashFreq.80.build.flash_freq=80m
+esp32c5.menu.FlashFreq.40=40MHz
+esp32c5.menu.FlashFreq.40.build.flash_freq=40m
+
+esp32c5.menu.FlashSize.4M=4MB (32Mb)
+esp32c5.menu.FlashSize.4M.build.flash_size=4MB
+esp32c5.menu.FlashSize.8M=8MB (64Mb)
+esp32c5.menu.FlashSize.8M.build.flash_size=8MB
+esp32c5.menu.FlashSize.2M=2MB (16Mb)
+esp32c5.menu.FlashSize.2M.build.flash_size=2MB
+esp32c5.menu.FlashSize.16M=16MB (128Mb)
+esp32c5.menu.FlashSize.16M.build.flash_size=16MB
+
+esp32c5.menu.UploadSpeed.921600=921600
+esp32c5.menu.UploadSpeed.921600.upload.speed=921600
+esp32c5.menu.UploadSpeed.115200=115200
+esp32c5.menu.UploadSpeed.115200.upload.speed=115200
+esp32c5.menu.UploadSpeed.256000.windows=256000
+esp32c5.menu.UploadSpeed.256000.upload.speed=256000
+esp32c5.menu.UploadSpeed.230400.windows.upload.speed=256000
+esp32c5.menu.UploadSpeed.230400=230400
+esp32c5.menu.UploadSpeed.230400.upload.speed=230400
+esp32c5.menu.UploadSpeed.460800.linux=460800
+esp32c5.menu.UploadSpeed.460800.macosx=460800
+esp32c5.menu.UploadSpeed.460800.upload.speed=460800
+esp32c5.menu.UploadSpeed.512000.windows=512000
+esp32c5.menu.UploadSpeed.512000.upload.speed=512000
+
+esp32c5.menu.DebugLevel.none=None
+esp32c5.menu.DebugLevel.none.build.code_debug=0
+esp32c5.menu.DebugLevel.error=Error
+esp32c5.menu.DebugLevel.error.build.code_debug=1
+esp32c5.menu.DebugLevel.warn=Warn
+esp32c5.menu.DebugLevel.warn.build.code_debug=2
+esp32c5.menu.DebugLevel.info=Info
+esp32c5.menu.DebugLevel.info.build.code_debug=3
+esp32c5.menu.DebugLevel.debug=Debug
+esp32c5.menu.DebugLevel.debug.build.code_debug=4
+esp32c5.menu.DebugLevel.verbose=Verbose
+esp32c5.menu.DebugLevel.verbose.build.code_debug=5
+
+esp32c5.menu.EraseFlash.none=Disabled
+esp32c5.menu.EraseFlash.none.upload.erase_cmd=
+esp32c5.menu.EraseFlash.all=Enabled
+esp32c5.menu.EraseFlash.all.upload.erase_cmd=-e
+
+esp32c5.menu.ZigbeeMode.default=Disabled
+esp32c5.menu.ZigbeeMode.default.build.zigbee_mode=
+esp32c5.menu.ZigbeeMode.default.build.zigbee_libs=
+esp32c5.menu.ZigbeeMode.ed=Zigbee ED (end device)
+esp32c5.menu.ZigbeeMode.ed.build.zigbee_mode=-DZIGBEE_MODE_ED
+esp32c5.menu.ZigbeeMode.ed.build.zigbee_libs=-lesp_zb_api_ed -lesp_zb_cli_command -lzboss_stack.ed -lzboss_port
+esp32c5.menu.ZigbeeMode.zczr=Zigbee ZCZR (coordinator/router)
+esp32c5.menu.ZigbeeMode.zczr.build.zigbee_mode=-DZIGBEE_MODE_ZCZR
+esp32c5.menu.ZigbeeMode.zczr.build.zigbee_libs=-lesp_zb_api_zczr -lesp_zb_cli_command -lzboss_stack.zczr -lzboss_port
+esp32c5.menu.ZigbeeMode.rcp=Zigbee RCP (radio co-processor)
+esp32c5.menu.ZigbeeMode.rcp.build.zigbee_mode=-DZIGBEE_MODE_RCP
+esp32c5.menu.ZigbeeMode.rcp.build.zigbee_libs=-lesp_zb_api_rcp -lesp_zb_cli_command -lzboss_stack.rcp -lzboss_port
+esp32c5.menu.ZigbeeMode.ed_debug=Zigbee ED (end device) - Debug
+esp32c5.menu.ZigbeeMode.ed_debug.build.zigbee_mode=-DZIGBEE_MODE_ED
+esp32c5.menu.ZigbeeMode.ed_debug.build.zigbee_libs=-lesp_zb_api_ed.debug -lesp_zb_cli_command -lzboss_stack.ed.debug -lzboss_port.debug
+esp32c5.menu.ZigbeeMode.zczr_debug=Zigbee ZCZR (coordinator/router) - Debug
+esp32c5.menu.ZigbeeMode.zczr_debug.build.zigbee_mode=-DZIGBEE_MODE_ZCZR
+esp32c5.menu.ZigbeeMode.zczr_debug.build.zigbee_libs=-lesp_zb_api_zczr.debug -lesp_zb_cli_command -lzboss_stack.zczr.debug -lzboss_port.debug
+esp32c5.menu.ZigbeeMode.rcp_debug=Zigbee RCP (radio co-processor) - Debug
+esp32c5.menu.ZigbeeMode.rcp_debug.build.zigbee_mode=-DZIGBEE_MODE_RCP
+esp32c5.menu.ZigbeeMode.rcp_debug.build.zigbee_libs=-lesp_zb_api_rcp.debug -lesp_zb_cli_command -lzboss_stack.rcp.debug -lzboss_port.debug
+
+##############################################################
+
 esp32p4.name=ESP32P4 Dev Module
 
 esp32p4.bootloader.tool=esptool_py
diff --git a/cores/esp32/Esp.cpp b/cores/esp32/Esp.cpp
index 9f90a828b25..3cb0e7351c6 100644
--- a/cores/esp32/Esp.cpp
+++ b/cores/esp32/Esp.cpp
@@ -63,6 +63,9 @@ extern "C" {
 #elif CONFIG_IDF_TARGET_ESP32P4
 #include "esp32p4/rom/spi_flash.h"
 #define ESP_FLASH_IMAGE_BASE 0x2000  // Esp32p4 is located at 0x2000
+#elif CONFIG_IDF_TARGET_ESP32C5
+#include "esp32c5/rom/spi_flash.h"
+#define ESP_FLASH_IMAGE_BASE 0x0000  // Esp32c5 is located at 0x0000
 #else
 #error Target CONFIG_IDF_TARGET is not supported
 #endif
diff --git a/cores/esp32/HardwareSerial.h b/cores/esp32/HardwareSerial.h
index b1f6df17724..775b6ee2bcb 100644
--- a/cores/esp32/HardwareSerial.h
+++ b/cores/esp32/HardwareSerial.h
@@ -139,6 +139,8 @@ typedef enum {
 #define SOC_RX0 (gpio_num_t)23
 #elif CONFIG_IDF_TARGET_ESP32P4
 #define SOC_RX0 (gpio_num_t)38
+#elif CONFIG_IDF_TARGET_ESP32C5
+#define SOC_RX0 (gpio_num_t)12
 #endif
 #endif
 
@@ -157,6 +159,8 @@ typedef enum {
 #define SOC_TX0 (gpio_num_t)24
 #elif CONFIG_IDF_TARGET_ESP32P4
 #define SOC_TX0 (gpio_num_t)37
+#elif CONFIG_IDF_TARGET_ESP32C5
+#define SOC_TX0 (gpio_num_t)11
 #endif
 #endif
 
@@ -180,6 +184,8 @@ typedef enum {
 #define RX1 (gpio_num_t)0
 #elif CONFIG_IDF_TARGET_ESP32P4
 #define RX1 (gpio_num_t)11
+#elif CONFIG_IDF_TARGET_ESP32C5
+#define RX1 (gpio_num_t)4
 #endif
 #endif
 
@@ -200,6 +206,8 @@ typedef enum {
 #define TX1 (gpio_num_t)1
 #elif CONFIG_IDF_TARGET_ESP32P4
 #define TX1 (gpio_num_t)10
+#elif CONFIG_IDF_TARGET_ESP32C5
+#define TX1 (gpio_num_t)5
 #endif
 #endif
 #endif /* SOC_UART_HP_NUM > 1 */
diff --git a/cores/esp32/esp32-hal-cpu.c b/cores/esp32/esp32-hal-cpu.c
index 1ffde860792..8c13a4077fd 100644
--- a/cores/esp32/esp32-hal-cpu.c
+++ b/cores/esp32/esp32-hal-cpu.c
@@ -19,7 +19,7 @@
 #include "esp_attr.h"
 #include "esp_log.h"
 #include "soc/rtc.h"
-#if !defined(CONFIG_IDF_TARGET_ESP32C2) && !defined(CONFIG_IDF_TARGET_ESP32C6) && !defined(CONFIG_IDF_TARGET_ESP32H2) && !defined(CONFIG_IDF_TARGET_ESP32P4)
+#if !defined(CONFIG_IDF_TARGET_ESP32C2) && !defined(CONFIG_IDF_TARGET_ESP32C6) && !defined(CONFIG_IDF_TARGET_ESP32H2) && !defined(CONFIG_IDF_TARGET_ESP32P4) && !defined(CONFIG_IDF_TARGET_ESP32C5)
 #include "soc/rtc_cntl_reg.h"
 #include "soc/syscon_reg.h"
 #endif
@@ -48,6 +48,8 @@
 #include "esp32h2/rom/rtc.h"
 #elif CONFIG_IDF_TARGET_ESP32P4
 #include "esp32p4/rom/rtc.h"
+#elif CONFIG_IDF_TARGET_ESP32C5
+#include "esp32c5/rom/rtc.h"
 #else
 #error Target CONFIG_IDF_TARGET is not supported
 #endif
@@ -179,7 +181,7 @@ bool setCpuFrequencyMhz(uint32_t cpu_freq_mhz) {
   rtc_cpu_freq_config_t conf, cconf;
   uint32_t capb, apb;
   //Get XTAL Frequency and calculate min CPU MHz
-#if (!defined(CONFIG_IDF_TARGET_ESP32H2) && !defined(CONFIG_IDF_TARGET_ESP32P4))
+#if (!defined(CONFIG_IDF_TARGET_ESP32H2) && !defined(CONFIG_IDF_TARGET_ESP32P4) && !defined(CONFIG_IDF_TARGET_ESP32C5))
   rtc_xtal_freq_t xtal = rtc_clk_xtal_freq_get();
 #endif
 #if CONFIG_IDF_TARGET_ESP32
@@ -195,7 +197,7 @@ bool setCpuFrequencyMhz(uint32_t cpu_freq_mhz) {
     }
   }
 #endif
-#if (!defined(CONFIG_IDF_TARGET_ESP32H2) && !defined(CONFIG_IDF_TARGET_ESP32P4))
+#if (!defined(CONFIG_IDF_TARGET_ESP32H2) && !defined(CONFIG_IDF_TARGET_ESP32P4) && !defined(CONFIG_IDF_TARGET_ESP32C5))
   if (cpu_freq_mhz > xtal && cpu_freq_mhz != 240 && cpu_freq_mhz != 160 && cpu_freq_mhz != 120 && cpu_freq_mhz != 80) {
     if (xtal >= RTC_XTAL_FREQ_40M) {
       log_e("Bad frequency: %u MHz! Options are: 240, 160, 120, 80, %u, %u and %u MHz", cpu_freq_mhz, xtal, xtal / 2, xtal / 4);
diff --git a/cores/esp32/esp32-hal-i2c-slave.c b/cores/esp32/esp32-hal-i2c-slave.c
index 46c3a4d58c2..0e01259da61 100644
--- a/cores/esp32/esp32-hal-i2c-slave.c
+++ b/cores/esp32/esp32-hal-i2c-slave.c
@@ -43,7 +43,9 @@
 #include "soc/i2c_struct.h"
 #include "soc/periph_defs.h"
 #include "hal/i2c_ll.h"
+#ifndef CONFIG_IDF_TARGET_ESP32C5
 #include "hal/clk_gate_ll.h"
+#endif
 #include "esp32-hal-log.h"
 #include "esp32-hal-i2c-slave.h"
 #include "esp32-hal-periman.h"
@@ -325,7 +327,7 @@ esp_err_t i2cSlaveInit(uint8_t num, int sda, int scl, uint16_t slaveID, uint32_t
     frequency = 100000L;
   }
   frequency = (frequency * 5) / 4;
-#if !defined(CONFIG_IDF_TARGET_ESP32P4)
+#if !defined(CONFIG_IDF_TARGET_ESP32P4) && !defined(CONFIG_IDF_TARGET_ESP32C5)
   if (i2c->num == 0) {
     periph_ll_enable_clk_clear_rst(PERIPH_I2C0_MODULE);
 #if SOC_HP_I2C_NUM > 1
@@ -556,6 +558,9 @@ static bool i2c_slave_set_frequency(i2c_slave_struct_t *i2c, uint32_t clk_speed)
     i2c_ll_set_source_clk(i2c->dev, SOC_MOD_CLK_APB); /*!< I2C source clock from APB, 80M*/
   }
 #elif SOC_I2C_SUPPORT_XTAL
+#ifndef XTAL_CLK_FREQ
+#define XTAL_CLK_FREQ APB_CLK_FREQ
+#endif
   i2c_ll_master_cal_bus_clk(XTAL_CLK_FREQ, clk_speed, &clk_cal);
   I2C_CLOCK_SRC_ATOMIC() {
     i2c_ll_set_source_clk(i2c->dev, SOC_MOD_CLK_XTAL); /*!< I2C source clock from XTAL, 40M */
diff --git a/cores/esp32/esp32-hal-matrix.c b/cores/esp32/esp32-hal-matrix.c
index 7cddb4e04db..0d81e979f2b 100644
--- a/cores/esp32/esp32-hal-matrix.c
+++ b/cores/esp32/esp32-hal-matrix.c
@@ -34,6 +34,8 @@
 #include "esp32h2/rom/gpio.h"
 #elif CONFIG_IDF_TARGET_ESP32P4
 #include "esp32p4/rom/gpio.h"
+#elif CONFIG_IDF_TARGET_ESP32C5
+#include "esp32c5/rom/gpio.h"
 #else
 #error Target CONFIG_IDF_TARGET is not supported
 #endif
diff --git a/cores/esp32/esp32-hal-misc.c b/cores/esp32/esp32-hal-misc.c
index 50e2973d27a..39f81d50ae5 100644
--- a/cores/esp32/esp32-hal-misc.c
+++ b/cores/esp32/esp32-hal-misc.c
@@ -30,7 +30,7 @@
 #endif  //CONFIG_BT_ENABLED
 #include <sys/time.h>
 #include "soc/rtc.h"
-#if !defined(CONFIG_IDF_TARGET_ESP32C2) && !defined(CONFIG_IDF_TARGET_ESP32C6) && !defined(CONFIG_IDF_TARGET_ESP32H2) && !defined(CONFIG_IDF_TARGET_ESP32P4)
+#if !defined(CONFIG_IDF_TARGET_ESP32C2) && !defined(CONFIG_IDF_TARGET_ESP32C6) && !defined(CONFIG_IDF_TARGET_ESP32H2) && !defined(CONFIG_IDF_TARGET_ESP32P4) && !defined(CONFIG_IDF_TARGET_ESP32C5)
 #include "soc/rtc_cntl_reg.h"
 #include "soc/syscon_reg.h"
 #endif
@@ -56,6 +56,8 @@
 #include "esp32h2/rom/rtc.h"
 #elif CONFIG_IDF_TARGET_ESP32P4
 #include "esp32p4/rom/rtc.h"
+#elif CONFIG_IDF_TARGET_ESP32C5
+#include "esp32c5/rom/rtc.h"
 
 #else
 #error Target CONFIG_IDF_TARGET is not supported
diff --git a/cores/esp32/esp32-hal-spi.c b/cores/esp32/esp32-hal-spi.c
index 80928309670..4cff353d76c 100644
--- a/cores/esp32/esp32-hal-spi.c
+++ b/cores/esp32/esp32-hal-spi.c
@@ -26,7 +26,9 @@
 #include "soc/io_mux_reg.h"
 #include "soc/gpio_sig_map.h"
 #include "soc/rtc.h"
+#ifndef CONFIG_IDF_TARGET_ESP32C5
 #include "hal/clk_gate_ll.h"
+#endif
 #include "esp32-hal-periman.h"
 #include "esp_private/periph_ctrl.h"
 
@@ -60,6 +62,9 @@
 #elif CONFIG_IDF_TARGET_ESP32P4
 #include "esp32p4/rom/ets_sys.h"
 #include "esp32p4/rom/gpio.h"
+#elif CONFIG_IDF_TARGET_ESP32C5
+#include "esp32c5/rom/ets_sys.h"
+#include "esp32c5/rom/gpio.h"
 #else
 #error Target CONFIG_IDF_TARGET is not supported
 #endif
@@ -119,7 +124,7 @@ struct spi_struct_t {
 
 #define SPI_SS_IDX(p, n) ((p == 0) ? SPI_FSPI_SS_IDX(n) : ((p == 1) ? SPI_HSPI_SS_IDX(n) : 0))
 
-#elif CONFIG_IDF_TARGET_ESP32C2 || CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2
+#elif CONFIG_IDF_TARGET_ESP32C2 || CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32C5
 // ESP32C3
 #define SPI_COUNT (1)
 
@@ -161,7 +166,7 @@ static spi_t _spi_bus_array[] = {
   {(volatile spi_dev_t *)(DR_REG_SPI2_BASE), 0, -1, -1, -1, -1}
 #elif CONFIG_IDF_TARGET_ESP32C3
   {(volatile spi_dev_t *)(DR_REG_SPI2_BASE), 0, -1, -1, -1, -1}
-#elif CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2
+#elif CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32C5
   {(spi_dev_t *)(DR_REG_SPI2_BASE), 0, -1, -1, -1, -1}
 #else
   {(volatile spi_dev_t *)(DR_REG_SPI0_BASE), 0, -1, -1, -1, -1},
@@ -188,7 +193,7 @@ static spi_t _spi_bus_array[] = {
   {(volatile spi_dev_t *)(DR_REG_SPI2_BASE), NULL, 0, -1, -1, -1, -1}
 #elif CONFIG_IDF_TARGET_ESP32C3
   {(volatile spi_dev_t *)(DR_REG_SPI2_BASE), NULL, 0, -1, -1, -1, -1}
-#elif CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2
+#elif CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32C5
   {(spi_dev_t *)(DR_REG_SPI2_BASE), NULL, 0, -1, -1, -1, -1}
 #else
   {(volatile spi_dev_t *)(DR_REG_SPI0_BASE), NULL, 0, -1, -1, -1, -1},
@@ -685,7 +690,7 @@ spi_t *spiStartBus(uint8_t spi_num, uint32_t clockDiv, uint8_t dataMode, uint8_t
   spi->dev->user.doutdin = 1;
   int i;
   for (i = 0; i < 16; i++) {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
     spi->dev->data_buf[i].val = 0x00000000;
 #else
     spi->dev->data_buf[i] = 0x00000000;
@@ -733,7 +738,7 @@ void spiWrite(spi_t *spi, const uint32_t *data, uint8_t len) {
   spi->dev->miso_dlen.usr_miso_dbitlen = 0;
 #endif
   for (i = 0; i < len; i++) {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
     spi->dev->data_buf[i].val = data[i];
 #else
     spi->dev->data_buf[i] = data[i];
@@ -760,7 +765,7 @@ void spiTransfer(spi_t *spi, uint32_t *data, uint8_t len) {
   spi->dev->mosi_dlen.usr_mosi_dbitlen = (len * 32) - 1;
   spi->dev->miso_dlen.usr_miso_dbitlen = (len * 32) - 1;
   for (i = 0; i < len; i++) {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
     spi->dev->data_buf[i].val = data[i];
 #else
     spi->dev->data_buf[i] = data[i];
@@ -773,7 +778,7 @@ void spiTransfer(spi_t *spi, uint32_t *data, uint8_t len) {
   spi->dev->cmd.usr = 1;
   while (spi->dev->cmd.usr);
   for (i = 0; i < len; i++) {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
     data[i] = spi->dev->data_buf[i].val;
 #else
     data[i] = spi->dev->data_buf[i];
@@ -791,7 +796,7 @@ void spiWriteByte(spi_t *spi, uint8_t data) {
 #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32
   spi->dev->miso_dlen.usr_miso_dbitlen = 0;
 #endif
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -813,7 +818,7 @@ uint8_t spiTransferByte(spi_t *spi, uint8_t data) {
   SPI_MUTEX_LOCK();
   spi->dev->mosi_dlen.usr_mosi_dbitlen = 7;
   spi->dev->miso_dlen.usr_miso_dbitlen = 7;
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -824,7 +829,7 @@ uint8_t spiTransferByte(spi_t *spi, uint8_t data) {
 #endif
   spi->dev->cmd.usr = 1;
   while (spi->dev->cmd.usr);
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   data = spi->dev->data_buf[0].val & 0xFF;
 #else
   data = spi->dev->data_buf[0] & 0xFF;
@@ -854,7 +859,7 @@ void spiWriteWord(spi_t *spi, uint16_t data) {
 #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32
   spi->dev->miso_dlen.usr_miso_dbitlen = 0;
 #endif
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -878,7 +883,7 @@ uint16_t spiTransferWord(spi_t *spi, uint16_t data) {
   SPI_MUTEX_LOCK();
   spi->dev->mosi_dlen.usr_mosi_dbitlen = 15;
   spi->dev->miso_dlen.usr_miso_dbitlen = 15;
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -889,7 +894,7 @@ uint16_t spiTransferWord(spi_t *spi, uint16_t data) {
 #endif
   spi->dev->cmd.usr = 1;
   while (spi->dev->cmd.usr);
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   data = spi->dev->data_buf[0].val;
 #else
   data = spi->dev->data_buf[0];
@@ -913,7 +918,7 @@ void spiWriteLong(spi_t *spi, uint32_t data) {
 #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32
   spi->dev->miso_dlen.usr_miso_dbitlen = 0;
 #endif
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -937,7 +942,7 @@ uint32_t spiTransferLong(spi_t *spi, uint32_t data) {
   SPI_MUTEX_LOCK();
   spi->dev->mosi_dlen.usr_mosi_dbitlen = 31;
   spi->dev->miso_dlen.usr_miso_dbitlen = 31;
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -948,7 +953,7 @@ uint32_t spiTransferLong(spi_t *spi, uint32_t data) {
 #endif
   spi->dev->cmd.usr = 1;
   while (spi->dev->cmd.usr);
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   data = spi->dev->data_buf[0].val;
 #else
   data = spi->dev->data_buf[0];
@@ -987,7 +992,7 @@ static void __spiTransferBytes(spi_t *spi, const uint8_t *data, uint8_t *out, ui
   spi->dev->miso_dlen.usr_miso_dbitlen = ((bytes * 8) - 1);
 
   for (i = 0; i < words; i++) {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
     spi->dev->data_buf[i].val = wordsBuf[i];  //copy buffer to spi fifo
 #else
     spi->dev->data_buf[i] = wordsBuf[i];  //copy buffer to spi fifo
@@ -1004,7 +1009,7 @@ static void __spiTransferBytes(spi_t *spi, const uint8_t *data, uint8_t *out, ui
 
   if (out) {
     for (i = 0; i < words; i++) {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
       wordsBuf[i] = spi->dev->data_buf[i].val;  //copy spi fifo to buffer
 #else
       wordsBuf[i] = spi->dev->data_buf[i];  //copy spi fifo to buffer
@@ -1145,7 +1150,7 @@ void ARDUINO_ISR_ATTR spiWriteByteNL(spi_t *spi, uint8_t data) {
 #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32
   spi->dev->miso_dlen.usr_miso_dbitlen = 0;
 #endif
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -1164,7 +1169,7 @@ uint8_t spiTransferByteNL(spi_t *spi, uint8_t data) {
   }
   spi->dev->mosi_dlen.usr_mosi_dbitlen = 7;
   spi->dev->miso_dlen.usr_miso_dbitlen = 7;
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -1175,7 +1180,7 @@ uint8_t spiTransferByteNL(spi_t *spi, uint8_t data) {
 #endif
   spi->dev->cmd.usr = 1;
   while (spi->dev->cmd.usr);
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   data = spi->dev->data_buf[0].val & 0xFF;
 #else
   data = spi->dev->data_buf[0] & 0xFF;
@@ -1194,7 +1199,7 @@ void ARDUINO_ISR_ATTR spiWriteShortNL(spi_t *spi, uint16_t data) {
 #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32
   spi->dev->miso_dlen.usr_miso_dbitlen = 0;
 #endif
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -1216,7 +1221,7 @@ uint16_t spiTransferShortNL(spi_t *spi, uint16_t data) {
   }
   spi->dev->mosi_dlen.usr_mosi_dbitlen = 15;
   spi->dev->miso_dlen.usr_miso_dbitlen = 15;
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -1227,7 +1232,7 @@ uint16_t spiTransferShortNL(spi_t *spi, uint16_t data) {
 #endif
   spi->dev->cmd.usr = 1;
   while (spi->dev->cmd.usr);
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   data = spi->dev->data_buf[0].val & 0xFFFF;
 #else
   data = spi->dev->data_buf[0] & 0xFFFF;
@@ -1249,7 +1254,7 @@ void ARDUINO_ISR_ATTR spiWriteLongNL(spi_t *spi, uint32_t data) {
 #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32
   spi->dev->miso_dlen.usr_miso_dbitlen = 0;
 #endif
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -1271,7 +1276,7 @@ uint32_t spiTransferLongNL(spi_t *spi, uint32_t data) {
   }
   spi->dev->mosi_dlen.usr_mosi_dbitlen = 31;
   spi->dev->miso_dlen.usr_miso_dbitlen = 31;
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -1282,7 +1287,7 @@ uint32_t spiTransferLongNL(spi_t *spi, uint32_t data) {
 #endif
   spi->dev->cmd.usr = 1;
   while (spi->dev->cmd.usr);
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   data = spi->dev->data_buf[0].val;
 #else
   data = spi->dev->data_buf[0];
@@ -1313,7 +1318,7 @@ void spiWriteNL(spi_t *spi, const void *data_in, uint32_t len) {
     spi->dev->miso_dlen.usr_miso_dbitlen = 0;
 #endif
     for (size_t i = 0; i < c_longs; i++) {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
       spi->dev->data_buf[i].val = data[i];
 #else
       spi->dev->data_buf[i] = data[i];
@@ -1352,7 +1357,7 @@ void spiTransferBytesNL(spi_t *spi, const void *data_in, uint8_t *data_out, uint
     spi->dev->miso_dlen.usr_miso_dbitlen = (c_len * 8) - 1;
     if (data) {
       for (size_t i = 0; i < c_longs; i++) {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
         spi->dev->data_buf[i].val = data[i];
 #else
         spi->dev->data_buf[i] = data[i];
@@ -1360,7 +1365,7 @@ void spiTransferBytesNL(spi_t *spi, const void *data_in, uint8_t *data_out, uint
       }
     } else {
       for (size_t i = 0; i < c_longs; i++) {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
         spi->dev->data_buf[i].val = 0xFFFFFFFF;
 #else
         spi->dev->data_buf[i] = 0xFFFFFFFF;
@@ -1376,13 +1381,13 @@ void spiTransferBytesNL(spi_t *spi, const void *data_in, uint8_t *data_out, uint
     if (result) {
       if (c_len & 3) {
         for (size_t i = 0; i < (c_longs - 1); i++) {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
           result[i] = spi->dev->data_buf[i].val;
 #else
           result[i] = spi->dev->data_buf[i];
 #endif
         }
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
         uint32_t last_data = spi->dev->data_buf[c_longs - 1].val;
 #else
         uint32_t last_data = spi->dev->data_buf[c_longs - 1];
@@ -1394,7 +1399,7 @@ void spiTransferBytesNL(spi_t *spi, const void *data_in, uint8_t *data_out, uint
         }
       } else {
         for (size_t i = 0; i < c_longs; i++) {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
           result[i] = spi->dev->data_buf[i].val;
 #else
           result[i] = spi->dev->data_buf[i];
@@ -1436,7 +1441,7 @@ void spiTransferBitsNL(spi_t *spi, uint32_t data, uint32_t *out, uint8_t bits) {
 
   spi->dev->mosi_dlen.usr_mosi_dbitlen = (bits - 1);
   spi->dev->miso_dlen.usr_miso_dbitlen = (bits - 1);
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   spi->dev->data_buf[0].val = data;
 #else
   spi->dev->data_buf[0] = data;
@@ -1447,7 +1452,7 @@ void spiTransferBitsNL(spi_t *spi, uint32_t data, uint32_t *out, uint8_t bits) {
 #endif
   spi->dev->cmd.usr = 1;
   while (spi->dev->cmd.usr);
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   data = spi->dev->data_buf[0].val;
 #else
   data = spi->dev->data_buf[0];
@@ -1488,27 +1493,27 @@ void ARDUINO_ISR_ATTR spiWritePixelsNL(spi_t *spi, const void *data_in, uint32_t
       if (msb) {
         if (l_bytes && i == (c_longs - 1)) {
           if (l_bytes == 2) {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
             MSB_16_SET(spi->dev->data_buf[i].val, data[i]);
 #else
             MSB_16_SET(spi->dev->data_buf[i], data[i]);
 #endif
           } else {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
             spi->dev->data_buf[i].val = data[i] & 0xFF;
 #else
             spi->dev->data_buf[i] = data[i] & 0xFF;
 #endif
           }
         } else {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
           MSB_PIX_SET(spi->dev->data_buf[i].val, data[i]);
 #else
           MSB_PIX_SET(spi->dev->data_buf[i], data[i]);
 #endif
         }
       } else {
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
         spi->dev->data_buf[i].val = data[i];
 #else
         spi->dev->data_buf[i] = data[i];
diff --git a/cores/esp32/esp32-hal-uart.c b/cores/esp32/esp32-hal-uart.c
index 75e2da013ea..a928a8ede3a 100644
--- a/cores/esp32/esp32-hal-uart.c
+++ b/cores/esp32/esp32-hal-uart.c
@@ -206,6 +206,14 @@ static bool lpuartCheckPins(int8_t rxPin, int8_t txPin, int8_t ctsPin, int8_t rt
 }
 #endif  // SOC_UART_LP_NUM >= 1
 
+#ifndef GPIO_FUNC_IN_LOW
+#define GPIO_FUNC_IN_LOW GPIO_MATRIX_CONST_ZERO_INPUT
+#endif
+
+#ifndef GPIO_FUNC_IN_HIGH
+#define GPIO_FUNC_IN_HIGH GPIO_MATRIX_CONST_ONE_INPUT
+#endif
+
 // Negative Pin Number will keep it unmodified, thus this function can detach individual pins
 // This function will also unset the pins in the Peripheral Manager and set the pin to -1 after detaching
 static bool _uartDetachPins(uint8_t uart_num, int8_t rxPin, int8_t txPin, int8_t ctsPin, int8_t rtsPin) {
@@ -221,7 +229,8 @@ static bool _uartDetachPins(uint8_t uart_num, int8_t rxPin, int8_t txPin, int8_t
 
   // detaches HP and LP pins and sets Peripheral Manager and UART information
   if (rxPin >= 0 && uart->_rxPin == rxPin && perimanGetPinBusType(rxPin) == ESP32_BUS_TYPE_UART_RX) {
-    gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[rxPin], PIN_FUNC_GPIO);
+    //gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[rxPin], PIN_FUNC_GPIO);
+    esp_rom_gpio_pad_select_gpio(rxPin);
     // avoids causing BREAK in the UART line
     if (uart->_inverted) {
       esp_rom_gpio_connect_in_signal(GPIO_FUNC_IN_LOW, UART_PERIPH_SIGNAL(uart_num, SOC_UART_RX_PIN_IDX), false);
@@ -235,7 +244,8 @@ static bool _uartDetachPins(uint8_t uart_num, int8_t rxPin, int8_t txPin, int8_t
     }
   }
   if (txPin >= 0 && uart->_txPin == txPin && perimanGetPinBusType(txPin) == ESP32_BUS_TYPE_UART_TX) {
-    gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[txPin], PIN_FUNC_GPIO);
+    //gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[txPin], PIN_FUNC_GPIO);
+    esp_rom_gpio_pad_select_gpio(txPin);
     esp_rom_gpio_connect_out_signal(txPin, SIG_GPIO_OUT_IDX, false, false);
     uart->_txPin = -1;  // -1 means unassigned/detached
     if (!perimanClearPinBus(txPin)) {
@@ -244,7 +254,8 @@ static bool _uartDetachPins(uint8_t uart_num, int8_t rxPin, int8_t txPin, int8_t
     }
   }
   if (ctsPin >= 0 && uart->_ctsPin == ctsPin && perimanGetPinBusType(ctsPin) == ESP32_BUS_TYPE_UART_CTS) {
-    gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[ctsPin], PIN_FUNC_GPIO);
+    //gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[ctsPin], PIN_FUNC_GPIO);
+    esp_rom_gpio_pad_select_gpio(ctsPin);
     esp_rom_gpio_connect_in_signal(GPIO_FUNC_IN_LOW, UART_PERIPH_SIGNAL(uart_num, SOC_UART_CTS_PIN_IDX), false);
     uart->_ctsPin = -1;  // -1 means unassigned/detached
     if (!perimanClearPinBus(ctsPin)) {
@@ -253,7 +264,8 @@ static bool _uartDetachPins(uint8_t uart_num, int8_t rxPin, int8_t txPin, int8_t
     }
   }
   if (rtsPin >= 0 && uart->_rtsPin == rtsPin && perimanGetPinBusType(rtsPin) == ESP32_BUS_TYPE_UART_RTS) {
-    gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[rtsPin], PIN_FUNC_GPIO);
+    //gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[rtsPin], PIN_FUNC_GPIO);
+    esp_rom_gpio_pad_select_gpio(rtsPin);
     esp_rom_gpio_connect_out_signal(rtsPin, SIG_GPIO_OUT_IDX, false, false);
     uart->_rtsPin = -1;  // -1 means unassigned/detached
     if (!perimanClearPinBus(rtsPin)) {
@@ -808,7 +820,7 @@ void uartSetRxInvert(uart_t *uart, bool invert) {
   if (uart == NULL) {
     return;
   }
-#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
   // POTENTIAL ISSUE :: original code only set/reset rxd_inv bit
   // IDF or LL set/reset the whole inv_mask!
   // if (invert)
diff --git a/idf_component.yml b/idf_component.yml
index 967c4ecf0f6..c1fc614cae5 100644
--- a/idf_component.yml
+++ b/idf_component.yml
@@ -10,6 +10,7 @@ targets:
   - esp32c6
   - esp32h2
   - esp32p4
+  - esp32c5
 tags:
   - arduino
 files:
@@ -22,6 +23,7 @@ files:
     - "variants/esp32c6/**/*"
     - "variants/esp32h2/**/*"
     - "variants/esp32p4/**/*"
+    - "variants/esp32c5/**/*"
   exclude:
     - "docs/"
     - "docs/**/*"
@@ -44,7 +46,7 @@ files:
     - "platform.txt"
     - "programmers.txt"
 dependencies:
-  idf: ">=5.3,<5.5"
+  idf: ">=5.3,<5.6"
   # mdns 1.2.1 is necessary to build H2 with no WiFi
   espressif/mdns:
     version: "^1.2.3"
@@ -107,7 +109,7 @@ dependencies:
     rules:
       - if: "target == esp32p4"
   espressif/esp_wifi_remote:
-    version: "^0.4.1"
+    version: "^0.5.4"
     rules:
       - if: "target == esp32p4"
   espressif/libsodium:
diff --git a/libraries/SPI/src/SPI.cpp b/libraries/SPI/src/SPI.cpp
index 35e52f43e4d..732128809c9 100644
--- a/libraries/SPI/src/SPI.cpp
+++ b/libraries/SPI/src/SPI.cpp
@@ -83,7 +83,7 @@ void SPIClass::begin(int8_t sck, int8_t miso, int8_t mosi, int8_t ss) {
     _miso = (_spi_num == FSPI) ? MISO : -1;
     _mosi = (_spi_num == FSPI) ? MOSI : -1;
     _ss = (_spi_num == FSPI) ? SS : -1;
-#elif CONFIG_IDF_TARGET_ESP32C2 || CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#elif CONFIG_IDF_TARGET_ESP32C2 || CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
     _sck = SCK;
     _miso = MISO;
     _mosi = MOSI;
diff --git a/platform.txt b/platform.txt
index 65be05b3bf4..f41a8b4a764 100644
--- a/platform.txt
+++ b/platform.txt
@@ -84,6 +84,7 @@ build.extra_flags.esp32c3=-DARDUINO_USB_MODE=1 -DARDUINO_USB_CDC_ON_BOOT={build.
 build.extra_flags.esp32c6=-DARDUINO_USB_MODE=1 -DARDUINO_USB_CDC_ON_BOOT={build.cdc_on_boot}
 build.extra_flags.esp32h2=-DARDUINO_USB_MODE=1 -DARDUINO_USB_CDC_ON_BOOT={build.cdc_on_boot}
 build.extra_flags.esp32p4=-DARDUINO_USB_MODE={build.usb_mode} -DARDUINO_USB_CDC_ON_BOOT={build.cdc_on_boot} -DARDUINO_USB_MSC_ON_BOOT={build.msc_on_boot} -DARDUINO_USB_DFU_ON_BOOT={build.dfu_on_boot}
+build.extra_flags.esp32c5=-DARDUINO_USB_MODE=1 -DARDUINO_USB_CDC_ON_BOOT={build.cdc_on_boot}
 
 # This can be overriden in boards.txt
 build.zigbee_mode=
@@ -260,6 +261,14 @@ debug_config.esp32c6=
 debug_script.esp32h2=esp32h2-builtin.cfg
 debug_config.esp32h2=
 
+# ESP32-P4 debug configuration (TBD)
+debug_script.esp32p4=esp32p4-builtin.cfg
+debug_config.esp32p4=
+
+# ESP32-C5 debug configuration (TBD)
+debug_script.esp32c5=esp32c5-builtin.cfg
+debug_config.esp32c5=
+
 # Debug API variable definitions
 debug.executable={build.path}/{build.project_name}.elf
 debug.toolchain=gcc
diff --git a/variants/esp32c5/pins_arduino.h b/variants/esp32c5/pins_arduino.h
new file mode 100644
index 00000000000..eeaf3e01ebb
--- /dev/null
+++ b/variants/esp32c5/pins_arduino.h
@@ -0,0 +1,42 @@
+#ifndef Pins_Arduino_h
+#define Pins_Arduino_h
+
+#include <stdint.h>
+#include "soc/soc_caps.h"
+
+#define PIN_RGB_LED 8
+// BUILTIN_LED can be used in new Arduino API digitalWrite() like in Blink.ino
+static const uint8_t LED_BUILTIN = SOC_GPIO_PIN_COUNT + PIN_RGB_LED;
+#define BUILTIN_LED LED_BUILTIN  // backward compatibility
+#define LED_BUILTIN LED_BUILTIN  // allow testing #ifdef LED_BUILTIN
+// RGB_BUILTIN and RGB_BRIGHTNESS can be used in new Arduino API rgbLedWrite()
+#define RGB_BUILTIN    LED_BUILTIN
+#define RGB_BRIGHTNESS 64
+
+static const uint8_t TX = 11;
+static const uint8_t RX = 12;
+
+// static const uint8_t USB_DM = 13;
+// static const uint8_t USB_DP = 14;
+
+static const uint8_t SDA = 23;
+static const uint8_t SCL = 22;
+
+static const uint8_t SS = 18;
+static const uint8_t MOSI = 19;
+static const uint8_t MISO = 20;
+static const uint8_t SCK = 21;
+
+static const uint8_t A0 = 1;
+static const uint8_t A1 = 2;
+static const uint8_t A2 = 3;
+static const uint8_t A3 = 4;
+static const uint8_t A4 = 5;
+static const uint8_t A5 = 6;
+
+// LP I2C Pins are fixed on ESP32-C6
+#define WIRE1_PIN_DEFINED
+static const uint8_t SDA1 = 2;
+static const uint8_t SCL1 = 3;
+
+#endif /* Pins_Arduino_h */

From bf90cbd18316603a717fa08e2ba4dfcb85541236 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Wed, 22 Jan 2025 01:34:44 +0200
Subject: [PATCH 002/105] fix(examples): Add changes required to some examples

---
 libraries/ESP32/examples/DeepSleep/TouchWakeUp/TouchWakeUp.ino | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/libraries/ESP32/examples/DeepSleep/TouchWakeUp/TouchWakeUp.ino b/libraries/ESP32/examples/DeepSleep/TouchWakeUp/TouchWakeUp.ino
index 9d2b248ba44..5b1e0e9e115 100644
--- a/libraries/ESP32/examples/DeepSleep/TouchWakeUp/TouchWakeUp.ino
+++ b/libraries/ESP32/examples/DeepSleep/TouchWakeUp/TouchWakeUp.ino
@@ -48,7 +48,7 @@ Method to print the touchpad by which ESP32
 has been awaken from sleep
 */
 void print_wakeup_touchpad() {
-  touchPin = esp_sleep_get_touchpad_wakeup_status();
+  touchPin = (touch_pad_t)esp_sleep_get_touchpad_wakeup_status();
 
 #if CONFIG_IDF_TARGET_ESP32
   switch (touchPin) {

From af5abd5f6196ab4868b229f1e45f662961e531c7 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Wed, 22 Jan 2025 12:19:42 +0200
Subject: [PATCH 003/105] fix(c5): Update bootloader location

---
 boards.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/boards.txt b/boards.txt
index ea520e60fde..af3e217df9d 100644
--- a/boards.txt
+++ b/boards.txt
@@ -186,7 +186,7 @@ esp32c5.build.mcu=esp32c5
 esp32c5.build.core=esp32
 esp32c5.build.variant=esp32c5
 esp32c5.build.board=ESP32C5_DEV
-esp32c5.build.bootloader_addr=0x0
+esp32c5.build.bootloader_addr=0x2000
 
 esp32c5.build.cdc_on_boot=0
 esp32c5.build.f_cpu=240000000L

From 0894d7db68562d4690c5b201df7f0c333c776bc1 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Wed, 22 Jan 2025 12:31:54 +0200
Subject: [PATCH 004/105] fix(report): Add missing chip names

---
 cores/esp32/Esp.cpp               | 6 ++++++
 cores/esp32/chip-debug-report.cpp | 5 +++++
 2 files changed, 11 insertions(+)

diff --git a/cores/esp32/Esp.cpp b/cores/esp32/Esp.cpp
index 3cb0e7351c6..2b2e1280683 100644
--- a/cores/esp32/Esp.cpp
+++ b/cores/esp32/Esp.cpp
@@ -21,6 +21,7 @@
 #include "Esp.h"
 #include "esp_sleep.h"
 #include "spi_flash_mmap.h"
+#include "esp_idf_version.h"
 #include <memory>
 #include <soc/soc.h>
 #include <esp_partition.h>
@@ -304,6 +305,11 @@ const char *EspClass::getChipModel(void) {
     case CHIP_ESP32C6: return "ESP32-C6";
     case CHIP_ESP32H2: return "ESP32-H2";
     case CHIP_ESP32P4: return "ESP32-P4";
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
+    case CHIP_ESP32C5: return "ESP32-C5";
+    case CHIP_ESP32C61: return "ESP32-C61";
+    case CHIP_ESP32H21: return "ESP32-H21";
+#endif
     default:           return "UNKNOWN";
   }
 #endif
diff --git a/cores/esp32/chip-debug-report.cpp b/cores/esp32/chip-debug-report.cpp
index daafef3cab9..e3f3f431f81 100644
--- a/cores/esp32/chip-debug-report.cpp
+++ b/cores/esp32/chip-debug-report.cpp
@@ -88,6 +88,11 @@ static void printChipInfo(void) {
     case CHIP_ESP32C6: chip_report_printf("ESP32-C6\n"); break;
     case CHIP_ESP32H2: chip_report_printf("ESP32-H2\n"); break;
     case CHIP_ESP32P4: chip_report_printf("ESP32-P4\n"); break;
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
+    case CHIP_ESP32C5: chip_report_printf("ESP32-C5\n"); break;
+    case CHIP_ESP32C61: chip_report_printf("ESP32-C61\n"); break;
+    case CHIP_ESP32H21: chip_report_printf("ESP32-H21\n"); break;
+#endif
     default:           chip_report_printf("Unknown %d\n", info.model); break;
   }
   printPkgVersion();

From 100ed8e89524d5228ea2fc8d5220eba775462519 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Proch=C3=A1zka?=
 <90197375+P-R-O-C-H-Y@users.noreply.github.com>
Date: Wed, 22 Jan 2025 12:56:41 +0100
Subject: [PATCH 005/105] fix(c5): Update debug log in setCpuFrequencyMhz

---
 cores/esp32/esp32-hal-cpu.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/cores/esp32/esp32-hal-cpu.c b/cores/esp32/esp32-hal-cpu.c
index 8c13a4077fd..30c7e3a2b0a 100644
--- a/cores/esp32/esp32-hal-cpu.c
+++ b/cores/esp32/esp32-hal-cpu.c
@@ -267,6 +267,12 @@ bool setCpuFrequencyMhz(uint32_t cpu_freq_mhz) {
     (conf.source == SOC_CPU_CLK_SRC_PLL) ? "PLL" : ((conf.source == SOC_CPU_CLK_SRC_APLL) ? "APLL" : ((conf.source == SOC_CPU_CLK_SRC_XTAL) ? "XTAL" : "8M")),
     conf.source_freq_mhz, conf.div, conf.freq_mhz, apb
   );
+#elif defined(CONFIG_IDF_TARGET_ESP32C5)
+  log_d(
+    "%s: %u / %u = %u Mhz, APB: %u Hz",
+    (conf.source == SOC_CPU_CLK_SRC_PLL_F240M || conf.source == SOC_CPU_CLK_SRC_PLL_F160M) ? "PLL" : ((conf.source == SOC_CPU_CLK_SRC_XTAL) ? "XTAL" : "8M"),
+    conf.source_freq_mhz, conf.div, conf.freq_mhz, apb
+  );
 #else
   log_d(
     "%s: %u / %u = %u Mhz, APB: %u Hz", (conf.source == SOC_CPU_CLK_SRC_PLL) ? "PLL" : ((conf.source == SOC_CPU_CLK_SRC_XTAL) ? "XTAL" : "17.5M"),

From d9d3bf48d3f25bd3bc8a2217c67034c5842eccb5 Mon Sep 17 00:00:00 2001
From: Jason2866 <24528715+Jason2866@users.noreply.github.com>
Date: Wed, 22 Jan 2025 14:50:05 +0100
Subject: [PATCH 006/105] add c5 bootloader location to pioarduino script
 (#10889)

* add c5 bootloader location to pioarduino script

* ci(pre-commit): Apply automatic fixes

---------

Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 tools/pioarduino-build.py | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/tools/pioarduino-build.py b/tools/pioarduino-build.py
index 3335a716888..47940b0d043 100644
--- a/tools/pioarduino-build.py
+++ b/tools/pioarduino-build.py
@@ -213,7 +213,11 @@ def add_tinyuf2_extra_image():
     LIBSOURCE_DIRS=[join(FRAMEWORK_DIR, "libraries")],
     FLASH_EXTRA_IMAGES=[
         (
-            "0x1000" if build_mcu in ["esp32", "esp32s2"] else ("0x2000" if build_mcu in ["esp32p4"] else "0x0000"),
+            (
+                "0x1000"
+                if build_mcu in ["esp32", "esp32s2"]
+                else ("0x2000" if build_mcu in ["esp32p4", "esp32c5"] else "0x0000")
+            ),
             get_bootloader_image(variants_dir),
         ),
         ("0x8000", join(env.subst("$BUILD_DIR"), "partitions.bin")),

From 8af81cdf096f003255679485733566ffb23f3042 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Wed, 22 Jan 2025 15:52:13 +0200
Subject: [PATCH 007/105] fix(ci): Fix/stop some examples for C5

---
 libraries/ESP32/examples/DeepSleep/ExternalWakeUp/ci.json    | 3 ++-
 .../ESP32/examples/DeepSleep/SmoothBlink_ULP_Code/ci.json    | 3 ++-
 libraries/ESP32/examples/DeepSleep/TouchWakeUp/ci.json       | 3 ++-
 libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino     | 2 +-
 .../ESP32/examples/ResetReason/ResetReason/ResetReason.ino   | 2 ++
 libraries/ESP32/examples/TWAI/TWAIreceive/ci.json            | 5 +++++
 libraries/ESP32/examples/TWAI/TWAItransmit/ci.json           | 5 +++++
 libraries/ESP_SR/examples/Basic/ci.json                      | 3 ++-
 8 files changed, 21 insertions(+), 5 deletions(-)
 create mode 100644 libraries/ESP32/examples/TWAI/TWAIreceive/ci.json
 create mode 100644 libraries/ESP32/examples/TWAI/TWAItransmit/ci.json

diff --git a/libraries/ESP32/examples/DeepSleep/ExternalWakeUp/ci.json b/libraries/ESP32/examples/DeepSleep/ExternalWakeUp/ci.json
index cd679adefad..dfd49d94fe9 100644
--- a/libraries/ESP32/examples/DeepSleep/ExternalWakeUp/ci.json
+++ b/libraries/ESP32/examples/DeepSleep/ExternalWakeUp/ci.json
@@ -3,6 +3,7 @@
     "esp32c3": false,
     "esp32c6": false,
     "esp32h2": false,
-    "esp32p4": false
+    "esp32p4": false,
+    "esp32c5": false
   }
 }
diff --git a/libraries/ESP32/examples/DeepSleep/SmoothBlink_ULP_Code/ci.json b/libraries/ESP32/examples/DeepSleep/SmoothBlink_ULP_Code/ci.json
index 6afa60f44c4..5fa2bd14e5d 100644
--- a/libraries/ESP32/examples/DeepSleep/SmoothBlink_ULP_Code/ci.json
+++ b/libraries/ESP32/examples/DeepSleep/SmoothBlink_ULP_Code/ci.json
@@ -5,6 +5,7 @@
     "esp32h2": false,
     "esp32p4": false,
     "esp32s2": false,
-    "esp32s3": false
+    "esp32s3": false,
+    "esp32c5": false
   }
 }
diff --git a/libraries/ESP32/examples/DeepSleep/TouchWakeUp/ci.json b/libraries/ESP32/examples/DeepSleep/TouchWakeUp/ci.json
index 25c42144223..ae65fa0df74 100644
--- a/libraries/ESP32/examples/DeepSleep/TouchWakeUp/ci.json
+++ b/libraries/ESP32/examples/DeepSleep/TouchWakeUp/ci.json
@@ -2,6 +2,7 @@
   "targets": {
     "esp32c3": false,
     "esp32c6": false,
-    "esp32h2": false
+    "esp32h2": false,
+    "esp32c5": false
   }
 }
diff --git a/libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino b/libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino
index 17e7af290bf..1b96d868ecb 100644
--- a/libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino
+++ b/libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino
@@ -21,7 +21,7 @@
  *
  */
 
-#if CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4
+#if CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
 // ESP32 C3 has only 2 channels for RX and 2 for TX, thus MAX RMT_MEM is 128
 #define RMT_TX_PIN 4
 #define RMT_RX_PIN 5
diff --git a/libraries/ESP32/examples/ResetReason/ResetReason/ResetReason.ino b/libraries/ESP32/examples/ResetReason/ResetReason/ResetReason.ino
index 0104c6422f2..ca7e15bf479 100644
--- a/libraries/ESP32/examples/ResetReason/ResetReason/ResetReason.ino
+++ b/libraries/ESP32/examples/ResetReason/ResetReason/ResetReason.ino
@@ -28,6 +28,8 @@
 #include "esp32h2/rom/rtc.h"
 #elif CONFIG_IDF_TARGET_ESP32P4
 #include "esp32p4/rom/rtc.h"
+#elif CONFIG_IDF_TARGET_ESP32C5
+#include "esp32c5/rom/rtc.h"
 #else
 #error Target CONFIG_IDF_TARGET is not supported
 #endif
diff --git a/libraries/ESP32/examples/TWAI/TWAIreceive/ci.json b/libraries/ESP32/examples/TWAI/TWAIreceive/ci.json
new file mode 100644
index 00000000000..7379dba8bb9
--- /dev/null
+++ b/libraries/ESP32/examples/TWAI/TWAIreceive/ci.json
@@ -0,0 +1,5 @@
+{
+  "targets": {
+    "esp32c5": false
+  }
+}
diff --git a/libraries/ESP32/examples/TWAI/TWAItransmit/ci.json b/libraries/ESP32/examples/TWAI/TWAItransmit/ci.json
new file mode 100644
index 00000000000..7379dba8bb9
--- /dev/null
+++ b/libraries/ESP32/examples/TWAI/TWAItransmit/ci.json
@@ -0,0 +1,5 @@
+{
+  "targets": {
+    "esp32c5": false
+  }
+}
diff --git a/libraries/ESP_SR/examples/Basic/ci.json b/libraries/ESP_SR/examples/Basic/ci.json
index c395378f45e..ec0e969a7d0 100644
--- a/libraries/ESP_SR/examples/Basic/ci.json
+++ b/libraries/ESP_SR/examples/Basic/ci.json
@@ -13,6 +13,7 @@
     "esp32c6": false,
     "esp32h2": false,
     "esp32p4": false,
-    "esp32s2": false
+    "esp32s2": false,
+    "esp32c5": false
   }
 }

From 9fbcb345b786e30de491e34b1cd4ea8d8ff4e2ef Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Proch=C3=A1zka?=
 <90197375+P-R-O-C-H-Y@users.noreply.github.com>
Date: Wed, 22 Jan 2025 18:44:49 +0100
Subject: [PATCH 008/105] fix(c5): Update PIN_RGB_LED in pins_arduino.h

---
 variants/esp32c5/pins_arduino.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/variants/esp32c5/pins_arduino.h b/variants/esp32c5/pins_arduino.h
index eeaf3e01ebb..6ed7f0320fe 100644
--- a/variants/esp32c5/pins_arduino.h
+++ b/variants/esp32c5/pins_arduino.h
@@ -4,7 +4,7 @@
 #include <stdint.h>
 #include "soc/soc_caps.h"
 
-#define PIN_RGB_LED 8
+#define PIN_RGB_LED 27
 // BUILTIN_LED can be used in new Arduino API digitalWrite() like in Blink.ino
 static const uint8_t LED_BUILTIN = SOC_GPIO_PIN_COUNT + PIN_RGB_LED;
 #define BUILTIN_LED LED_BUILTIN  // backward compatibility

From f45cd7bf337316f4c6dde18bf23cd9c5b413863f Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Mon, 27 Jan 2025 14:06:54 +0200
Subject: [PATCH 009/105] fix(psram): Add support for ESP32-C5 PSRAM

---
 boards.txt                        | 5 +++++
 cores/esp32/chip-debug-report.cpp | 3 +++
 cores/esp32/esp32-hal-psram.c     | 2 ++
 3 files changed, 10 insertions(+)

diff --git a/boards.txt b/boards.txt
index af3e217df9d..0f42aa18a05 100644
--- a/boards.txt
+++ b/boards.txt
@@ -210,6 +210,11 @@ esp32c5.menu.JTAGAdapter.bridge=ESP USB Bridge
 esp32c5.menu.JTAGAdapter.bridge.build.openocdscript=esp32c5-bridge.cfg
 esp32c5.menu.JTAGAdapter.bridge.build.copy_jtag_files=1
 
+esp32c5.menu.PSRAM.disabled=Disabled
+esp32c5.menu.PSRAM.disabled.build.defines=
+esp32c5.menu.PSRAM.enabled=Enabled
+esp32c5.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM
+
 esp32c5.menu.CDCOnBoot.default=Disabled
 esp32c5.menu.CDCOnBoot.default.build.cdc_on_boot=0
 esp32c5.menu.CDCOnBoot.cdc=Enabled
diff --git a/cores/esp32/chip-debug-report.cpp b/cores/esp32/chip-debug-report.cpp
index e3f3f431f81..281c7bdb62d 100644
--- a/cores/esp32/chip-debug-report.cpp
+++ b/cores/esp32/chip-debug-report.cpp
@@ -67,6 +67,9 @@ static void printPkgVersion(void) {
 #elif CONFIG_IDF_TARGET_ESP32P4
   uint32_t pkg_ver = REG_GET_FIELD(EFUSE_RD_MAC_SYS_2_REG, EFUSE_PKG_VERSION);
   chip_report_printf("%lu", pkg_ver);
+#elif CONFIG_IDF_TARGET_ESP32C5
+  uint32_t pkg_ver = REG_GET_FIELD(EFUSE_RD_MAC_SYS2_REG, EFUSE_PKG_VERSION);
+  chip_report_printf("%lu", pkg_ver);
 #else
   chip_report_printf("Unknown");
 #endif
diff --git a/cores/esp32/esp32-hal-psram.c b/cores/esp32/esp32-hal-psram.c
index 3c7a51c3343..0d57a67ede4 100644
--- a/cores/esp32/esp32-hal-psram.c
+++ b/cores/esp32/esp32-hal-psram.c
@@ -29,6 +29,8 @@
 #include "esp32s3/rom/cache.h"
 #elif CONFIG_IDF_TARGET_ESP32P4
 #include "esp32p4/rom/cache.h"
+#elif CONFIG_IDF_TARGET_ESP32C5
+#include "esp32c5/rom/cache.h"
 #else
 #error Target CONFIG_IDF_TARGET is not supported
 #endif

From 75de09ef298c5bc9e26c7be2fd8af0446b4e4296 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Tue, 4 Feb 2025 00:14:19 +0200
Subject: [PATCH 010/105] fix(board): Update ESP32-C5 Dev Kit Pinout

---
 variants/esp32c5/pins_arduino.h | 24 +++++++++++++++---------
 1 file changed, 15 insertions(+), 9 deletions(-)

diff --git a/variants/esp32c5/pins_arduino.h b/variants/esp32c5/pins_arduino.h
index 6ed7f0320fe..e3a7e57ef44 100644
--- a/variants/esp32c5/pins_arduino.h
+++ b/variants/esp32c5/pins_arduino.h
@@ -19,13 +19,13 @@ static const uint8_t RX = 12;
 // static const uint8_t USB_DM = 13;
 // static const uint8_t USB_DP = 14;
 
-static const uint8_t SDA = 23;
-static const uint8_t SCL = 22;
+static const uint8_t SDA = 0;
+static const uint8_t SCL = 1;
 
-static const uint8_t SS = 18;
-static const uint8_t MOSI = 19;
-static const uint8_t MISO = 20;
-static const uint8_t SCK = 21;
+static const uint8_t SS = 6;
+static const uint8_t MOSI = 8;
+static const uint8_t MISO = 9;
+static const uint8_t SCK = 10;
 
 static const uint8_t A0 = 1;
 static const uint8_t A1 = 2;
@@ -34,9 +34,15 @@ static const uint8_t A3 = 4;
 static const uint8_t A4 = 5;
 static const uint8_t A5 = 6;
 
-// LP I2C Pins are fixed on ESP32-C6
+// LP I2C Pins are fixed on ESP32-C5
+static const uint8_t LP_SDA = 2;
+static const uint8_t LP_SCL = 3;
 #define WIRE1_PIN_DEFINED
-static const uint8_t SDA1 = 2;
-static const uint8_t SCL1 = 3;
+#define SDA1 LP_SDA
+#define SCL1 LP_SCL
+
+// LP UART Pins are fixed on ESP32-C5
+static const uint8_t LP_RX = 4;
+static const uint8_t LP_TX = 5;
 
 #endif /* Pins_Arduino_h */

From 6283c15ae22da9ec731b2fc7a1f5539f9efca6cf Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Tue, 18 Feb 2025 14:24:37 +0200
Subject: [PATCH 011/105] IDF master (#10887)

* feat(ci): Run sketches on ESP32-C5

* IDF master 1160a86b

* fix(zigbee): Remove RCP mode from ESP32-C5
---
 .github/scripts/on-push.sh                |   1 +
 .github/scripts/sketch_utils.sh           |   5 +
 .github/workflows/push.yml                |   1 +
 boards.txt                                |  14 +-
 package/package_esp32_index.template.json | 204 +++++++++++-----------
 5 files changed, 113 insertions(+), 112 deletions(-)

diff --git a/.github/scripts/on-push.sh b/.github/scripts/on-push.sh
index 6095f88e727..3eb020c09a3 100755
--- a/.github/scripts/on-push.sh
+++ b/.github/scripts/on-push.sh
@@ -90,6 +90,7 @@ if [ "$BUILD_LOG" -eq 1 ]; then
 fi
 
 #build sketches for different targets
+build "esp32c5" "$CHUNK_INDEX" "$CHUNKS_CNT" "$BUILD_LOG" "$LOG_LEVEL" "$SKETCHES_FILE" "${SKETCHES_ESP32[@]}"
 build "esp32p4" "$CHUNK_INDEX" "$CHUNKS_CNT" "$BUILD_LOG" "$LOG_LEVEL" "$SKETCHES_FILE" "${SKETCHES_ESP32[@]}"
 build "esp32s3" "$CHUNK_INDEX" "$CHUNKS_CNT" "$BUILD_LOG" "$LOG_LEVEL" "$SKETCHES_FILE" "${SKETCHES_ESP32[@]}"
 build "esp32s2" "$CHUNK_INDEX" "$CHUNKS_CNT" "$BUILD_LOG" "$LOG_LEVEL" "$SKETCHES_FILE" "${SKETCHES_ESP32[@]}"
diff --git a/.github/scripts/sketch_utils.sh b/.github/scripts/sketch_utils.sh
index e536da50111..323f39b3afc 100755
--- a/.github/scripts/sketch_utils.sh
+++ b/.github/scripts/sketch_utils.sh
@@ -156,6 +156,7 @@ function build_sketch { # build_sketch <ide_path> <user_path> <path-to-ino> [ext
             esp32c6_opts=$(echo "$debug_level,$fqbn_append" | sed 's/^,*//;s/,*$//;s/,\{2,\}/,/g')
             esp32h2_opts=$(echo "$debug_level,$fqbn_append" | sed 's/^,*//;s/,*$//;s/,\{2,\}/,/g')
             esp32p4_opts=$(echo "PSRAM=enabled,USBMode=default,$debug_level,$fqbn_append" | sed 's/^,*//;s/,*$//;s/,\{2,\}/,/g')
+            esp32c5_opts=$(echo "$debug_level,$fqbn_append" | sed 's/^,*//;s/,*$//;s/,\{2,\}/,/g')
 
             # Select the common part of the FQBN based on the target.  The rest will be
             # appended depending on the passed options.
@@ -191,6 +192,10 @@ function build_sketch { # build_sketch <ide_path> <user_path> <path-to-ino> [ext
                     [ -n "${options:-$esp32p4_opts}" ] && opt=":${options:-$esp32p4_opts}"
                     fqbn="espressif:esp32:esp32p4$opt"
                 ;;
+                "esp32c5")
+                    [ -n "${options:-$esp32c5_opts}" ] && opt=":${options:-$esp32c5_opts}"
+                    fqbn="espressif:esp32:esp32c5$opt"
+                ;;
                 *)
                     echo "ERROR: Invalid chip: $target"
                     exit 1
diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml
index feb32f95d03..428b89a8c21 100644
--- a/.github/workflows/push.yml
+++ b/.github/workflows/push.yml
@@ -47,6 +47,7 @@ on:
       - "variants/esp32/**/*"
       - "variants/esp32c2/**/*"
       - "variants/esp32c3/**/*"
+      - "variants/esp32c5/**/*"
       - "variants/esp32c6/**/*"
       - "variants/esp32h2/**/*"
       - "variants/esp32p4/**/*"
diff --git a/boards.txt b/boards.txt
index 0f42aa18a05..f7ad60d3eab 100644
--- a/boards.txt
+++ b/boards.txt
@@ -359,22 +359,16 @@ esp32c5.menu.ZigbeeMode.default.build.zigbee_mode=
 esp32c5.menu.ZigbeeMode.default.build.zigbee_libs=
 esp32c5.menu.ZigbeeMode.ed=Zigbee ED (end device)
 esp32c5.menu.ZigbeeMode.ed.build.zigbee_mode=-DZIGBEE_MODE_ED
-esp32c5.menu.ZigbeeMode.ed.build.zigbee_libs=-lesp_zb_api_ed -lesp_zb_cli_command -lzboss_stack.ed -lzboss_port
+esp32c5.menu.ZigbeeMode.ed.build.zigbee_libs=-lesp_zb_api.ed -lzboss_stack.ed -lzboss_port.native
 esp32c5.menu.ZigbeeMode.zczr=Zigbee ZCZR (coordinator/router)
 esp32c5.menu.ZigbeeMode.zczr.build.zigbee_mode=-DZIGBEE_MODE_ZCZR
-esp32c5.menu.ZigbeeMode.zczr.build.zigbee_libs=-lesp_zb_api_zczr -lesp_zb_cli_command -lzboss_stack.zczr -lzboss_port
-esp32c5.menu.ZigbeeMode.rcp=Zigbee RCP (radio co-processor)
-esp32c5.menu.ZigbeeMode.rcp.build.zigbee_mode=-DZIGBEE_MODE_RCP
-esp32c5.menu.ZigbeeMode.rcp.build.zigbee_libs=-lesp_zb_api_rcp -lesp_zb_cli_command -lzboss_stack.rcp -lzboss_port
+esp32c5.menu.ZigbeeMode.zczr.build.zigbee_libs=-lesp_zb_api.zczr -lzboss_stack.zczr -lzboss_port.native
 esp32c5.menu.ZigbeeMode.ed_debug=Zigbee ED (end device) - Debug
 esp32c5.menu.ZigbeeMode.ed_debug.build.zigbee_mode=-DZIGBEE_MODE_ED
-esp32c5.menu.ZigbeeMode.ed_debug.build.zigbee_libs=-lesp_zb_api_ed.debug -lesp_zb_cli_command -lzboss_stack.ed.debug -lzboss_port.debug
+esp32c5.menu.ZigbeeMode.ed_debug.build.zigbee_libs=-lesp_zb_api.ed.debug -lzboss_stack.ed.debug -lzboss_port.native.debug
 esp32c5.menu.ZigbeeMode.zczr_debug=Zigbee ZCZR (coordinator/router) - Debug
 esp32c5.menu.ZigbeeMode.zczr_debug.build.zigbee_mode=-DZIGBEE_MODE_ZCZR
-esp32c5.menu.ZigbeeMode.zczr_debug.build.zigbee_libs=-lesp_zb_api_zczr.debug -lesp_zb_cli_command -lzboss_stack.zczr.debug -lzboss_port.debug
-esp32c5.menu.ZigbeeMode.rcp_debug=Zigbee RCP (radio co-processor) - Debug
-esp32c5.menu.ZigbeeMode.rcp_debug.build.zigbee_mode=-DZIGBEE_MODE_RCP
-esp32c5.menu.ZigbeeMode.rcp_debug.build.zigbee_libs=-lesp_zb_api_rcp.debug -lesp_zb_cli_command -lzboss_stack.rcp.debug -lzboss_port.debug
+esp32c5.menu.ZigbeeMode.zczr_debug.build.zigbee_libs=-lesp_zb_api.zczr.debug -lzboss_stack.zczr.debug -lzboss_port.native.debug
 
 ##############################################################
 
diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index b0d7c3200d1..8bbd2e6a4e9 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-release_v5.4-d4aa25a3-v1"
+              "version": "idf-master-1160a86b-v1"
             },
             {
               "packager": "esp32",
@@ -61,7 +61,7 @@
             {
               "packager": "esp32",
               "name": "xtensa-esp-elf-gdb",
-              "version": "14.2_20240403"
+              "version": "15.2_20241112"
             },
             {
               "packager": "esp32",
@@ -71,7 +71,7 @@
             {
               "packager": "esp32",
               "name": "riscv32-esp-elf-gdb",
-              "version": "14.2_20240403"
+              "version": "15.2_20241112"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-release_v5.4-d4aa25a3-v1",
+          "version": "idf-master-1160a86b-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.4/esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "checksum": "SHA-256:81101d580ebafb78f71bd494f4f5162fd829279d18634282c0f8f95c9e928335",
-              "size": "350941396"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
+              "size": "405894668"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.4/esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "checksum": "SHA-256:81101d580ebafb78f71bd494f4f5162fd829279d18634282c0f8f95c9e928335",
-              "size": "350941396"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
+              "size": "405894668"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.4/esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "checksum": "SHA-256:81101d580ebafb78f71bd494f4f5162fd829279d18634282c0f8f95c9e928335",
-              "size": "350941396"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
+              "size": "405894668"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.4/esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "checksum": "SHA-256:81101d580ebafb78f71bd494f4f5162fd829279d18634282c0f8f95c9e928335",
-              "size": "350941396"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
+              "size": "405894668"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.4/esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "checksum": "SHA-256:81101d580ebafb78f71bd494f4f5162fd829279d18634282c0f8f95c9e928335",
-              "size": "350941396"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
+              "size": "405894668"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.4/esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "checksum": "SHA-256:81101d580ebafb78f71bd494f4f5162fd829279d18634282c0f8f95c9e928335",
-              "size": "350941396"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
+              "size": "405894668"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.4/esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "checksum": "SHA-256:81101d580ebafb78f71bd494f4f5162fd829279d18634282c0f8f95c9e928335",
-              "size": "350941396"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
+              "size": "405894668"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.4/esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.4-d4aa25a3-v1.zip",
-              "checksum": "SHA-256:81101d580ebafb78f71bd494f4f5162fd829279d18634282c0f8f95c9e928335",
-              "size": "350941396"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
+              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
+              "size": "405894668"
             }
           ]
         },
@@ -228,63 +228,63 @@
         },
         {
           "name": "xtensa-esp-elf-gdb",
-          "version": "14.2_20240403",
+          "version": "15.2_20241112",
           "systems": [
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/xtensa-esp-elf-gdb-14.2_20240403-x86_64-linux-gnu.tar.gz",
-              "archiveFileName": "xtensa-esp-elf-gdb-14.2_20240403-x86_64-linux-gnu.tar.gz",
-              "checksum": "SHA-256:9d68472d4cba5cf8c2b79d94f86f92c828e76a632bd1e6be5e7706e5b304d36e",
-              "size": "31010320"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-x86_64-linux-gnu.tar.gz",
+              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-x86_64-linux-gnu.tar.gz",
+              "checksum": "SHA-256:18774349d2b1c7d7f5ba984563f7022aef4a3df4b706ed8821c53266f599343d",
+              "size": "35179121"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/xtensa-esp-elf-gdb-14.2_20240403-aarch64-linux-gnu.tar.gz",
-              "archiveFileName": "xtensa-esp-elf-gdb-14.2_20240403-aarch64-linux-gnu.tar.gz",
-              "checksum": "SHA-256:bdabc3217994815fc311c4e16e588b78f6596b5ad4ffa46c80b40e982cfb1e66",
-              "size": "30954580"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-aarch64-linux-gnu.tar.gz",
+              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-aarch64-linux-gnu.tar.gz",
+              "checksum": "SHA-256:77cb3b2c85d6cfbb40b7f99eebbc2b1c3f4fe13eba20b3da798bdbbc6eb8e87c",
+              "size": "34295046"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/xtensa-esp-elf-gdb-14.2_20240403-arm-linux-gnueabi.tar.gz",
-              "archiveFileName": "xtensa-esp-elf-gdb-14.2_20240403-arm-linux-gnueabi.tar.gz",
-              "checksum": "SHA-256:d54b8d703ba897b28c627da3d27106a3906dd01ba298778a67064710bc33c76d",
-              "size": "28697281"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-arm-linux-gnueabi.tar.gz",
+              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-arm-linux-gnueabi.tar.gz",
+              "checksum": "SHA-256:b87af0539de118eb9d43a4a89c8c1b0a6ab2557560015155104c44f91b5c4aa0",
+              "size": "30338727"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/xtensa-esp-elf-gdb-14.2_20240403-i586-linux-gnu.tar.gz",
-              "archiveFileName": "xtensa-esp-elf-gdb-14.2_20240403-i586-linux-gnu.tar.gz",
-              "checksum": "SHA-256:64d3bc992ed8fdec383d49e8b803ac494605a38117c8293db8da055037de96b0",
-              "size": "29890994"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-i586-linux-gnu.tar.gz",
+              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-i586-linux-gnu.tar.gz",
+              "checksum": "SHA-256:2c7531bd390928fed479999ac9089b39a25f56ca4f4cc330db7d7a633a37405b",
+              "size": "33906121"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/xtensa-esp-elf-gdb-14.2_20240403-x86_64-apple-darwin14.tar.gz",
-              "archiveFileName": "xtensa-esp-elf-gdb-14.2_20240403-x86_64-apple-darwin14.tar.gz",
-              "checksum": "SHA-256:023e74b3fda793da4bc0509b02de776ee0dad6efaaac17bef5916fb7dc9c26b9",
-              "size": "44446611"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-x86_64-apple-darwin21.1.tar.gz",
+              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-x86_64-apple-darwin21.1.tar.gz",
+              "checksum": "SHA-256:ba2907be9a4c22c4e418f42ec84cf57401570a71dabbe69425227114ebf351a7",
+              "size": "52502302"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/xtensa-esp-elf-gdb-14.2_20240403-aarch64-apple-darwin21.1.tar.gz",
-              "archiveFileName": "xtensa-esp-elf-gdb-14.2_20240403-aarch64-apple-darwin21.1.tar.gz",
-              "checksum": "SHA-256:ea757c6bf8c25238f6d2fdcc6bbab25a1b00608a0f9e19b7ddd2f37ddbdc3fb1",
-              "size": "37021423"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-aarch64-apple-darwin21.1.tar.gz",
+              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-aarch64-apple-darwin21.1.tar.gz",
+              "checksum": "SHA-256:893500d6de354a6870820b9398531d8cd37d1cd85f3ae9b1f8a4c070b8048707",
+              "size": "41892363"
             },
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/xtensa-esp-elf-gdb-14.2_20240403-i686-w64-mingw32.zip",
-              "archiveFileName": "xtensa-esp-elf-gdb-14.2_20240403-i686-w64-mingw32.zip",
-              "checksum": "SHA-256:322e8d9b700dc32d8158e3dc55fb85ec55de48d0bb7789375ee39a28d5d655e2",
-              "size": "26302466"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-i686-w64-mingw32.zip",
+              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-i686-w64-mingw32.zip",
+              "checksum": "SHA-256:328181380fccb252105c51a86071edbc5ef63e0114540edc4f8b2d62acf44916",
+              "size": "31307770"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/xtensa-esp-elf-gdb-14.2_20240403-x86_64-w64-mingw32.zip",
-              "archiveFileName": "xtensa-esp-elf-gdb-14.2_20240403-x86_64-w64-mingw32.zip",
-              "checksum": "SHA-256:a27a2fe20f192f8e0a51b8936428b4e1cf8935cfe008ee445cc49f6fc7f6db2e",
-              "size": "28366035"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-x86_64-w64-mingw32.zip",
+              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-x86_64-w64-mingw32.zip",
+              "checksum": "SHA-256:9c1949058d7aa1fa6f6f2d03173659b9f54e3c3940cbeebc1d56ae169c604ab2",
+              "size": "31420687"
             }
           ]
         },
@@ -352,63 +352,63 @@
         },
         {
           "name": "riscv32-esp-elf-gdb",
-          "version": "14.2_20240403",
+          "version": "15.2_20241112",
           "systems": [
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/riscv32-esp-elf-gdb-14.2_20240403-x86_64-linux-gnu.tar.gz",
-              "archiveFileName": "riscv32-esp-elf-gdb-14.2_20240403-x86_64-linux-gnu.tar.gz",
-              "checksum": "SHA-256:ce004bc0bbd71b246800d2d13b239218b272a38bd528e316f21f1af2db8a4b13",
-              "size": "30707431"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-x86_64-linux-gnu.tar.gz",
+              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-x86_64-linux-gnu.tar.gz",
+              "checksum": "SHA-256:bfca245b3d84244ad3b6156496728d916ac5ccc0d7f8e048194b7eba5cdbe047",
+              "size": "35297398"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/riscv32-esp-elf-gdb-14.2_20240403-aarch64-linux-gnu.tar.gz",
-              "archiveFileName": "riscv32-esp-elf-gdb-14.2_20240403-aarch64-linux-gnu.tar.gz",
-              "checksum": "SHA-256:ba10f2866c61410b88c65957274280b1a62e3bed05131654ed9b6758efe18e55",
-              "size": "30824065"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-aarch64-linux-gnu.tar.gz",
+              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-aarch64-linux-gnu.tar.gz",
+              "checksum": "SHA-256:8536da9e3093b8f25e0b5204b04ed4afea432d1fd262f2abb466016d3d750ea6",
+              "size": "34455317"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/riscv32-esp-elf-gdb-14.2_20240403-arm-linux-gnueabi.tar.gz",
-              "archiveFileName": "riscv32-esp-elf-gdb-14.2_20240403-arm-linux-gnueabi.tar.gz",
-              "checksum": "SHA-256:88539db5d987f28827efac7e26080a2803b9b539342ccd2963ccfdd56d7f08f7",
-              "size": "29000575"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-arm-linux-gnueabi.tar.gz",
+              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-arm-linux-gnueabi.tar.gz",
+              "checksum": "SHA-256:33a80d5e6604bb7d08b15492b8ec84c9176245e066d0bf8aad7570786ca44081",
+              "size": "31188203"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/riscv32-esp-elf-gdb-14.2_20240403-i586-linux-gnu.tar.gz",
-              "archiveFileName": "riscv32-esp-elf-gdb-14.2_20240403-i586-linux-gnu.tar.gz",
-              "checksum": "SHA-256:0e628ee37438ab6ba05eb889a76d09e50cb98e0020a16b8e2b935c5cf19b4ed2",
-              "size": "29947521"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-i586-linux-gnu.tar.gz",
+              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-i586-linux-gnu.tar.gz",
+              "checksum": "SHA-256:ba448ecf2c80064013eaacb0e7be514a5ef17516f49ff3e50bc41c5578b8d88e",
+              "size": "34211289"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/riscv32-esp-elf-gdb-14.2_20240403-x86_64-apple-darwin14.tar.gz",
-              "archiveFileName": "riscv32-esp-elf-gdb-14.2_20240403-x86_64-apple-darwin14.tar.gz",
-              "checksum": "SHA-256:8f6bda832d70dad5860a639d55aba4237bd10cbac9f4822db1eece97357b34a9",
-              "size": "44196117"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-x86_64-apple-darwin21.1.tar.gz",
+              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-x86_64-apple-darwin21.1.tar.gz",
+              "checksum": "SHA-256:bdd07c54fe3216eb5c34f92cac514eb4af777c951573f186c33408c75f56bb4b",
+              "size": "52831957"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/riscv32-esp-elf-gdb-14.2_20240403-aarch64-apple-darwin21.1.tar.gz",
-              "archiveFileName": "riscv32-esp-elf-gdb-14.2_20240403-aarch64-apple-darwin21.1.tar.gz",
-              "checksum": "SHA-256:d88b6116e86456c8480ce9bc95aed375a35c0d091f1da0a53b86be0e6ef3d320",
-              "size": "36794404"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-aarch64-apple-darwin21.1.tar.gz",
+              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-aarch64-apple-darwin21.1.tar.gz",
+              "checksum": "SHA-256:9924f439ae77c3346e532a48a0d56330466c33ce1abd8d72b77f9f7f5c3b1196",
+              "size": "42227631"
             },
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/riscv32-esp-elf-gdb-14.2_20240403-i686-w64-mingw32.zip",
-              "archiveFileName": "riscv32-esp-elf-gdb-14.2_20240403-i686-w64-mingw32.zip",
-              "checksum": "SHA-256:d6e7ce05805b0d8d4dd138ad239b98a1adf8da98941867d60760eb1ae5361730",
-              "size": "26486295"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-i686-w64-mingw32.zip",
+              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-i686-w64-mingw32.zip",
+              "checksum": "SHA-256:dcdafd30854b092671f555d844d94b0733e2ffcac8c026b4fb7b8a72ebef0016",
+              "size": "31971712"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v14.2_20240403/riscv32-esp-elf-gdb-14.2_20240403-x86_64-w64-mingw32.zip",
-              "archiveFileName": "riscv32-esp-elf-gdb-14.2_20240403-x86_64-w64-mingw32.zip",
-              "checksum": "SHA-256:5c9f211dc46daf6b96fad09d709284a0f0186fef8947d9f6edd6bca5b5ad4317",
-              "size": "27942579"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-x86_64-w64-mingw32.zip",
+              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-x86_64-w64-mingw32.zip",
+              "checksum": "SHA-256:6ec8b3a073f2c5835321b4b560f8fc56180458204d071da139ff983436ea45e5",
+              "size": "31759225"
             }
           ]
         },

From 042015efc8930c3de0633ad930c8c05ed536aadd Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Tue, 18 Feb 2025 21:09:27 +0200
Subject: [PATCH 012/105] IDF master (#10981)

* IDF master 1160a86b

* fix(ci): Do not compile RainMaker examples on ESP32
---
 .../RainMaker/examples/RMakerCustom/ci.json   |  3 +
 .../RainMaker/examples/RMakerSwitch/ci.json   |  3 +
 package/package_esp32_index.template.json     | 68 +++++++++----------
 3 files changed, 40 insertions(+), 34 deletions(-)

diff --git a/libraries/RainMaker/examples/RMakerCustom/ci.json b/libraries/RainMaker/examples/RMakerCustom/ci.json
index 1c80eda1d90..ce63fe9ccf0 100644
--- a/libraries/RainMaker/examples/RMakerCustom/ci.json
+++ b/libraries/RainMaker/examples/RMakerCustom/ci.json
@@ -1,4 +1,7 @@
 {
+  "targets": {
+    "esp32": false
+  },
   "fqbn_append": "PartitionScheme=rainmaker_4MB",
   "requires": [
     "CONFIG_ESP_RMAKER_WORK_QUEUE_TASK_STACK=[1-9][0-9]*"
diff --git a/libraries/RainMaker/examples/RMakerSwitch/ci.json b/libraries/RainMaker/examples/RMakerSwitch/ci.json
index 1c80eda1d90..ce63fe9ccf0 100644
--- a/libraries/RainMaker/examples/RMakerSwitch/ci.json
+++ b/libraries/RainMaker/examples/RMakerSwitch/ci.json
@@ -1,4 +1,7 @@
 {
+  "targets": {
+    "esp32": false
+  },
   "fqbn_append": "PartitionScheme=rainmaker_4MB",
   "requires": [
     "CONFIG_ESP_RMAKER_WORK_QUEUE_TASK_STACK=[1-9][0-9]*"
diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index 8bbd2e6a4e9..714328f9a17 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-master-1160a86b-v1"
+              "version": "idf-master-1160a86b-v2"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-master-1160a86b-v1",
+          "version": "idf-master-1160a86b-v2",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
-              "size": "405894668"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
+              "size": "406007754"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
-              "size": "405894668"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
+              "size": "406007754"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
-              "size": "405894668"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
+              "size": "406007754"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
-              "size": "405894668"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
+              "size": "406007754"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
-              "size": "405894668"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
+              "size": "406007754"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
-              "size": "405894668"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
+              "size": "406007754"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
-              "size": "405894668"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
+              "size": "406007754"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v1.zip",
-              "checksum": "SHA-256:ab71bb61b12ad109750d4d39200c2aeaa826395f65a2c95c2012d969eb5f76a2",
-              "size": "405894668"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
+              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
+              "size": "406007754"
             }
           ]
         },

From e30e3c30f189aa87d69acb16b672f0ff2a94f1be Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Tue, 25 Feb 2025 10:28:07 +0200
Subject: [PATCH 013/105] IDF master (#10999)

* IDF master c71d74e2

* IDF master 81e8b752

* IDF master 877057db
---
 package/package_esp32_index.template.json | 68 +++++++++++------------
 1 file changed, 34 insertions(+), 34 deletions(-)

diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index 714328f9a17..46f0cd3418a 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-master-1160a86b-v2"
+              "version": "idf-master-877057db-v1"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-master-1160a86b-v2",
+          "version": "idf-master-877057db-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
-              "size": "406007754"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
+              "size": "411930767"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
-              "size": "406007754"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
+              "size": "411930767"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
-              "size": "406007754"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
+              "size": "411930767"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
-              "size": "406007754"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
+              "size": "411930767"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
-              "size": "406007754"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
+              "size": "411930767"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
-              "size": "406007754"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
+              "size": "411930767"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
-              "size": "406007754"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
+              "size": "411930767"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-1160a86b-v2.zip",
-              "checksum": "SHA-256:2050bda30b1d3cc397683f38267744dc45d7e4c4dc857250477117f30db754db",
-              "size": "406007754"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
+              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
+              "size": "411930767"
             }
           ]
         },

From 3fe2fe5311df6fc93cad8cb19e5a234b37605e3d Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Thu, 27 Feb 2025 00:56:51 +0200
Subject: [PATCH 014/105] IDF master 0461e2ff (#11018)

---
 package/package_esp32_index.template.json | 68 +++++++++++------------
 1 file changed, 34 insertions(+), 34 deletions(-)

diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index 46f0cd3418a..f5bf9ed85cd 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-master-877057db-v1"
+              "version": "idf-master-0461e2ff-v1"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-master-877057db-v1",
+          "version": "idf-master-0461e2ff-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
-              "size": "411930767"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
+              "size": "411886500"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
-              "size": "411930767"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
+              "size": "411886500"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
-              "size": "411930767"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
+              "size": "411886500"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
-              "size": "411930767"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
+              "size": "411886500"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
-              "size": "411930767"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
+              "size": "411886500"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
-              "size": "411930767"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
+              "size": "411886500"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
-              "size": "411930767"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
+              "size": "411886500"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-877057db-v1.zip",
-              "checksum": "SHA-256:fcded8de4107841bea5aaeb7bf7b53a336b3d132df29fb09ae6697b187d51920",
-              "size": "411930767"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
+              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
+              "size": "411886500"
             }
           ]
         },

From d66eeb77547290eb5811fe6662ca2f709e747577 Mon Sep 17 00:00:00 2001
From: Jason2866 <24528715+Jason2866@users.noreply.github.com>
Date: Wed, 5 Mar 2025 11:44:51 +0100
Subject: [PATCH 015/105] c5 flash base address is 0x2000 (#11037)

* c5 flash base address is 0x2000

* ci(pre-commit): Apply automatic fixes

---------

Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 cores/esp32/Esp.cpp | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/cores/esp32/Esp.cpp b/cores/esp32/Esp.cpp
index 2b2e1280683..f911b2d5f20 100644
--- a/cores/esp32/Esp.cpp
+++ b/cores/esp32/Esp.cpp
@@ -66,7 +66,7 @@ extern "C" {
 #define ESP_FLASH_IMAGE_BASE 0x2000  // Esp32p4 is located at 0x2000
 #elif CONFIG_IDF_TARGET_ESP32C5
 #include "esp32c5/rom/spi_flash.h"
-#define ESP_FLASH_IMAGE_BASE 0x0000  // Esp32c5 is located at 0x0000
+#define ESP_FLASH_IMAGE_BASE 0x2000  // Esp32c5 is located at 0x2000
 #else
 #error Target CONFIG_IDF_TARGET is not supported
 #endif
@@ -306,11 +306,11 @@ const char *EspClass::getChipModel(void) {
     case CHIP_ESP32H2: return "ESP32-H2";
     case CHIP_ESP32P4: return "ESP32-P4";
 #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
-    case CHIP_ESP32C5: return "ESP32-C5";
+    case CHIP_ESP32C5:  return "ESP32-C5";
     case CHIP_ESP32C61: return "ESP32-C61";
     case CHIP_ESP32H21: return "ESP32-H21";
 #endif
-    default:           return "UNKNOWN";
+    default: return "UNKNOWN";
   }
 #endif
 }

From 7c1ac1ae60672216f942b812dcebc0e97326e9e2 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Mon, 10 Mar 2025 22:19:40 +0200
Subject: [PATCH 016/105] feat(wifi): Add support for 2.4GHz and 5GHz band
 switching (#11045)

* feat(wifi): Add support for 2.4GHz and 5GHz band switching

* ci(pre-commit): Apply automatic fixes

---------

Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 libraries/WiFi/examples/WiFiScan/WiFiScan.ino | 41 ++++++---
 libraries/WiFi/src/WiFiGeneric.cpp            | 88 +++++++++++++++++++
 libraries/WiFi/src/WiFiGeneric.h              |  4 +
 3 files changed, 121 insertions(+), 12 deletions(-)

diff --git a/libraries/WiFi/examples/WiFiScan/WiFiScan.ino b/libraries/WiFi/examples/WiFiScan/WiFiScan.ino
index 15ce367c897..98733adb0bb 100644
--- a/libraries/WiFi/examples/WiFiScan/WiFiScan.ino
+++ b/libraries/WiFi/examples/WiFiScan/WiFiScan.ino
@@ -1,5 +1,5 @@
 /*
- *  This sketch demonstrates how to scan WiFi networks.
+ *  This sketch demonstrates how to scan WiFi networks. For chips that support 5GHz band, separate scans are done for all bands.
  *  The API is based on the Arduino WiFi Shield library, but has significant changes as newer WiFi functions are supported.
  *  E.g. the return value of `encryptionType()` different because more modern encryption is supported.
  */
@@ -7,18 +7,13 @@
 
 void setup() {
   Serial.begin(115200);
-
-  // Set WiFi to station mode and disconnect from an AP if it was previously connected.
-  WiFi.mode(WIFI_STA);
-  WiFi.disconnect();
-  delay(100);
-
+  // Enable Station Interface
+  WiFi.STA.begin();
   Serial.println("Setup done");
 }
 
-void loop() {
+void ScanWiFi() {
   Serial.println("Scan start");
-
   // WiFi.scanNetworks will return the number of networks found.
   int n = WiFi.scanNetworks();
   Serial.println("Scan done");
@@ -54,11 +49,33 @@ void loop() {
       delay(10);
     }
   }
-  Serial.println("");
 
   // Delete the scan result to free memory for code below.
   WiFi.scanDelete();
-
+  Serial.println("-------------------------------------");
+}
+void loop() {
+  Serial.println("-------------------------------------");
+  Serial.println("Default wifi band mode scan:");
+  Serial.println("-------------------------------------");
+  WiFi.setBandMode(WIFI_BAND_MODE_AUTO);
+  ScanWiFi();
+#if CONFIG_SOC_WIFI_SUPPORT_5G
+  // Wait a bit before scanning again.
+  delay(1000);
+  Serial.println("-------------------------------------");
+  Serial.println("2.4 Ghz wifi band mode scan:");
+  Serial.println("-------------------------------------");
+  WiFi.setBandMode(WIFI_BAND_MODE_2G_ONLY);
+  ScanWiFi();
+  // Wait a bit before scanning again.
+  delay(1000);
+  Serial.println("-------------------------------------");
+  Serial.println("5 Ghz wifi band mode scan:");
+  Serial.println("-------------------------------------");
+  WiFi.setBandMode(WIFI_BAND_MODE_5G_ONLY);
+  ScanWiFi();
+#endif
   // Wait a bit before scanning again.
-  delay(5000);
+  delay(10000);
 }
diff --git a/libraries/WiFi/src/WiFiGeneric.cpp b/libraries/WiFi/src/WiFiGeneric.cpp
index aa994963514..6e38e19a29f 100644
--- a/libraries/WiFi/src/WiFiGeneric.cpp
+++ b/libraries/WiFi/src/WiFiGeneric.cpp
@@ -378,6 +378,10 @@ static bool espWiFiStart() {
     log_e("esp_wifi_start 0x%x: %s", err, esp_err_to_name(err));
     return _esp_wifi_started;
   }
+#if SOC_WIFI_SUPPORT_5G
+  log_v("Setting Band Mode to AUTO");
+  esp_wifi_set_band_mode(WIFI_BAND_MODE_AUTO);
+#endif
   return _esp_wifi_started;
 }
 
@@ -729,6 +733,90 @@ wifi_ps_type_t WiFiGenericClass::getSleep() {
   return _sleepEnabled;
 }
 
+/**
+ * control wifi band mode
+ * @param band_mode enum possible band modes
+ * @return ok
+ */
+bool WiFiGenericClass::setBandMode(wifi_band_mode_t band_mode) {
+#if SOC_WIFI_SUPPORT_5G
+  if (!WiFi.STA.started() && !WiFi.AP.started()) {
+    log_e("You need to start WiFi first");
+    return false;
+  }
+  wifi_band_mode_t bm = WIFI_BAND_MODE_AUTO;
+  esp_err_t err = esp_wifi_get_band_mode(&bm);
+  if (err != ESP_OK) {
+    log_e("Failed to get Current Band Mode: 0x%x: %s", err, esp_err_to_name(err));
+    return false;
+  } else if (bm == band_mode) {
+    log_d("No change in Band Mode");
+    return true;
+  } else {
+    log_d("Switching Band Mode from %d to %d", bm, band_mode);
+  }
+#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_ERROR
+  if (WiFi.STA.connected() || WiFi.AP.connected()) {
+    log_e("Your network will get disconnected!");
+  }
+#endif
+  err = esp_wifi_set_band_mode(band_mode);
+  if (err != ESP_OK) {
+    log_e("Failed to set Band Mode: 0x%x: %s", err, esp_err_to_name(err));
+    return false;
+  }
+  delay(100);
+  return true;
+#else
+  if (band_mode == WIFI_BAND_MODE_5G_ONLY) {
+    log_e("This chip supports only 2.4GHz WiFi");
+  }
+  return band_mode != WIFI_BAND_MODE_5G_ONLY;
+#endif
+}
+
+/**
+ * get the current enabled wifi band mode
+ * @return enum band mode
+ */
+wifi_band_mode_t WiFiGenericClass::getBandMode() {
+#if SOC_WIFI_SUPPORT_5G
+  wifi_band_mode_t band_mode = WIFI_BAND_MODE_AUTO;
+  if (!WiFi.STA.started() && !WiFi.AP.started()) {
+    log_e("You need to start WiFi first");
+    return band_mode;
+  }
+  esp_err_t err = esp_wifi_get_band_mode(&band_mode);
+  if (err != ESP_OK) {
+    log_e("Failed to get Band Mode: 0x%x: %s", err, esp_err_to_name(err));
+  }
+  return band_mode;
+#else
+  return WIFI_BAND_MODE_2G_ONLY;
+#endif
+}
+
+/**
+ * get the current active wifi band
+ * @return enum band
+ */
+wifi_band_t WiFiGenericClass::getBand() {
+#if SOC_WIFI_SUPPORT_5G
+  wifi_band_t band = WIFI_BAND_2G;
+  if (!WiFi.STA.started() && !WiFi.AP.started()) {
+    log_e("You need to start WiFi first");
+    return band;
+  }
+  esp_err_t err = esp_wifi_get_band(&band);
+  if (err != ESP_OK) {
+    log_e("Failed to get Band: 0x%x: %s", err, esp_err_to_name(err));
+  }
+  return band;
+#else
+  return WIFI_BAND_2G;
+#endif
+}
+
 /**
  * control wifi tx power
  * @param power enum maximum wifi tx power
diff --git a/libraries/WiFi/src/WiFiGeneric.h b/libraries/WiFi/src/WiFiGeneric.h
index ed216229ed4..8497b4b4f3d 100644
--- a/libraries/WiFi/src/WiFiGeneric.h
+++ b/libraries/WiFi/src/WiFiGeneric.h
@@ -111,6 +111,10 @@ class WiFiGenericClass {
   bool setTxPower(wifi_power_t power);
   wifi_power_t getTxPower();
 
+  bool setBandMode(wifi_band_mode_t band_mode);
+  wifi_band_mode_t getBandMode();
+  wifi_band_t getBand();
+
   bool initiateFTM(uint8_t frm_count = 16, uint16_t burst_period = 2, uint8_t channel = 1, const uint8_t *mac = NULL);
 
   static bool setDualAntennaConfig(uint8_t gpio_ant1, uint8_t gpio_ant2, wifi_rx_ant_t rx_mode, wifi_tx_ant_t tx_mode);

From a61961d5c995106ba89e1361655471938dfc4502 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Fri, 28 Mar 2025 10:48:39 +0200
Subject: [PATCH 017/105] IDF master (#11150)

* IDF master ee77c489

* IDF master ee77c489

* IDF master 50be9735

* IDF master 23c73cdc

* IDF master a45d713b
---
 package/package_esp32_index.template.json | 128 +++++++++++-----------
 1 file changed, 64 insertions(+), 64 deletions(-)

diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index f5bf9ed85cd..1b935fd8acf 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-master-0461e2ff-v1"
+              "version": "idf-master-a45d713b-v1"
             },
             {
               "packager": "esp32",
@@ -76,7 +76,7 @@
             {
               "packager": "esp32",
               "name": "openocd-esp32",
-              "version": "v0.12.0-esp32-20241016"
+              "version": "v0.12.0-esp32-20250226"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-master-0461e2ff-v1",
+          "version": "idf-master-a45d713b-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
-              "size": "411886500"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
+              "size": "420636315"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
-              "size": "411886500"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
+              "size": "420636315"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
-              "size": "411886500"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
+              "size": "420636315"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
-              "size": "411886500"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
+              "size": "420636315"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
-              "size": "411886500"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
+              "size": "420636315"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
-              "size": "411886500"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
+              "size": "420636315"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
-              "size": "411886500"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
+              "size": "420636315"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-0461e2ff-v1.zip",
-              "checksum": "SHA-256:e1413b7d711cbdc4efb3064d6ac25e09068d7a01db3a706bd1426b0fd992e35b",
-              "size": "411886500"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
+              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
+              "size": "420636315"
             }
           ]
         },
@@ -414,56 +414,56 @@
         },
         {
           "name": "openocd-esp32",
-          "version": "v0.12.0-esp32-20241016",
+          "version": "v0.12.0-esp32-20250226",
           "systems": [
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20241016/openocd-esp32-linux-amd64-0.12.0-esp32-20241016.tar.gz",
-              "archiveFileName": "openocd-esp32-linux-amd64-0.12.0-esp32-20241016.tar.gz",
-              "checksum": "SHA-256:e82b0f036dc99244bead5f09a86e91bb2365cbcd1122ac68261e5647942485df",
-              "size": "2398717"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-linux-amd64-0.12.0-esp32-20250226.tar.gz",
+              "archiveFileName": "openocd-esp32-linux-amd64-0.12.0-esp32-20250226.tar.gz",
+              "checksum": "SHA-256:914c726342ba5828e53f41aa454f01f317c42d8e6772d3d874593a6960fc4729",
+              "size": "2414924"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20241016/openocd-esp32-linux-arm64-0.12.0-esp32-20241016.tar.gz",
-              "archiveFileName": "openocd-esp32-linux-arm64-0.12.0-esp32-20241016.tar.gz",
-              "checksum": "SHA-256:8f8daf5bd22ec5d2fa9257b0862ec33da18ee677e023fb9a9eb17f74ce208c76",
-              "size": "2271584"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-linux-arm64-0.12.0-esp32-20250226.tar.gz",
+              "archiveFileName": "openocd-esp32-linux-arm64-0.12.0-esp32-20250226.tar.gz",
+              "checksum": "SHA-256:c44ee99a9209c0234dbbcec86339fd685f5c61a763b29c33eba590bf62db2296",
+              "size": "2293923"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20241016/openocd-esp32-linux-armel-0.12.0-esp32-20241016.tar.gz",
-              "archiveFileName": "openocd-esp32-linux-armel-0.12.0-esp32-20241016.tar.gz",
-              "checksum": "SHA-256:bc9c020ecf20e2000f76cffa44305fd5bc44d2e688ea78cce423399d33f19767",
-              "size": "2414206"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-linux-armel-0.12.0-esp32-20250226.tar.gz",
+              "archiveFileName": "openocd-esp32-linux-armel-0.12.0-esp32-20250226.tar.gz",
+              "checksum": "SHA-256:21ab6af3cf05f9290f4d59f1f381d5094dd2755fc528d3d2feb9334348fc0d8d",
+              "size": "2436071"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20241016/openocd-esp32-macos-0.12.0-esp32-20241016.tar.gz",
-              "archiveFileName": "openocd-esp32-macos-0.12.0-esp32-20241016.tar.gz",
-              "checksum": "SHA-256:02a2dffe801a2d005fa9e614d80ff8173395b2cb0b5d3118d0229d094a9946a7",
-              "size": "2508089"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-macos-0.12.0-esp32-20250226.tar.gz",
+              "archiveFileName": "openocd-esp32-macos-0.12.0-esp32-20250226.tar.gz",
+              "checksum": "SHA-256:0b5751699e93b6d101381611c96216ddff8c7dfd16425c610993fa27993f9a0a",
+              "size": "2525387"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20241016/openocd-esp32-macos-arm64-0.12.0-esp32-20241016.tar.gz",
-              "archiveFileName": "openocd-esp32-macos-arm64-0.12.0-esp32-20241016.tar.gz",
-              "checksum": "SHA-256:c382f9e884d6565cb6089bff5f200f4810994667d885f062c3d3c5625a0fa9d6",
-              "size": "2552569"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-macos-arm64-0.12.0-esp32-20250226.tar.gz",
+              "archiveFileName": "openocd-esp32-macos-arm64-0.12.0-esp32-20250226.tar.gz",
+              "checksum": "SHA-256:8bffbbb594b27a4971a3922792135f8c836fff26991f7f450094386920263531",
+              "size": "2568843"
             },
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20241016/openocd-esp32-win32-0.12.0-esp32-20241016.zip",
-              "archiveFileName": "openocd-esp32-win32-0.12.0-esp32-20241016.zip",
-              "checksum": "SHA-256:3b5d615e0a72cc771a45dd469031312d5881c01d7b6bc9edb29b8b6bda8c2e90",
-              "size": "2946244"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-win32-0.12.0-esp32-20250226.zip",
+              "archiveFileName": "openocd-esp32-win32-0.12.0-esp32-20250226.zip",
+              "checksum": "SHA-256:aaf3c955bb4eb47805a1ba108dfd07a8a56ce720cb40194a354362b5f0961230",
+              "size": "2960226"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20241016/openocd-esp32-win64-0.12.0-esp32-20241016.zip",
-              "archiveFileName": "openocd-esp32-win64-0.12.0-esp32-20241016.zip",
-              "checksum": "SHA-256:5e7b2fd1947d3a8625f6a11db7a2340cf2f41ff4c61284c022c7d7c32b18780a",
-              "size": "2946244"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-win64-0.12.0-esp32-20250226.zip",
+              "archiveFileName": "openocd-esp32-win64-0.12.0-esp32-20250226.zip",
+              "checksum": "SHA-256:79baf35325117a53093b62f6b9bee677dd12275d7066e3f8a274d2a80e986b6e",
+              "size": "2960225"
             }
           ]
         },

From 42ae2426affacf7162770b9399b486eb7954203f Mon Sep 17 00:00:00 2001
From: Jason2866 <24528715+Jason2866@users.noreply.github.com>
Date: Mon, 21 Apr 2025 18:32:51 +0200
Subject: [PATCH 018/105] fix C5 compile (#11255)

---
 cores/esp32/esp32-hal-uart.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/cores/esp32/esp32-hal-uart.c b/cores/esp32/esp32-hal-uart.c
index ca88edbca27..21540b3e95a 100644
--- a/cores/esp32/esp32-hal-uart.c
+++ b/cores/esp32/esp32-hal-uart.c
@@ -1157,7 +1157,11 @@ bool uartSetClockSource(uint8_t uartNum, uart_sclk_t clkSrc) {
   if (uart->num >= SOC_UART_HP_NUM) {
     switch (clkSrc) {
       case UART_SCLK_XTAL:    uart->_uart_clock_source = LP_UART_SCLK_XTAL_D2; break;
+#if CONFIG_IDF_TARGET_ESP32C5
+      case UART_SCLK_RTC:     uart->_uart_clock_source = LP_UART_SCLK_RC_FAST; break;
+#else
       case UART_SCLK_RTC:     uart->_uart_clock_source = LP_UART_SCLK_LP_FAST; break;
+#endif
       case UART_SCLK_DEFAULT:
       default:                uart->_uart_clock_source = LP_UART_SCLK_DEFAULT;
     }

From 03e9c45084c389436869f1ae649549e245866ade Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Wed, 23 Apr 2025 15:50:58 +0300
Subject: [PATCH 019/105] IDF master (#11204)

* fix(esp-now): Update TX Callback

* IDF master d930a386

---------

Co-authored-by: Jason2866 <24528715+Jason2866@users.noreply.github.com>
---
 libraries/ESP_NOW/src/ESP32_NOW.cpp       |   5 +
 package/package_esp32_index.template.json | 204 +++++++++++-----------
 2 files changed, 107 insertions(+), 102 deletions(-)

diff --git a/libraries/ESP_NOW/src/ESP32_NOW.cpp b/libraries/ESP_NOW/src/ESP32_NOW.cpp
index 6fd3ff0a0b1..83fec4c4529 100644
--- a/libraries/ESP_NOW/src/ESP32_NOW.cpp
+++ b/libraries/ESP_NOW/src/ESP32_NOW.cpp
@@ -129,7 +129,12 @@ static void _esp_now_rx_cb(const esp_now_recv_info_t *info, const uint8_t *data,
   }
 }
 
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
+static void _esp_now_tx_cb(const esp_now_send_info_t *tx_info, esp_now_send_status_t status) {
+  const uint8_t *mac_addr = tx_info->des_addr;
+#else
 static void _esp_now_tx_cb(const uint8_t *mac_addr, esp_now_send_status_t status) {
+#endif
   log_v(MACSTR " : %s", MAC2STR(mac_addr), (status == ESP_NOW_SEND_SUCCESS) ? "SUCCESS" : "FAILED");
   //find the peer and call it's callback
   for (uint8_t i = 0; i < ESP_NOW_MAX_TOTAL_PEER_NUM; i++) {
diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index 1b935fd8acf..a0d78ebc47e 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-master-a45d713b-v1"
+              "version": "idf-master-d930a386-v1"
             },
             {
               "packager": "esp32",
@@ -61,7 +61,7 @@
             {
               "packager": "esp32",
               "name": "xtensa-esp-elf-gdb",
-              "version": "15.2_20241112"
+              "version": "16.2_20250324"
             },
             {
               "packager": "esp32",
@@ -71,7 +71,7 @@
             {
               "packager": "esp32",
               "name": "riscv32-esp-elf-gdb",
-              "version": "15.2_20241112"
+              "version": "16.2_20250324"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-master-a45d713b-v1",
+          "version": "idf-master-d930a386-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
-              "size": "420636315"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
+              "size": "422376381"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
-              "size": "420636315"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
+              "size": "422376381"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
-              "size": "420636315"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
+              "size": "422376381"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
-              "size": "420636315"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
+              "size": "422376381"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
-              "size": "420636315"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
+              "size": "422376381"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
-              "size": "420636315"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
+              "size": "422376381"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
-              "size": "420636315"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
+              "size": "422376381"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-a45d713b-v1.zip",
-              "checksum": "SHA-256:52aec557b9744e721770853c67c4ee6a391debd7bb779f654bea0e5113658786",
-              "size": "420636315"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
+              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
+              "size": "422376381"
             }
           ]
         },
@@ -228,63 +228,63 @@
         },
         {
           "name": "xtensa-esp-elf-gdb",
-          "version": "15.2_20241112",
+          "version": "16.2_20250324",
           "systems": [
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-x86_64-linux-gnu.tar.gz",
-              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-x86_64-linux-gnu.tar.gz",
-              "checksum": "SHA-256:18774349d2b1c7d7f5ba984563f7022aef4a3df4b706ed8821c53266f599343d",
-              "size": "35179121"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/xtensa-esp-elf-gdb-16.2_20250324-x86_64-linux-gnu.tar.gz",
+              "archiveFileName": "xtensa-esp-elf-gdb-16.2_20250324-x86_64-linux-gnu.tar.gz",
+              "checksum": "SHA-256:27b58ab12248e04277c4fdc74038cf0a001d5142df091ab94939ad35053738fd",
+              "size": "36361058"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-aarch64-linux-gnu.tar.gz",
-              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-aarch64-linux-gnu.tar.gz",
-              "checksum": "SHA-256:77cb3b2c85d6cfbb40b7f99eebbc2b1c3f4fe13eba20b3da798bdbbc6eb8e87c",
-              "size": "34295046"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/xtensa-esp-elf-gdb-16.2_20250324-aarch64-linux-gnu.tar.gz",
+              "archiveFileName": "xtensa-esp-elf-gdb-16.2_20250324-aarch64-linux-gnu.tar.gz",
+              "checksum": "SHA-256:24f85aa778e1605098a13ff7bd29d5760767faf012705c8915cb08b32cad0206",
+              "size": "35442104"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-arm-linux-gnueabi.tar.gz",
-              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-arm-linux-gnueabi.tar.gz",
-              "checksum": "SHA-256:b87af0539de118eb9d43a4a89c8c1b0a6ab2557560015155104c44f91b5c4aa0",
-              "size": "30338727"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/xtensa-esp-elf-gdb-16.2_20250324-arm-linux-gnueabi.tar.gz",
+              "archiveFileName": "xtensa-esp-elf-gdb-16.2_20250324-arm-linux-gnueabi.tar.gz",
+              "checksum": "SHA-256:c73e43038b6d50374cd0ee714370ce748189e0b00404d581babd2bb0115c4785",
+              "size": "31260410"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-i586-linux-gnu.tar.gz",
-              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-i586-linux-gnu.tar.gz",
-              "checksum": "SHA-256:2c7531bd390928fed479999ac9089b39a25f56ca4f4cc330db7d7a633a37405b",
-              "size": "33906121"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/xtensa-esp-elf-gdb-16.2_20250324-i586-linux-gnu.tar.gz",
+              "archiveFileName": "xtensa-esp-elf-gdb-16.2_20250324-i586-linux-gnu.tar.gz",
+              "checksum": "SHA-256:dc7b8aad0fb1c6a1abfdb8dff4f08221ea08a0f28fb837f181969ac1174d4dc6",
+              "size": "35067894"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-x86_64-apple-darwin21.1.tar.gz",
-              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-x86_64-apple-darwin21.1.tar.gz",
-              "checksum": "SHA-256:ba2907be9a4c22c4e418f42ec84cf57401570a71dabbe69425227114ebf351a7",
-              "size": "52502302"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/xtensa-esp-elf-gdb-16.2_20250324-x86_64-apple-darwin21.1.tar.gz",
+              "archiveFileName": "xtensa-esp-elf-gdb-16.2_20250324-x86_64-apple-darwin21.1.tar.gz",
+              "checksum": "SHA-256:398c429cfe696bad01d636c5488cadc87b20471c1b5ed02c60eee5ef2a775c93",
+              "size": "54992785"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-aarch64-apple-darwin21.1.tar.gz",
-              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-aarch64-apple-darwin21.1.tar.gz",
-              "checksum": "SHA-256:893500d6de354a6870820b9398531d8cd37d1cd85f3ae9b1f8a4c070b8048707",
-              "size": "41892363"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/xtensa-esp-elf-gdb-16.2_20250324-aarch64-apple-darwin21.1.tar.gz",
+              "archiveFileName": "xtensa-esp-elf-gdb-16.2_20250324-aarch64-apple-darwin21.1.tar.gz",
+              "checksum": "SHA-256:b6d85c0d76d653bb55f9d06b0cd509eab7e99db541c88b8c849c64827e9d74a9",
+              "size": "43538967"
             },
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-i686-w64-mingw32.zip",
-              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-i686-w64-mingw32.zip",
-              "checksum": "SHA-256:328181380fccb252105c51a86071edbc5ef63e0114540edc4f8b2d62acf44916",
-              "size": "31307770"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/xtensa-esp-elf-gdb-16.2_20250324-i686-w64-mingw32.zip",
+              "archiveFileName": "xtensa-esp-elf-gdb-16.2_20250324-i686-w64-mingw32.zip",
+              "checksum": "SHA-256:f748d6b65fdf66733b82e12d0d85a05e3134122416280379df129cfebe2aa4b2",
+              "size": "32189419"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/xtensa-esp-elf-gdb-15.2_20241112-x86_64-w64-mingw32.zip",
-              "archiveFileName": "xtensa-esp-elf-gdb-15.2_20241112-x86_64-w64-mingw32.zip",
-              "checksum": "SHA-256:9c1949058d7aa1fa6f6f2d03173659b9f54e3c3940cbeebc1d56ae169c604ab2",
-              "size": "31420687"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/xtensa-esp-elf-gdb-16.2_20250324-x86_64-w64-mingw32.zip",
+              "archiveFileName": "xtensa-esp-elf-gdb-16.2_20250324-x86_64-w64-mingw32.zip",
+              "checksum": "SHA-256:e970fc3ec8a1d0acee2432e91e0a01b348613a0425aacfa981b2fc505fe920cc",
+              "size": "32290997"
             }
           ]
         },
@@ -352,63 +352,63 @@
         },
         {
           "name": "riscv32-esp-elf-gdb",
-          "version": "15.2_20241112",
+          "version": "16.2_20250324",
           "systems": [
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-x86_64-linux-gnu.tar.gz",
-              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-x86_64-linux-gnu.tar.gz",
-              "checksum": "SHA-256:bfca245b3d84244ad3b6156496728d916ac5ccc0d7f8e048194b7eba5cdbe047",
-              "size": "35297398"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/riscv32-esp-elf-gdb-16.2_20250324-x86_64-linux-gnu.tar.gz",
+              "archiveFileName": "riscv32-esp-elf-gdb-16.2_20250324-x86_64-linux-gnu.tar.gz",
+              "checksum": "SHA-256:f9b172d8d72d0a1e2b0b80127df29263a0cb0d0c4e998e09c27031bfac09f3ec",
+              "size": "36528201"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-aarch64-linux-gnu.tar.gz",
-              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-aarch64-linux-gnu.tar.gz",
-              "checksum": "SHA-256:8536da9e3093b8f25e0b5204b04ed4afea432d1fd262f2abb466016d3d750ea6",
-              "size": "34455317"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/riscv32-esp-elf-gdb-16.2_20250324-aarch64-linux-gnu.tar.gz",
+              "archiveFileName": "riscv32-esp-elf-gdb-16.2_20250324-aarch64-linux-gnu.tar.gz",
+              "checksum": "SHA-256:68bb6a85fb58b8a738f799e8fb4fa1f56cfeffc4de803ceb03c8a33cb2cd919d",
+              "size": "35643464"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-arm-linux-gnueabi.tar.gz",
-              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-arm-linux-gnueabi.tar.gz",
-              "checksum": "SHA-256:33a80d5e6604bb7d08b15492b8ec84c9176245e066d0bf8aad7570786ca44081",
-              "size": "31188203"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/riscv32-esp-elf-gdb-16.2_20250324-arm-linux-gnueabi.tar.gz",
+              "archiveFileName": "riscv32-esp-elf-gdb-16.2_20250324-arm-linux-gnueabi.tar.gz",
+              "checksum": "SHA-256:673038ab9fb2b7391ff9252824194e3b9e40668efe9ce54d1e582a9d6c51f04a",
+              "size": "32154574"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-i586-linux-gnu.tar.gz",
-              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-i586-linux-gnu.tar.gz",
-              "checksum": "SHA-256:ba448ecf2c80064013eaacb0e7be514a5ef17516f49ff3e50bc41c5578b8d88e",
-              "size": "34211289"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/riscv32-esp-elf-gdb-16.2_20250324-i586-linux-gnu.tar.gz",
+              "archiveFileName": "riscv32-esp-elf-gdb-16.2_20250324-i586-linux-gnu.tar.gz",
+              "checksum": "SHA-256:62f05d5fe08145b25e423dd0b3f1ae260be99abf5462b8cfd918bf2231e26e30",
+              "size": "35410891"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-x86_64-apple-darwin21.1.tar.gz",
-              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-x86_64-apple-darwin21.1.tar.gz",
-              "checksum": "SHA-256:bdd07c54fe3216eb5c34f92cac514eb4af777c951573f186c33408c75f56bb4b",
-              "size": "52831957"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/riscv32-esp-elf-gdb-16.2_20250324-x86_64-apple-darwin21.1.tar.gz",
+              "archiveFileName": "riscv32-esp-elf-gdb-16.2_20250324-x86_64-apple-darwin21.1.tar.gz",
+              "checksum": "SHA-256:63ae12cfbab648e2d2ca7a700a0c615c4f36a6fbe6876c11ba108115ee0d60f2",
+              "size": "55359246"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-aarch64-apple-darwin21.1.tar.gz",
-              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-aarch64-apple-darwin21.1.tar.gz",
-              "checksum": "SHA-256:9924f439ae77c3346e532a48a0d56330466c33ce1abd8d72b77f9f7f5c3b1196",
-              "size": "42227631"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/riscv32-esp-elf-gdb-16.2_20250324-aarch64-apple-darwin21.1.tar.gz",
+              "archiveFileName": "riscv32-esp-elf-gdb-16.2_20250324-aarch64-apple-darwin21.1.tar.gz",
+              "checksum": "SHA-256:bfbe49774f839020cef988537da0a06896dfe4a382674c62285361ed9bd4aee3",
+              "size": "43926592"
             },
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-i686-w64-mingw32.zip",
-              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-i686-w64-mingw32.zip",
-              "checksum": "SHA-256:dcdafd30854b092671f555d844d94b0733e2ffcac8c026b4fb7b8a72ebef0016",
-              "size": "31971712"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/riscv32-esp-elf-gdb-16.2_20250324-i686-w64-mingw32.zip",
+              "archiveFileName": "riscv32-esp-elf-gdb-16.2_20250324-i686-w64-mingw32.zip",
+              "checksum": "SHA-256:e8b84eec990ff514729b3770edf2b543f36670f43663ce0c3b624fb4884812ca",
+              "size": "32914955"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v15.2_20241112/riscv32-esp-elf-gdb-15.2_20241112-x86_64-w64-mingw32.zip",
-              "archiveFileName": "riscv32-esp-elf-gdb-15.2_20241112-x86_64-w64-mingw32.zip",
-              "checksum": "SHA-256:6ec8b3a073f2c5835321b4b560f8fc56180458204d071da139ff983436ea45e5",
-              "size": "31759225"
+              "url": "https://github.com/espressif/binutils-gdb/releases/download/esp-gdb-v16.2_20250324/riscv32-esp-elf-gdb-16.2_20250324-x86_64-w64-mingw32.zip",
+              "archiveFileName": "riscv32-esp-elf-gdb-16.2_20250324-x86_64-w64-mingw32.zip",
+              "checksum": "SHA-256:37c79178900c19ca7487c26af4b5ad6b0d3f34683bd0e9c2ddd39038c999e429",
+              "size": "32667353"
             }
           ]
         },

From b115acea40b2381bc00e07944d926fe726d05ef5 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Thu, 1 May 2025 02:15:03 +0300
Subject: [PATCH 020/105] IDF master (#11289)

* fix(libs): Ensure compilation with ESP32-C5

* fix(i2c): Update I2C Slave init call

* IDF master 465b159c

* ci(simple_ble): Add check for BLE supported

* IDF master 38628f98

---------

Co-authored-by: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
---
 cores/esp32/esp32-hal-i2c-slave.c             |  7 ++
 idf_component.yml                             | 18 ++---
 libraries/BluetoothSerial/src/BTAddress.cpp   |  4 +-
 libraries/BluetoothSerial/src/BTAddress.h     |  4 +-
 .../BluetoothSerial/src/BTAdvertisedDevice.h  |  6 +-
 .../src/BTAdvertisedDeviceSet.cpp             |  4 +-
 libraries/BluetoothSerial/src/BTScan.h        |  7 +-
 .../BluetoothSerial/src/BTScanResultsSet.cpp  |  4 +-
 .../BluetoothSerial/src/BluetoothSerial.cpp   |  3 +-
 .../BluetoothSerial/src/BluetoothSerial.h     |  3 +-
 .../examples/SimpleBleDevice/ci.json          |  1 +
 libraries/SimpleBLE/src/SimpleBLE.cpp         |  3 +-
 libraries/SimpleBLE/src/SimpleBLE.h           |  3 +-
 package/package_esp32_index.template.json     | 68 +++++++++----------
 14 files changed, 80 insertions(+), 55 deletions(-)

diff --git a/cores/esp32/esp32-hal-i2c-slave.c b/cores/esp32/esp32-hal-i2c-slave.c
index 0e01259da61..1d92a55ae15 100644
--- a/cores/esp32/esp32-hal-i2c-slave.c
+++ b/cores/esp32/esp32-hal-i2c-slave.c
@@ -43,6 +43,7 @@
 #include "soc/i2c_struct.h"
 #include "soc/periph_defs.h"
 #include "hal/i2c_ll.h"
+#include "hal/i2c_types.h"
 #ifndef CONFIG_IDF_TARGET_ESP32C5
 #include "hal/clk_gate_ll.h"
 #endif
@@ -337,7 +338,13 @@ esp_err_t i2cSlaveInit(uint8_t num, int sda, int scl, uint16_t slaveID, uint32_t
   }
 #endif  // !defined(CONFIG_IDF_TARGET_ESP32P4)
 
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
+  i2c_ll_set_mode(i2c->dev, I2C_BUS_MODE_SLAVE);
+  i2c_ll_enable_pins_open_drain(i2c->dev, true);
+#else
   i2c_ll_slave_init(i2c->dev);
+#endif
+
 #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
   i2c_ll_enable_fifo_mode(i2c->dev, true);
 #else
diff --git a/idf_component.yml b/idf_component.yml
index c1fc614cae5..f0e3f84b28d 100644
--- a/idf_component.yml
+++ b/idf_component.yml
@@ -57,12 +57,12 @@ dependencies:
     version: "==1.6.3"
     require: public
     rules:
-      - if: "target not in [esp32c2, esp32p4]"
+      - if: "target not in [esp32c2, esp32p4, esp32c5]"
   espressif/esp-zigbee-lib:
     version: "==1.6.3"
     require: public
     rules:
-      - if: "target not in [esp32c2, esp32p4]"
+      - if: "target not in [esp32c2, esp32p4, esp32c5]"
   espressif/esp-dsp:
     version: "^1.3.4"
     rules:
@@ -73,32 +73,32 @@ dependencies:
   espressif/esp_rainmaker:
     version: "1.5.2"
     rules:
-      - if: "target not in [esp32c2, esp32p4]"
+      - if: "target not in [esp32c2, esp32p4, esp32c5]"
   espressif/rmaker_common:
     version: "1.4.6"
     rules:
-      - if: "target not in [esp32c2, esp32p4]"
+      - if: "target not in [esp32c2, esp32p4, esp32c5]"
   espressif/esp_insights:
     version: "1.2.2"
     rules:
-      - if: "target not in [esp32c2, esp32p4]"
+      - if: "target not in [esp32c2, esp32p4, esp32c5]"
   # New version breaks esp_insights 1.0.1
   espressif/esp_diag_data_store:
     version: "1.0.2"
     rules:
-      - if: "target not in [esp32c2, esp32p4]"
+      - if: "target not in [esp32c2, esp32p4, esp32c5]"
   espressif/esp_diagnostics:
     version: "1.2.1"
     rules:
-      - if: "target not in [esp32c2, esp32p4]"
+      - if: "target not in [esp32c2, esp32p4, esp32c5]"
   espressif/cbor:
     version: "0.6.0~1"
     rules:
-      - if: "target not in [esp32c2, esp32p4]"
+      - if: "target not in [esp32c2, esp32p4, esp32c5]"
   espressif/qrcode:
     version: "0.1.0~2"
     rules:
-      - if: "target not in [esp32c2, esp32p4]"
+      - if: "target not in [esp32c2, esp32p4, esp32c5]"
   # RainMaker End
   espressif/esp-sr:
     version: "^1.4.2"
diff --git a/libraries/BluetoothSerial/src/BTAddress.cpp b/libraries/BluetoothSerial/src/BTAddress.cpp
index 6a6de6522bd..6dc05f3aafb 100644
--- a/libraries/BluetoothSerial/src/BTAddress.cpp
+++ b/libraries/BluetoothSerial/src/BTAddress.cpp
@@ -7,7 +7,9 @@
  *      Author: Thomas M. (ArcticSnowSky)
  */
 #include "sdkconfig.h"
-#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
+#include "soc/soc_caps.h"
+
+#if SOC_BT_SUPPORTED && defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
 
 #include "BTAddress.h"
 #include <string>
diff --git a/libraries/BluetoothSerial/src/BTAddress.h b/libraries/BluetoothSerial/src/BTAddress.h
index a2af9247fb0..ece3ae83525 100644
--- a/libraries/BluetoothSerial/src/BTAddress.h
+++ b/libraries/BluetoothSerial/src/BTAddress.h
@@ -10,7 +10,9 @@
 #ifndef COMPONENTS_CPP_UTILS_BTADDRESS_H_
 #define COMPONENTS_CPP_UTILS_BTADDRESS_H_
 #include "sdkconfig.h"
-#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
+#include "soc/soc_caps.h"
+
+#if SOC_BT_SUPPORTED && defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
 #include <esp_gap_bt_api.h>  // ESP32 BT
 #include <Arduino.h>
 
diff --git a/libraries/BluetoothSerial/src/BTAdvertisedDevice.h b/libraries/BluetoothSerial/src/BTAdvertisedDevice.h
index 63c19c908b6..53aa2629b56 100644
--- a/libraries/BluetoothSerial/src/BTAdvertisedDevice.h
+++ b/libraries/BluetoothSerial/src/BTAdvertisedDevice.h
@@ -5,9 +5,11 @@
  *      Author: Thomas M. (ArcticSnowSky)
  */
 
-#ifndef __BTADVERTISEDDEVICE_H__
-#define __BTADVERTISEDDEVICE_H__
+#pragma once
+#include "sdkconfig.h"
+#include "soc/soc_caps.h"
 
+#if SOC_BT_SUPPORTED && defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
 #include "BTAddress.h"
 #include <string>
 
diff --git a/libraries/BluetoothSerial/src/BTAdvertisedDeviceSet.cpp b/libraries/BluetoothSerial/src/BTAdvertisedDeviceSet.cpp
index ed6076a3103..9afc28547e5 100644
--- a/libraries/BluetoothSerial/src/BTAdvertisedDeviceSet.cpp
+++ b/libraries/BluetoothSerial/src/BTAdvertisedDeviceSet.cpp
@@ -6,7 +6,9 @@
  */
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
+#include "soc/soc_caps.h"
+
+#if SOC_BT_SUPPORTED && defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
 
 //#include <map>
 
diff --git a/libraries/BluetoothSerial/src/BTScan.h b/libraries/BluetoothSerial/src/BTScan.h
index a08f68cd7c2..6fd2daf9f6d 100644
--- a/libraries/BluetoothSerial/src/BTScan.h
+++ b/libraries/BluetoothSerial/src/BTScan.h
@@ -5,8 +5,11 @@
  *      Author: Thomas M. (ArcticSnowSky)
  */
 
-#ifndef __BTSCAN_H__
-#define __BTSCAN_H__
+#pragma once
+#include "sdkconfig.h"
+#include "soc/soc_caps.h"
+
+#if SOC_BT_SUPPORTED && defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
 
 #include <map>
 #include <string>
diff --git a/libraries/BluetoothSerial/src/BTScanResultsSet.cpp b/libraries/BluetoothSerial/src/BTScanResultsSet.cpp
index 3633c010eae..02459b081ba 100644
--- a/libraries/BluetoothSerial/src/BTScanResultsSet.cpp
+++ b/libraries/BluetoothSerial/src/BTScanResultsSet.cpp
@@ -6,7 +6,9 @@
  */
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
+#include "soc/soc_caps.h"
+
+#if SOC_BT_SUPPORTED && defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
 
 #include <esp_err.h>
 
diff --git a/libraries/BluetoothSerial/src/BluetoothSerial.cpp b/libraries/BluetoothSerial/src/BluetoothSerial.cpp
index 3d00504c1b1..b7eede93ee6 100644
--- a/libraries/BluetoothSerial/src/BluetoothSerial.cpp
+++ b/libraries/BluetoothSerial/src/BluetoothSerial.cpp
@@ -19,8 +19,9 @@
 #include <cstring>
 #include "freertos/FreeRTOS.h"
 #include "freertos/task.h"
+#include "soc/soc_caps.h"
 
-#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
+#if SOC_BT_SUPPORTED && defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
 
 #ifdef ARDUINO_ARCH_ESP32
 #include "esp32-hal-log.h"
diff --git a/libraries/BluetoothSerial/src/BluetoothSerial.h b/libraries/BluetoothSerial/src/BluetoothSerial.h
index d59fbf1f714..8cb6edb876c 100644
--- a/libraries/BluetoothSerial/src/BluetoothSerial.h
+++ b/libraries/BluetoothSerial/src/BluetoothSerial.h
@@ -16,8 +16,9 @@
 #define _BLUETOOTH_SERIAL_H_
 
 #include "sdkconfig.h"
+#include "soc/soc_caps.h"
 
-#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
+#if SOC_BT_SUPPORTED && defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
 
 #include "Arduino.h"
 #include "Stream.h"
diff --git a/libraries/SimpleBLE/examples/SimpleBleDevice/ci.json b/libraries/SimpleBLE/examples/SimpleBleDevice/ci.json
index d33a23f332e..3b6a150b31a 100644
--- a/libraries/SimpleBLE/examples/SimpleBleDevice/ci.json
+++ b/libraries/SimpleBLE/examples/SimpleBleDevice/ci.json
@@ -1,5 +1,6 @@
 {
   "requires": [
+    "CONFIG_SOC_BLE_SUPPORTED=y",
     "CONFIG_BT_ENABLED=y",
     "CONFIG_BLUEDROID_ENABLED=y"
   ]
diff --git a/libraries/SimpleBLE/src/SimpleBLE.cpp b/libraries/SimpleBLE/src/SimpleBLE.cpp
index 3c4ed915c05..3f1f2bbd1c1 100644
--- a/libraries/SimpleBLE/src/SimpleBLE.cpp
+++ b/libraries/SimpleBLE/src/SimpleBLE.cpp
@@ -13,8 +13,9 @@
 // limitations under the License.
 
 #include "sdkconfig.h"
+#include "soc/soc_caps.h"
 
-#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
+#if SOC_BT_SUPPORTED && defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
 
 #include "SimpleBLE.h"
 #include "esp32-hal-log.h"
diff --git a/libraries/SimpleBLE/src/SimpleBLE.h b/libraries/SimpleBLE/src/SimpleBLE.h
index 23c1cdb593f..df1ee751f10 100644
--- a/libraries/SimpleBLE/src/SimpleBLE.h
+++ b/libraries/SimpleBLE/src/SimpleBLE.h
@@ -16,8 +16,9 @@
 #define _SIMPLE_BLE_H_
 
 #include "sdkconfig.h"
+#include "soc/soc_caps.h"
 
-#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
+#if SOC_BT_SUPPORTED && defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED)
 
 #include <cstdint>
 #include <cstdio>
diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index a0d78ebc47e..63027704d8a 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-master-d930a386-v1"
+              "version": "idf-master-38628f98-v1"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-master-d930a386-v1",
+          "version": "idf-master-38628f98-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
-              "size": "422376381"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
+              "size": "398323971"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
-              "size": "422376381"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
+              "size": "398323971"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
-              "size": "422376381"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
+              "size": "398323971"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
-              "size": "422376381"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
+              "size": "398323971"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
-              "size": "422376381"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
+              "size": "398323971"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
-              "size": "422376381"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
+              "size": "398323971"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
-              "size": "422376381"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
+              "size": "398323971"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-d930a386-v1.zip",
-              "checksum": "SHA-256:0310daa4f08f807f2bf3babd2587c2694df64c70e367863eadf5020636b717ae",
-              "size": "422376381"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
+              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
+              "size": "398323971"
             }
           ]
         },

From 602f1f6e7fbc56e36068c9521272d64d40e4df30 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Wed, 7 May 2025 16:24:33 +0300
Subject: [PATCH 021/105] IDF master (#11342)

* fix(ci): ESP32-P4 hosted compile fail (#11341)

* fix(ci): Update changes for P4 and C5 builds with latest IDF

* IDF master aaebc374

* ci(pre-commit): Apply automatic fixes

---------

Co-authored-by: Jason2866 <24528715+Jason2866@users.noreply.github.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 CMakeLists.txt                            |   2 +-
 cores/esp32/chip-debug-report.cpp         |   7 +-
 idf_component.yml                         |   2 +-
 libraries/WiFi/src/WiFiGeneric.cpp        |  12 +-
 package/package_esp32_index.template.json | 128 +++++++++++-----------
 5 files changed, 81 insertions(+), 70 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5ba9c999d81..9e981130715 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -362,7 +362,7 @@ set(priv_requires fatfs nvs_flash app_update spiffs bootloader_support bt esp_hi
 if(NOT CONFIG_ARDUINO_SELECTIVE_COMPILATION OR CONFIG_ARDUINO_SELECTIVE_OpenThread)
   #if(CONFIG_SOC_IEEE802154_SUPPORTED) # Does not work!
   #if(CONFIG_OPENTHREAD_ENABLED) # Does not work!
-  if(IDF_TARGET STREQUAL "esp32c6" OR IDF_TARGET STREQUAL "esp32h2") # Sadly only this works
+  if(IDF_TARGET STREQUAL "esp32c6" OR IDF_TARGET STREQUAL "esp32h2" OR IDF_TARGET STREQUAL "esp32c5") # Sadly only this works
     list(APPEND requires openthread)
   endif()
 endif()
diff --git a/cores/esp32/chip-debug-report.cpp b/cores/esp32/chip-debug-report.cpp
index 281c7bdb62d..8592031ee3f 100644
--- a/cores/esp32/chip-debug-report.cpp
+++ b/cores/esp32/chip-debug-report.cpp
@@ -68,7 +68,8 @@ static void printPkgVersion(void) {
   uint32_t pkg_ver = REG_GET_FIELD(EFUSE_RD_MAC_SYS_2_REG, EFUSE_PKG_VERSION);
   chip_report_printf("%lu", pkg_ver);
 #elif CONFIG_IDF_TARGET_ESP32C5
-  uint32_t pkg_ver = REG_GET_FIELD(EFUSE_RD_MAC_SYS2_REG, EFUSE_PKG_VERSION);
+  // ToDo: Update this line when EFUSE_PKG_VERSION is available again for ESP32-C5
+  uint32_t pkg_ver = 0;  //REG_GET_FIELD(EFUSE_RD_MAC_SYS2_REG, EFUSE_PKG_VERSION);
   chip_report_printf("%lu", pkg_ver);
 #else
   chip_report_printf("Unknown");
@@ -92,11 +93,11 @@ static void printChipInfo(void) {
     case CHIP_ESP32H2: chip_report_printf("ESP32-H2\n"); break;
     case CHIP_ESP32P4: chip_report_printf("ESP32-P4\n"); break;
 #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
-    case CHIP_ESP32C5: chip_report_printf("ESP32-C5\n"); break;
+    case CHIP_ESP32C5:  chip_report_printf("ESP32-C5\n"); break;
     case CHIP_ESP32C61: chip_report_printf("ESP32-C61\n"); break;
     case CHIP_ESP32H21: chip_report_printf("ESP32-H21\n"); break;
 #endif
-    default:           chip_report_printf("Unknown %d\n", info.model); break;
+    default: chip_report_printf("Unknown %d\n", info.model); break;
   }
   printPkgVersion();
   chip_report_printf("  Revision          : %.2f\n", (float)(info.revision) / 100.0);
diff --git a/idf_component.yml b/idf_component.yml
index f0e3f84b28d..642bc54143d 100644
--- a/idf_component.yml
+++ b/idf_component.yml
@@ -105,7 +105,7 @@ dependencies:
     rules:
       - if: "target in [esp32s3]"
   espressif/esp_hosted:
-    version: "^0.0.25"
+    version: "^2.0.0"
     rules:
       - if: "target == esp32p4"
   espressif/esp_wifi_remote:
diff --git a/libraries/WiFi/src/WiFiGeneric.cpp b/libraries/WiFi/src/WiFiGeneric.cpp
index e669ba81c12..6ae451d1cb7 100644
--- a/libraries/WiFi/src/WiFiGeneric.cpp
+++ b/libraries/WiFi/src/WiFiGeneric.cpp
@@ -252,13 +252,23 @@ static bool wifiHostedInit() {
   if (!hosted_initialized) {
     hosted_initialized = true;
     struct esp_hosted_sdio_config conf = INIT_DEFAULT_HOST_SDIO_CONFIG();
+#ifdef BOARD_HAS_SDIO_ESP_HOSTED
+    conf.pin_clk.pin = BOARD_SDIO_ESP_HOSTED_CLK;
+    conf.pin_cmd.pin = BOARD_SDIO_ESP_HOSTED_CMD;
+    conf.pin_d0.pin = BOARD_SDIO_ESP_HOSTED_D0;
+    conf.pin_d1.pin = BOARD_SDIO_ESP_HOSTED_D1;
+    conf.pin_d2.pin = BOARD_SDIO_ESP_HOSTED_D2;
+    conf.pin_d3.pin = BOARD_SDIO_ESP_HOSTED_D3;
+    conf.pin_reset.pin = BOARD_SDIO_ESP_HOSTED_RESET;
+#else
     conf.pin_clk.pin = CONFIG_ESP_SDIO_PIN_CLK;
     conf.pin_cmd.pin = CONFIG_ESP_SDIO_PIN_CMD;
     conf.pin_d0.pin = CONFIG_ESP_SDIO_PIN_D0;
     conf.pin_d1.pin = CONFIG_ESP_SDIO_PIN_D1;
     conf.pin_d2.pin = CONFIG_ESP_SDIO_PIN_D2;
     conf.pin_d3.pin = CONFIG_ESP_SDIO_PIN_D3;
-    //conf.pin_rst.pin = CONFIG_ESP_SDIO_GPIO_RESET_SLAVE;
+    conf.pin_reset.pin = CONFIG_ESP_SDIO_GPIO_RESET_SLAVE;
+#endif
     // esp_hosted_sdio_set_config() will fail on second attempt but here temporarily to not cause exception on reinit
     if (esp_hosted_sdio_set_config(&conf) != ESP_OK || esp_hosted_init() != ESP_OK) {
       log_e("esp_hosted_init failed!");
diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index 63027704d8a..aa21a192509 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-master-38628f98-v1"
+              "version": "idf-master-aaebc374-v1"
             },
             {
               "packager": "esp32",
@@ -76,7 +76,7 @@
             {
               "packager": "esp32",
               "name": "openocd-esp32",
-              "version": "v0.12.0-esp32-20250226"
+              "version": "v0.12.0-esp32-20250422"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-master-38628f98-v1",
+          "version": "idf-master-aaebc374-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
-              "size": "398323971"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
+              "size": "404569749"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
-              "size": "398323971"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
+              "size": "404569749"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
-              "size": "398323971"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
+              "size": "404569749"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
-              "size": "398323971"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
+              "size": "404569749"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
-              "size": "398323971"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
+              "size": "404569749"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
-              "size": "398323971"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
+              "size": "404569749"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
-              "size": "398323971"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
+              "size": "404569749"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-38628f98-v1.zip",
-              "checksum": "SHA-256:efc30a38cccff38c36a86fd3db78aeb13594da60ccf49bc7971b7a9f849abcdf",
-              "size": "398323971"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
+              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
+              "size": "404569749"
             }
           ]
         },
@@ -414,56 +414,56 @@
         },
         {
           "name": "openocd-esp32",
-          "version": "v0.12.0-esp32-20250226",
+          "version": "v0.12.0-esp32-20250422",
           "systems": [
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-linux-amd64-0.12.0-esp32-20250226.tar.gz",
-              "archiveFileName": "openocd-esp32-linux-amd64-0.12.0-esp32-20250226.tar.gz",
-              "checksum": "SHA-256:914c726342ba5828e53f41aa454f01f317c42d8e6772d3d874593a6960fc4729",
-              "size": "2414924"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250422/openocd-esp32-linux-amd64-0.12.0-esp32-20250422.tar.gz",
+              "archiveFileName": "openocd-esp32-linux-amd64-0.12.0-esp32-20250422.tar.gz",
+              "checksum": "SHA-256:eb1fa9b21c65b45a2200af6dcc2914e32335d37b6dbbd181778dcc0dc025e70a",
+              "size": "2445546"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-linux-arm64-0.12.0-esp32-20250226.tar.gz",
-              "archiveFileName": "openocd-esp32-linux-arm64-0.12.0-esp32-20250226.tar.gz",
-              "checksum": "SHA-256:c44ee99a9209c0234dbbcec86339fd685f5c61a763b29c33eba590bf62db2296",
-              "size": "2293923"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250422/openocd-esp32-linux-arm64-0.12.0-esp32-20250422.tar.gz",
+              "archiveFileName": "openocd-esp32-linux-arm64-0.12.0-esp32-20250422.tar.gz",
+              "checksum": "SHA-256:f70334a9b12a75b4d943e09fa5db30973037c39dbb54d6fa9f1a7118228b3d1c",
+              "size": "2330926"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-linux-armel-0.12.0-esp32-20250226.tar.gz",
-              "archiveFileName": "openocd-esp32-linux-armel-0.12.0-esp32-20250226.tar.gz",
-              "checksum": "SHA-256:21ab6af3cf05f9290f4d59f1f381d5094dd2755fc528d3d2feb9334348fc0d8d",
-              "size": "2436071"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250422/openocd-esp32-linux-armel-0.12.0-esp32-20250422.tar.gz",
+              "archiveFileName": "openocd-esp32-linux-armel-0.12.0-esp32-20250422.tar.gz",
+              "checksum": "SHA-256:4ac34d6fd1af86aeda87c8318732f8d691c300c285c7fd2f5037c432c63fbbb3",
+              "size": "2470732"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-macos-0.12.0-esp32-20250226.tar.gz",
-              "archiveFileName": "openocd-esp32-macos-0.12.0-esp32-20250226.tar.gz",
-              "checksum": "SHA-256:0b5751699e93b6d101381611c96216ddff8c7dfd16425c610993fa27993f9a0a",
-              "size": "2525387"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250422/openocd-esp32-macos-0.12.0-esp32-20250422.tar.gz",
+              "archiveFileName": "openocd-esp32-macos-0.12.0-esp32-20250422.tar.gz",
+              "checksum": "SHA-256:9186a7a06304c6d9201cbce4ee3c7099b393bf8d329cda17a68874f92308f6ce",
+              "size": "2548730"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-macos-arm64-0.12.0-esp32-20250226.tar.gz",
-              "archiveFileName": "openocd-esp32-macos-arm64-0.12.0-esp32-20250226.tar.gz",
-              "checksum": "SHA-256:8bffbbb594b27a4971a3922792135f8c836fff26991f7f450094386920263531",
-              "size": "2568843"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250422/openocd-esp32-macos-arm64-0.12.0-esp32-20250422.tar.gz",
+              "archiveFileName": "openocd-esp32-macos-arm64-0.12.0-esp32-20250422.tar.gz",
+              "checksum": "SHA-256:2cc39318d52f393233ff1f777871aebe5b97b3fbad29556a238489263401b774",
+              "size": "2593819"
             },
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-win32-0.12.0-esp32-20250226.zip",
-              "archiveFileName": "openocd-esp32-win32-0.12.0-esp32-20250226.zip",
-              "checksum": "SHA-256:aaf3c955bb4eb47805a1ba108dfd07a8a56ce720cb40194a354362b5f0961230",
-              "size": "2960226"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250422/openocd-esp32-win32-0.12.0-esp32-20250422.zip",
+              "archiveFileName": "openocd-esp32-win32-0.12.0-esp32-20250422.zip",
+              "checksum": "SHA-256:ecb4f8533fa9098d10000f5f7e8b8eaa8591015b824b481078ddb2b37e7aa6f2",
+              "size": "2988859"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250226/openocd-esp32-win64-0.12.0-esp32-20250226.zip",
-              "archiveFileName": "openocd-esp32-win64-0.12.0-esp32-20250226.zip",
-              "checksum": "SHA-256:79baf35325117a53093b62f6b9bee677dd12275d7066e3f8a274d2a80e986b6e",
-              "size": "2960225"
+              "url": "https://github.com/espressif/openocd-esp32/releases/download/v0.12.0-esp32-20250422/openocd-esp32-win64-0.12.0-esp32-20250422.zip",
+              "archiveFileName": "openocd-esp32-win64-0.12.0-esp32-20250422.zip",
+              "checksum": "SHA-256:e9eae8e1a8d0e030cd81dcb08394a9137cb7338a6211dfabcdbdfb37b58c5a23",
+              "size": "2988858"
             }
           ]
         },

From bc08c49579d083503d8db77254d62dcb36f0057f Mon Sep 17 00:00:00 2001
From: Jason2866 <24528715+Jason2866@users.noreply.github.com>
Date: Tue, 13 May 2025 12:25:39 +0200
Subject: [PATCH 022/105] Update version for wifi remote (#11344)

---
 idf_component.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/idf_component.yml b/idf_component.yml
index 642bc54143d..98dd5c9b9d9 100644
--- a/idf_component.yml
+++ b/idf_component.yml
@@ -109,7 +109,7 @@ dependencies:
     rules:
       - if: "target == esp32p4"
   espressif/esp_wifi_remote:
-    version: "^0.5.4"
+    version: "~0.9.2"
     rules:
       - if: "target == esp32p4"
   espressif/libsodium:

From 69cd5a0a664e96afb7007efe061bc80fef6f72cd Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Thu, 15 May 2025 11:10:00 +0200
Subject: [PATCH 023/105] IDF master 7cf5dacd (#11358)

---
 package/package_esp32_index.template.json | 68 +++++++++++------------
 1 file changed, 34 insertions(+), 34 deletions(-)

diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index aa21a192509..e3b42431cbf 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-master-aaebc374-v1"
+              "version": "idf-master-7cf5dacd-v2"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-master-aaebc374-v1",
+          "version": "idf-master-7cf5dacd-v2",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
-              "size": "404569749"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
+              "size": "405095217"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
-              "size": "404569749"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
+              "size": "405095217"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
-              "size": "404569749"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
+              "size": "405095217"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
-              "size": "404569749"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
+              "size": "405095217"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
-              "size": "404569749"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
+              "size": "405095217"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
-              "size": "404569749"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
+              "size": "405095217"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
-              "size": "404569749"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
+              "size": "405095217"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-aaebc374-v1.zip",
-              "checksum": "SHA-256:5baa0bbeae58973fd6bd4004332eb554b723a1e67f1af389840fac8081c2e21e",
-              "size": "404569749"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
+              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
+              "size": "405095217"
             }
           ]
         },

From 5540afa1ea9ab070d85e1d4fa3338e6c6ce12405 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Thu, 15 May 2025 11:13:32 +0200
Subject: [PATCH 024/105] feat(ci): Run push CI against IDF v5.5

---
 .github/workflows/push.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml
index 026e0b8fc0d..68148fbcff7 100644
--- a/.github/workflows/push.yml
+++ b/.github/workflows/push.yml
@@ -248,7 +248,7 @@ jobs:
         # See https://hub.docker.com/r/espressif/idf/tags and
         # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/tools/idf-docker-image.html
         # for details.
-        idf_ver: ["release-v5.4"]
+        idf_ver: ["release-v5.5"]
         idf_target:
           [
             "esp32",

From 3f63a4929f6cb7165e78d47c4478f62a76e00e9e Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Mon, 19 May 2025 13:54:12 +0200
Subject: [PATCH 025/105] fix(build): Add dependency on esp_http_client

---
 CMakeLists.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9e981130715..3288f16f39f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -356,7 +356,7 @@ endforeach()
 set(includedirs variants/${CONFIG_ARDUINO_VARIANT}/ cores/esp32/ ${ARDUINO_LIBRARIES_INCLUDEDIRS})
 set(srcs ${CORE_SRCS} ${ARDUINO_LIBRARIES_SRCS})
 set(priv_includes cores/esp32/libb64)
-set(requires spi_flash esp_partition mbedtls wpa_supplicant esp_adc esp_eth http_parser esp_ringbuf esp_driver_gptimer esp_driver_usb_serial_jtag driver)
+set(requires spi_flash esp_partition mbedtls wpa_supplicant esp_adc esp_eth http_parser esp_ringbuf esp_driver_gptimer esp_driver_usb_serial_jtag driver esp_http_client)
 set(priv_requires fatfs nvs_flash app_update spiffs bootloader_support bt esp_hid usb esp_psram ${ARDUINO_LIBRARIES_REQUIRES})
 
 if(NOT CONFIG_ARDUINO_SELECTIVE_COMPILATION OR CONFIG_ARDUINO_SELECTIVE_OpenThread)

From 6ce7e254c43604c4927ef1bcca0468e1d33db243 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Fri, 30 May 2025 17:18:32 +0300
Subject: [PATCH 026/105] IDF release/v5.5 (#11369)

* IDF release/v5.5 719b1b2b

* fix(build): Add dependency on esp_http_client

* fix(build): Add dependency on esp_https_ota

* IDF release/v5.5 28ac0243
---
 CMakeLists.txt                            |  2 +-
 package/package_esp32_index.template.json | 68 +++++++++++------------
 2 files changed, 35 insertions(+), 35 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 7cee7962a65..3cbb59dd3d9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -359,7 +359,7 @@ endforeach()
 set(includedirs variants/${CONFIG_ARDUINO_VARIANT}/ cores/esp32/ ${ARDUINO_LIBRARIES_INCLUDEDIRS})
 set(srcs ${CORE_SRCS} ${ARDUINO_LIBRARIES_SRCS})
 set(priv_includes cores/esp32/libb64)
-set(requires spi_flash esp_partition mbedtls wpa_supplicant esp_adc esp_eth http_parser esp_ringbuf esp_driver_gptimer esp_driver_usb_serial_jtag driver esp_http_client)
+set(requires spi_flash esp_partition mbedtls wpa_supplicant esp_adc esp_eth http_parser esp_ringbuf esp_driver_gptimer esp_driver_usb_serial_jtag driver esp_http_client esp_https_ota)
 set(priv_requires fatfs nvs_flash app_update spiffs bootloader_support bt esp_hid usb esp_psram ${ARDUINO_LIBRARIES_REQUIRES})
 
 if(NOT CONFIG_ARDUINO_SELECTIVE_COMPILATION OR CONFIG_ARDUINO_SELECTIVE_OpenThread)
diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index e3b42431cbf..eecc7c10788 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-master-7cf5dacd-v2"
+              "version": "idf-release_v5.5-28ac0243-v1"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-master-7cf5dacd-v2",
+          "version": "idf-release_v5.5-28ac0243-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
-              "size": "405095217"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
+              "size": "405149394"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
-              "size": "405095217"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
+              "size": "405149394"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
-              "size": "405095217"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
+              "size": "405149394"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
-              "size": "405095217"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
+              "size": "405149394"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
-              "size": "405095217"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
+              "size": "405149394"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
-              "size": "405095217"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
+              "size": "405149394"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
-              "size": "405095217"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
+              "size": "405149394"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-master/esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-master-7cf5dacd-v2.zip",
-              "checksum": "SHA-256:91f74810c5bee0fa4463f7df73f1f6b5e4a08a6c2094014b9a4c0fac61eb43de",
-              "size": "405095217"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
+              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
+              "size": "405149394"
             }
           ]
         },

From a6bba43d32ab65d73054a0a65b63a4716673975c Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Fri, 30 May 2025 19:12:34 +0300
Subject: [PATCH 027/105] fix(c5): Enable components for ESP32-C5

---
 idf_component.yml | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/idf_component.yml b/idf_component.yml
index 98dd5c9b9d9..dca97dc1655 100644
--- a/idf_component.yml
+++ b/idf_component.yml
@@ -57,12 +57,12 @@ dependencies:
     version: "==1.6.3"
     require: public
     rules:
-      - if: "target not in [esp32c2, esp32p4, esp32c5]"
+      - if: "target not in [esp32c2, esp32p4]"
   espressif/esp-zigbee-lib:
     version: "==1.6.3"
     require: public
     rules:
-      - if: "target not in [esp32c2, esp32p4, esp32c5]"
+      - if: "target not in [esp32c2, esp32p4]"
   espressif/esp-dsp:
     version: "^1.3.4"
     rules:
@@ -73,32 +73,32 @@ dependencies:
   espressif/esp_rainmaker:
     version: "1.5.2"
     rules:
-      - if: "target not in [esp32c2, esp32p4, esp32c5]"
+      - if: "target not in [esp32c2, esp32p4]"
   espressif/rmaker_common:
     version: "1.4.6"
     rules:
-      - if: "target not in [esp32c2, esp32p4, esp32c5]"
+      - if: "target not in [esp32c2, esp32p4]"
   espressif/esp_insights:
     version: "1.2.2"
     rules:
-      - if: "target not in [esp32c2, esp32p4, esp32c5]"
+      - if: "target not in [esp32c2, esp32p4]"
   # New version breaks esp_insights 1.0.1
   espressif/esp_diag_data_store:
     version: "1.0.2"
     rules:
-      - if: "target not in [esp32c2, esp32p4, esp32c5]"
+      - if: "target not in [esp32c2, esp32p4]"
   espressif/esp_diagnostics:
     version: "1.2.1"
     rules:
-      - if: "target not in [esp32c2, esp32p4, esp32c5]"
+      - if: "target not in [esp32c2, esp32p4]"
   espressif/cbor:
     version: "0.6.0~1"
     rules:
-      - if: "target not in [esp32c2, esp32p4, esp32c5]"
+      - if: "target not in [esp32c2, esp32p4]"
   espressif/qrcode:
     version: "0.1.0~2"
     rules:
-      - if: "target not in [esp32c2, esp32p4, esp32c5]"
+      - if: "target not in [esp32c2, esp32p4]"
   # RainMaker End
   espressif/esp-sr:
     version: "^1.4.2"

From 0ab9a0fe6fb450f527cb277d09b70065905cf807 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Proch=C3=A1zka?=
 <90197375+P-R-O-C-H-Y@users.noreply.github.com>
Date: Wed, 4 Jun 2025 17:48:48 +0200
Subject: [PATCH 028/105] feat(zigbee): Update to esp-zigbee-sdk 1.6.5 and fix
 ci.json files (#11436)

* feat(zigbee): Update esp-zigbee-sdk and fix ci.json files

* fix(ci): Check if LED_BUILTIN exist

* ci(pre-commit): Apply automatic fixes

---------

Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 idf_component.yml                                         | 4 ++--
 .../Zigbee/examples/Zigbee_On_Off_MultiSwitch/ci.json     | 2 +-
 .../examples/Zigbee_Power_Outlet/Zigbee_Power_Outlet.ino  | 8 +++++++-
 libraries/Zigbee/examples/Zigbee_Power_Outlet/ci.json     | 1 -
 4 files changed, 10 insertions(+), 5 deletions(-)

diff --git a/idf_component.yml b/idf_component.yml
index dca97dc1655..766704176b0 100644
--- a/idf_component.yml
+++ b/idf_component.yml
@@ -54,12 +54,12 @@ dependencies:
   espressif/esp_modem:
     version: "^1.1.0"
   espressif/esp-zboss-lib:
-    version: "==1.6.3"
+    version: "==1.6.4" # compatible with esp-zigbee-lib 1.6.5
     require: public
     rules:
       - if: "target not in [esp32c2, esp32p4]"
   espressif/esp-zigbee-lib:
-    version: "==1.6.3"
+    version: "==1.6.5"
     require: public
     rules:
       - if: "target not in [esp32c2, esp32p4]"
diff --git a/libraries/Zigbee/examples/Zigbee_On_Off_MultiSwitch/ci.json b/libraries/Zigbee/examples/Zigbee_On_Off_MultiSwitch/ci.json
index e79a477da11..15d6190e4ae 100644
--- a/libraries/Zigbee/examples/Zigbee_On_Off_MultiSwitch/ci.json
+++ b/libraries/Zigbee/examples/Zigbee_On_Off_MultiSwitch/ci.json
@@ -1,6 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=zigbee_zczr,ZigbeeMode=zczr",
   "requires": [
-    "CONFIG_SOC_IEEE802154_SUPPORTED=y"
+    "CONFIG_ZB_ENABLED=y"
   ]
 }
diff --git a/libraries/Zigbee/examples/Zigbee_Power_Outlet/Zigbee_Power_Outlet.ino b/libraries/Zigbee/examples/Zigbee_Power_Outlet/Zigbee_Power_Outlet.ino
index d9fe1b7aefe..ba1474d6455 100644
--- a/libraries/Zigbee/examples/Zigbee_Power_Outlet/Zigbee_Power_Outlet.ino
+++ b/libraries/Zigbee/examples/Zigbee_Power_Outlet/Zigbee_Power_Outlet.ino
@@ -34,7 +34,13 @@
 
 /* Zigbee power outlet configuration */
 #define ZIGBEE_OUTLET_ENDPOINT 1
-uint8_t led = RGB_BUILTIN;
+
+#ifdef LED_BUILTIN  // Use built-in LED if defined for the board
+uint8_t led = LED_BUILTIN;
+#else
+uint8_t led = 2;  // Use custom LED pin
+#endif
+
 uint8_t button = BOOT_PIN;
 
 ZigbeePowerOutlet zbOutlet = ZigbeePowerOutlet(ZIGBEE_OUTLET_ENDPOINT);
diff --git a/libraries/Zigbee/examples/Zigbee_Power_Outlet/ci.json b/libraries/Zigbee/examples/Zigbee_Power_Outlet/ci.json
index 23decd7127c..15d6190e4ae 100644
--- a/libraries/Zigbee/examples/Zigbee_Power_Outlet/ci.json
+++ b/libraries/Zigbee/examples/Zigbee_Power_Outlet/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=zigbee_zczr,ZigbeeMode=zczr",
   "requires": [
-    "CONFIG_SOC_IEEE802154_SUPPORTED=y",
     "CONFIG_ZB_ENABLED=y"
   ]
 }

From 89ff4653286206be29fe49e3c333f14065801616 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Tue, 10 Jun 2025 05:19:32 -0300
Subject: [PATCH 029/105] feat(esptool): Upgrade to esptool v5 (#11433)

* feat(esptool): Upgrade to esptool v5

* fix(script): Update script for better handling of esptool

* fix(script): Get proper download url

* fix(script): Apply copilot suggestions
---
 .github/scripts/update_esptool.py         | 236 ++++++++++++++++++++++
 package/package_esp32_index.template.json |  70 +++----
 platform.txt                              |  12 +-
 3 files changed, 277 insertions(+), 41 deletions(-)
 create mode 100644 .github/scripts/update_esptool.py

diff --git a/.github/scripts/update_esptool.py b/.github/scripts/update_esptool.py
new file mode 100644
index 00000000000..dd5de5526c3
--- /dev/null
+++ b/.github/scripts/update_esptool.py
@@ -0,0 +1,236 @@
+#!/usr/bin/env python3
+
+# This script is used to re-package the esptool if needed and update the JSON file
+# for the Arduino ESP32 platform.
+#
+# The script has only been tested on macOS.
+#
+# For regular esptool releases, the generated packages already contain the correct permissions,
+# extensions and are uploaded to the GitHub release assets. In this case, the script will only
+# update the JSON file with the information from the GitHub release.
+#
+# The script can be used in two modes:
+# 1. Local build: The build artifacts must be already downloaded and extracted in the base_folder.
+#    This is useful for esptool versions that are not yet released and that are grabbed from the
+#    GitHub build artifacts.
+# 2. Release build: The script will get the release information from GitHub and update the JSON file.
+#    This is useful for esptool versions that are already released and that are uploaded to the
+#    GitHub release assets.
+#
+#    For local build, the artifacts must be already downloaded and extracted in the base_folder
+#    set with the -l option.
+#    For example, a base folder "esptool" should contain the following folders extracted directly
+#    from the GitHub build artifacts:
+#        esptool/esptool-linux-aarch64
+#        esptool/esptool-linux-amd64
+#        esptool/esptool-linux-armv7
+#        esptool/esptool-macos-amd64
+#        esptool/esptool-macos-arm64
+#        esptool/esptool-windows-amd64
+
+import argparse
+import json
+import os
+import shutil
+import stat
+import tarfile
+import zipfile
+import hashlib
+import requests
+from pathlib import Path
+
+def compute_sha256(filepath):
+    sha256 = hashlib.sha256()
+    with open(filepath, "rb") as f:
+        for block in iter(lambda: f.read(4096), b""):
+            sha256.update(block)
+    return f"SHA-256:{sha256.hexdigest()}"
+
+def get_file_size(filepath):
+    return os.path.getsize(filepath)
+
+def update_json_for_host(tmp_json_path, version, host, url, archiveFileName, checksum, size):
+    with open(tmp_json_path) as f:
+        data = json.load(f)
+
+    for pkg in data.get("packages", []):
+        for tool in pkg.get("tools", []):
+            if tool.get("name") == "esptool_py":
+                tool["version"] = version
+
+                if url is None:
+                    # If the URL is not set, we need to find the old URL and update it
+                    for system in tool.get("systems", []):
+                        if system.get("host") == host:
+                            url = system.get("url").replace(system.get("archiveFileName"), archiveFileName)
+                            break
+                    else:
+                        print(f"No old URL found for host {host}. Using empty URL.")
+                        url = ""
+
+                # Preserve existing systems order and update or append the new system
+                systems = tool.get("systems", [])
+                system_updated = False
+                for i, system in enumerate(systems):
+                    if system.get("host") == host:
+                        systems[i] = {
+                            "host": host,
+                            "url": url,
+                            "archiveFileName": archiveFileName,
+                            "checksum": checksum,
+                            "size": str(size),
+                        }
+                        system_updated = True
+                        break
+
+                if not system_updated:
+                    systems.append({
+                        "host": host,
+                        "url": url,
+                        "archiveFileName": archiveFileName,
+                        "checksum": checksum,
+                        "size": str(size),
+                    })
+                tool["systems"] = systems
+
+    with open(tmp_json_path, "w") as f:
+        json.dump(data, f, indent=2, sort_keys=False, ensure_ascii=False)
+        f.write("\n")
+
+def update_tools_dependencies(tmp_json_path, version):
+    with open(tmp_json_path) as f:
+        data = json.load(f)
+
+    for pkg in data.get("packages", []):
+        for platform in pkg.get("platforms", []):
+            for dep in platform.get("toolsDependencies", []):
+                if dep.get("name") == "esptool_py":
+                    dep["version"] = version
+
+    with open(tmp_json_path, "w") as f:
+        json.dump(data, f, indent=2, sort_keys=False, ensure_ascii=False)
+        f.write("\n")
+
+def create_archives(version, base_folder):
+    archive_files = []
+
+    for dirpath in Path(base_folder).glob("esptool-*"):
+        if not dirpath.is_dir():
+            continue
+
+        base = dirpath.name[len("esptool-"):]
+
+        if "windows" in dirpath.name:
+            zipfile_name = f"esptool-v{version}-{base}.zip"
+            print(f"Creating {zipfile_name} from {dirpath} ...")
+            with zipfile.ZipFile(zipfile_name, "w", zipfile.ZIP_DEFLATED) as zipf:
+                for root, _, files in os.walk(dirpath):
+                    for file in files:
+                        full_path = os.path.join(root, file)
+                        zipf.write(full_path, os.path.relpath(full_path, start=dirpath))
+            archive_files.append(zipfile_name)
+        else:
+            tarfile_name = f"esptool-v{version}-{base}.tar.gz"
+            print(f"Creating {tarfile_name} from {dirpath} ...")
+            for root, dirs, files in os.walk(dirpath):
+                for name in dirs + files:
+                    os.chmod(os.path.join(root, name), stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR |
+                                                        stat.S_IRGRP | stat.S_IXGRP |
+                                                        stat.S_IROTH | stat.S_IXOTH)
+            with tarfile.open(tarfile_name, "w:gz") as tar:
+                tar.add(dirpath, arcname=dirpath.name)
+            archive_files.append(tarfile_name)
+
+    return archive_files
+
+def determine_hosts(archive_name):
+    if "linux-amd64" in archive_name:
+        return ["x86_64-pc-linux-gnu"]
+    elif "linux-armv7" in archive_name:
+        return ["arm-linux-gnueabihf"]
+    elif "linux-aarch64" in archive_name:
+        return ["aarch64-linux-gnu"]
+    elif "macos-amd64" in archive_name:
+        return ["x86_64-apple-darwin"]
+    elif "macos-arm64" in archive_name:
+        return ["arm64-apple-darwin"]
+    elif "windows-amd64" in archive_name:
+        return ["x86_64-mingw32", "i686-mingw32"]
+    else:
+        return []
+
+def update_json_from_local_build(tmp_json_path, version, base_folder, archive_files):
+    for archive in archive_files:
+        print(f"Processing archive: {archive}")
+        hosts = determine_hosts(archive)
+        if not hosts:
+            print(f"Skipping unknown archive type: {archive}")
+            continue
+
+        archive_path = Path(archive)
+        checksum = compute_sha256(archive_path)
+        size = get_file_size(archive_path)
+
+        for host in hosts:
+            update_json_for_host(tmp_json_path, version, host, None, archive_path.name, checksum, size)
+
+def update_json_from_release(tmp_json_path, version, release_info):
+    assets = release_info.get("assets", [])
+    for asset in assets:
+        if (asset.get("name").endswith(".tar.gz") or asset.get("name").endswith(".zip")) and "esptool" in asset.get("name"):
+            asset_fname = asset.get("name")
+            print(f"Processing asset: {asset_fname}")
+            hosts = determine_hosts(asset_fname)
+            if not hosts:
+                print(f"Skipping unknown archive type: {asset_fname}")
+                continue
+
+            asset_url = asset.get("browser_download_url")
+            asset_checksum = asset.get("digest")
+            asset_size = asset.get("size")
+            if asset_checksum is None:
+                asset_checksum = ""
+                print(f"Asset {asset_fname} has no checksum. Please set the checksum in the JSON file.")
+
+            for host in hosts:
+                update_json_for_host(tmp_json_path, version, host, asset_url, asset_fname, asset_checksum, asset_size)
+
+def get_release_info(version):
+    url = f"https://api.github.com/repos/espressif/esptool/releases/tags/v{version}"
+    response = requests.get(url)
+    response.raise_for_status()
+    return response.json()
+
+def main():
+    parser = argparse.ArgumentParser(description="Repack esptool and update JSON metadata.")
+    parser.add_argument("version", help="Version of the esptool (e.g. 5.0.dev1)")
+    parser.add_argument("-l", "--local", dest="base_folder", help="Enable local build mode and set the base folder with unpacked artifacts")
+    args = parser.parse_args()
+
+    script_dir = Path(__file__).resolve().parent
+    json_path = (script_dir / "../../package/package_esp32_index.template.json").resolve()
+    tmp_json_path = Path(str(json_path) + ".tmp")
+    shutil.copy(json_path, tmp_json_path)
+
+    local_build = args.base_folder is not None
+
+    if local_build:
+        os.chdir(args.base_folder)
+        os.environ['COPYFILE_DISABLE'] = 'true'  # this disables including resource forks in tar files on macOS
+        # Clear any existing archive files
+        for file in Path(args.base_folder).glob("esptool-*.*"):
+            file.unlink()
+        archive_files = create_archives(args.version, args.base_folder)
+        update_json_from_local_build(tmp_json_path, args.version, args.base_folder, archive_files)
+    else:
+        release_info = get_release_info(args.version)
+        update_json_from_release(tmp_json_path, args.version, release_info)
+
+    print(f"Updating esptool version fields to {args.version}")
+    update_tools_dependencies(tmp_json_path, args.version)
+
+    shutil.move(tmp_json_path, json_path)
+    print(f"Done. JSON updated at {json_path}")
+
+if __name__ == "__main__":
+    main()
diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index eecc7c10788..3ae2ff09ee6 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -81,7 +81,7 @@
             {
               "packager": "esp32",
               "name": "esptool_py",
-              "version": "4.9.dev3"
+              "version": "5.0.dev1"
             },
             {
               "packager": "esp32",
@@ -469,56 +469,56 @@
         },
         {
           "name": "esptool_py",
-          "version": "4.9.dev3",
+          "version": "5.0.dev1",
           "systems": [
             {
-              "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.1.0-RC3/esptool-v4.9.dev3-linux-amd64.tar.gz",
-              "archiveFileName": "esptool-v4.9.dev3-linux-amd64.tar.gz",
-              "checksum": "SHA-256:4ecaf51836cbf4ea3c19840018bfef3b0b8cd8fc3c95f6e1e043ca5bbeab9bf0",
-              "size": "64958202"
+              "host": "aarch64-linux-gnu",
+              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-linux-aarch64.tar.gz",
+              "archiveFileName": "esptool-v5.0.dev1-linux-aarch64.tar.gz",
+              "checksum": "SHA-256:bfafa7a7723ebbabfd8b6e3ca5ae00bfead0331de923754aeddb43b2c116a078",
+              "size": "58241736"
             },
             {
-              "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.1.0-RC3/esptool-v4.9.dev3-linux-armv7.tar.gz",
-              "archiveFileName": "esptool-v4.9.dev3-linux-armv7.tar.gz",
-              "checksum": "SHA-256:fff818573bce483ee793ac83c8211f6abf764aa3350f198228859f696a0a0b36",
-              "size": "31530030"
+              "host": "x86_64-pc-linux-gnu",
+              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-linux-amd64.tar.gz",
+              "archiveFileName": "esptool-v5.0.dev1-linux-amd64.tar.gz",
+              "checksum": "SHA-256:acd0486e96586b99d053a1479acbbbfcae8667227c831cdc53a171f9ccfa27ee",
+              "size": "100740042"
             },
             {
-              "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.1.0-RC3/esptool-v4.9.dev3-linux-aarch64.tar.gz",
-              "archiveFileName": "esptool-v4.9.dev3-linux-aarch64.tar.gz",
-              "checksum": "SHA-256:5b274bdff2f62e6a07c3c1dfa51b1128924621f661747eca3dbe0f77972f2f06",
-              "size": "33663882"
+              "host": "arm-linux-gnueabihf",
+              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-linux-armv7.tar.gz",
+              "archiveFileName": "esptool-v5.0.dev1-linux-armv7.tar.gz",
+              "checksum": "SHA-256:ea77a38681506761bbb7b0b39c130811ed565667b67ebbdb4d6dcc6cb6e07368",
+              "size": "53451939"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.1.0-RC3/esptool-v4.9.dev3-macos-amd64.tar.gz",
-              "archiveFileName": "esptool-v4.9.dev3-macos-amd64.tar.gz",
-              "checksum": "SHA-256:c733c83b58fcf5f642fbb2fddb8ff24640c2c785126cba0821fb70c4a5ceea7a",
-              "size": "32767836"
+              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-macos-amd64.tar.gz",
+              "archiveFileName": "esptool-v5.0.dev1-macos-amd64.tar.gz",
+              "checksum": "SHA-256:900a8e90731208bee96647e0e207a43612b9452c2120c4fdc0ff4c6be226257b",
+              "size": "59631998"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.1.0-RC3/esptool-v4.9.dev3-macos-arm64.tar.gz",
-              "archiveFileName": "esptool-v4.9.dev3-macos-arm64.tar.gz",
-              "checksum": "SHA-256:83c195a15981e6a5e7a130db2ccfb21e2d8093912e5b003681f9a5abadd71af7",
-              "size": "30121441"
+              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-macos-arm64.tar.gz",
+              "archiveFileName": "esptool-v5.0.dev1-macos-arm64.tar.gz",
+              "checksum": "SHA-256:3653f4de73cb4fc6a25351eaf663708e91c65ae3265d75bd54ca4315a4350bb4",
+              "size": "56349992"
             },
             {
-              "host": "i686-mingw32",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.1.0-RC3/esptool-v4.9.dev3-win64.zip",
-              "archiveFileName": "esptool-v4.9.dev3-win64.zip",
-              "checksum": "SHA-256:890051a4fdc684ff6f4af18d0bb27d274ca940ee0eef716a9455f8c64b25b215",
-              "size": "36072564"
+              "host": "x86_64-mingw32",
+              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-win64.zip",
+              "archiveFileName": "esptool-v5.0.dev1-win64.zip",
+              "checksum": "SHA-256:1e8fd89645daf94f2d4406ec73c9004e617ea921079515f9fd749205eece4d6d",
+              "size": "59102658"
             },
             {
-              "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.1.0-RC3/esptool-v4.9.dev3-win64.zip",
-              "archiveFileName": "esptool-v4.9.dev3-win64.zip",
-              "checksum": "SHA-256:890051a4fdc684ff6f4af18d0bb27d274ca940ee0eef716a9455f8c64b25b215",
-              "size": "36072564"
+              "host": "i686-mingw32",
+              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-win64.zip",
+              "archiveFileName": "esptool-v5.0.dev1-win64.zip",
+              "checksum": "SHA-256:1e8fd89645daf94f2d4406ec73c9004e617ea921079515f9fd749205eece4d6d",
+              "size": "59102658"
             }
           ]
         },
diff --git a/platform.txt b/platform.txt
index f41a8b4a764..8bfa69a79e0 100644
--- a/platform.txt
+++ b/platform.txt
@@ -120,7 +120,7 @@ recipe.hooks.prebuild.2.pattern.windows=cmd /c if not exist "{build.path}\partit
 recipe.hooks.prebuild.3.pattern.windows=cmd /c if not exist "{build.path}\partitions.csv" COPY "{runtime.platform.path}\tools\partitions\{build.partitions}.csv" "{build.path}\partitions.csv"
 
 # Check if custom bootloader exist: source > variant > build.boot
-recipe.hooks.prebuild.4.pattern_args=--chip {build.mcu} elf2image --flash_mode {build.flash_mode} --flash_freq {build.img_freq} --flash_size {build.flash_size} -o
+recipe.hooks.prebuild.4.pattern_args=--chip {build.mcu} elf2image --flash-mode {build.flash_mode} --flash-freq {build.img_freq} --flash-size {build.flash_size} -o
 recipe.hooks.prebuild.4.pattern=/usr/bin/env bash -c "[ -f "{build.source.path}"/bootloader.bin ] && cp -f "{build.source.path}"/bootloader.bin "{build.path}"/{build.project_name}.bootloader.bin || ( [ -f "{build.variant.path}"/{build.custom_bootloader}.bin ] && cp "{build.variant.path}"/{build.custom_bootloader}.bin "{build.path}"/{build.project_name}.bootloader.bin || "{tools.esptool_py.path}"/{tools.esptool_py.cmd} {recipe.hooks.prebuild.4.pattern_args} "{build.path}"/{build.project_name}.bootloader.bin "{compiler.sdk.path}"/bin/bootloader_{build.boot}_{build.boot_freq}.elf )"
 recipe.hooks.prebuild.4.pattern.windows=cmd /c IF EXIST "{build.source.path}\bootloader.bin" ( COPY /y "{build.source.path}\bootloader.bin" "{build.path}\{build.project_name}.bootloader.bin" ) ELSE ( IF EXIST "{build.variant.path}\{build.custom_bootloader}.bin" ( COPY "{build.variant.path}\{build.custom_bootloader}.bin" "{build.path}\{build.project_name}.bootloader.bin" ) ELSE ( "{tools.esptool_py.path}\{tools.esptool_py.cmd}" {recipe.hooks.prebuild.4.pattern_args} "{build.path}\{build.project_name}.bootloader.bin" "{compiler.sdk.path}\bin\bootloader_{build.boot}_{build.boot_freq}.elf" ) )
 
@@ -164,7 +164,7 @@ recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.f
 recipe.objcopy.partitions.bin.pattern={tools.gen_esp32part.cmd} -q "{build.path}/partitions.csv" "{build.path}/{build.project_name}.partitions.bin"
 
 ## Create bin
-recipe.objcopy.bin.pattern_args=--chip {build.mcu} elf2image --flash_mode "{build.flash_mode}" --flash_freq "{build.img_freq}" --flash_size "{build.flash_size}" --elf-sha256-offset 0xb0 -o "{build.path}/{build.project_name}.bin" "{build.path}/{build.project_name}.elf"
+recipe.objcopy.bin.pattern_args=--chip {build.mcu} elf2image --flash-mode "{build.flash_mode}" --flash-freq "{build.img_freq}" --flash-size "{build.flash_size}" --elf-sha256-offset 0xb0 -o "{build.path}/{build.project_name}.bin" "{build.path}/{build.project_name}.elf"
 recipe.objcopy.bin.pattern="{tools.esptool_py.path}/{tools.esptool_py.cmd}" {recipe.objcopy.bin.pattern_args}
 
 ## Create Insights Firmware Package
@@ -177,7 +177,7 @@ recipe.hooks.objcopy.postobjcopy.2.pattern=/usr/bin/env bash -c "[ ! -d "{build.
 recipe.hooks.objcopy.postobjcopy.2.pattern.windows=cmd /c if exist "{build.path}\libraries\ESP_SR" if exist "{compiler.sdk.path}\esp_sr\srmodels.bin" COPY /y "{compiler.sdk.path}\esp_sr\srmodels.bin" "{build.path}\srmodels.bin"
 
 # Create merged binary
-recipe.hooks.objcopy.postobjcopy.3.pattern_args=--chip {build.mcu} merge_bin -o "{build.path}/{build.project_name}.merged.bin" --fill-flash-size {build.flash_size} --flash_mode keep --flash_freq keep --flash_size keep {build.bootloader_addr} "{build.path}/{build.project_name}.bootloader.bin" 0x8000 "{build.path}/{build.project_name}.partitions.bin" 0xe000 "{runtime.platform.path}/tools/partitions/boot_app0.bin" 0x10000 "{build.path}/{build.project_name}.bin"
+recipe.hooks.objcopy.postobjcopy.3.pattern_args=--chip {build.mcu} merge-bin -o "{build.path}/{build.project_name}.merged.bin" --pad-to-size {build.flash_size} --flash-mode keep --flash-freq keep --flash-size keep {build.bootloader_addr} "{build.path}/{build.project_name}.bootloader.bin" 0x8000 "{build.path}/{build.project_name}.partitions.bin" 0xe000 "{runtime.platform.path}/tools/partitions/boot_app0.bin" 0x10000 "{build.path}/{build.project_name}.bin"
 recipe.hooks.objcopy.postobjcopy.3.pattern="{tools.esptool_py.path}/{tools.esptool_py.cmd}" {recipe.hooks.objcopy.postobjcopy.3.pattern_args}
 
 ## Save bin
@@ -294,14 +294,14 @@ debug.additional_config=debug_config.{build.mcu}
 tools.esptool_py.upload.protocol=serial
 tools.esptool_py.upload.params.verbose=
 tools.esptool_py.upload.params.quiet=
-tools.esptool_py.upload.pattern_args=--chip {build.mcu} --port "{serial.port}" --baud {upload.speed} {upload.flags} --before default_reset --after hard_reset write_flash {upload.erase_cmd} -z --flash_mode keep --flash_freq keep --flash_size keep {build.bootloader_addr} "{build.path}/{build.project_name}.bootloader.bin" 0x8000 "{build.path}/{build.project_name}.partitions.bin" 0xe000 "{runtime.platform.path}/tools/partitions/boot_app0.bin" 0x10000 "{build.path}/{build.project_name}.bin" {upload.extra_flags}
+tools.esptool_py.upload.pattern_args=--chip {build.mcu} --port "{serial.port}" --baud {upload.speed} {upload.flags} --before default-reset --after hard-reset write-flash {upload.erase_cmd} -z --flash-mode keep --flash-freq keep --flash-size keep {build.bootloader_addr} "{build.path}/{build.project_name}.bootloader.bin" 0x8000 "{build.path}/{build.project_name}.partitions.bin" 0xe000 "{runtime.platform.path}/tools/partitions/boot_app0.bin" 0x10000 "{build.path}/{build.project_name}.bin" {upload.extra_flags}
 tools.esptool_py.upload.pattern="{path}/{cmd}" {upload.pattern_args}
 
 ## Program Application
 ## -------------------
 tools.esptool_py.program.params.verbose=
 tools.esptool_py.program.params.quiet=
-tools.esptool_py.program.pattern_args=--chip {build.mcu} --port "{serial.port}" --baud {upload.speed} {upload.flags} --before default_reset --after hard_reset write_flash -z --flash_mode keep --flash_freq keep --flash_size keep 0x10000 "{build.path}/{build.project_name}.bin"
+tools.esptool_py.program.pattern_args=--chip {build.mcu} --port "{serial.port}" --baud {upload.speed} {upload.flags} --before default-reset --after hard-reset write-flash -z --flash-mode keep --flash-freq keep --flash-size keep 0x10000 "{build.path}/{build.project_name}.bin"
 tools.esptool_py.program.pattern="{path}/{cmd}" {program.pattern_args}
 
 ## Erase Chip (before burning the bootloader)
@@ -309,7 +309,7 @@ tools.esptool_py.program.pattern="{path}/{cmd}" {program.pattern_args}
 tools.esptool_py.erase.protocol=serial
 tools.esptool_py.erase.params.verbose=
 tools.esptool_py.erase.params.quiet=
-tools.esptool_py.erase.pattern_args=--chip {build.mcu} --port "{serial.port}" --baud {upload.speed} {upload.flags} --before default_reset --after hard_reset erase_flash
+tools.esptool_py.erase.pattern_args=--chip {build.mcu} --port "{serial.port}" --baud {upload.speed} {upload.flags} --before default-reset --after hard-reset erase-flash
 tools.esptool_py.erase.pattern="{path}/{cmd}" {erase.pattern_args}
 
 ## Burn Bootloader

From febca6b2f1d02b9252c2f5edc2aa312129c68720 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Mon, 23 Jun 2025 12:11:32 +0300
Subject: [PATCH 030/105] fix(p4): Update hosted and wifi_remote components

---
 idf_component.yml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/idf_component.yml b/idf_component.yml
index 257890257cc..82f14ea554a 100644
--- a/idf_component.yml
+++ b/idf_component.yml
@@ -107,11 +107,11 @@ dependencies:
     rules:
       - if: "target in [esp32s3]"
   espressif/esp_hosted:
-    version: "^2.0.0"
+    version: "^2.0.12"
     rules:
       - if: "target == esp32p4"
   espressif/esp_wifi_remote:
-    version: "~0.9.2"
+    version: "^0.13.0"
     rules:
       - if: "target == esp32p4"
   espressif/libsodium:

From 1c79eb823cf4beb8465b987bacea1347574979db Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Mon, 23 Jun 2025 08:47:49 -0300
Subject: [PATCH 031/105] feat(NimBLE): Add support for NimBLE (#11424)

* feat(NimBLE): Add support for NimBLE

Co-authored-by: h2zero <ryan@nable-embedded.io>

* ci(pre-commit): Apply automatic fixes

* fix(nimble): Fix typo in BLEClient

---------

Co-authored-by: h2zero <ryan@nable-embedded.io>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 cores/esp32/esp32-hal-bt.c                    |    6 +-
 cores/esp32/esp32-hal-misc.c                  |   11 +-
 libraries/BLE/README.md                       |    8 +-
 .../BLE5_extended_scan/BLE5_extended_scan.ino |    6 +-
 .../BLE/examples/BLE5_extended_scan/ci.json   |    3 +-
 .../BLE5_multi_advertising.ino                |    4 +-
 .../examples/BLE5_multi_advertising/ci.json   |    3 +-
 .../BLE5_periodic_advertising.ino             |    4 +-
 .../BLE5_periodic_advertising/ci.json         |    3 +-
 .../BLE5_periodic_sync/BLE5_periodic_sync.ino |    6 +-
 .../BLE/examples/BLE5_periodic_sync/ci.json   |    3 +-
 .../Beacon_Scanner/Beacon_Scanner.ino         |   42 +-
 libraries/BLE/examples/Client/Client.ino      |    2 +
 libraries/BLE/examples/Notify/Notify.ino      |    1 +
 .../Server_multiconnect.ino                   |   52 +-
 libraries/BLE/examples/UART/UART.ino          |   13 +-
 libraries/BLE/library.properties              |    2 +-
 libraries/BLE/src/BLE2901.cpp                 |   47 +-
 libraries/BLE/src/BLE2901.h                   |   39 +-
 libraries/BLE/src/BLE2902.cpp                 |   73 +-
 libraries/BLE/src/BLE2902.h                   |   46 +-
 libraries/BLE/src/BLE2904.cpp                 |   36 +-
 libraries/BLE/src/BLE2904.h                   |   39 +-
 libraries/BLE/src/BLEAddress.cpp              |  184 ++-
 libraries/BLE/src/BLEAddress.h                |   85 +-
 libraries/BLE/src/BLEAdvertisedDevice.cpp     |  165 ++-
 libraries/BLE/src/BLEAdvertisedDevice.h       |  154 ++-
 libraries/BLE/src/BLEAdvertising.cpp          |  915 +++++++++++--
 libraries/BLE/src/BLEAdvertising.h            |  210 ++-
 libraries/BLE/src/BLEBeacon.cpp               |   47 +-
 libraries/BLE/src/BLEBeacon.h                 |   20 +
 libraries/BLE/src/BLECharacteristic.cpp       | 1198 +++++++++++------
 libraries/BLE/src/BLECharacteristic.h         |  261 +++-
 libraries/BLE/src/BLECharacteristicMap.cpp    |   76 +-
 libraries/BLE/src/BLEClient.cpp               | 1009 +++++++++++---
 libraries/BLE/src/BLEClient.h                 |  191 ++-
 libraries/BLE/src/BLEConnInfo.h               |  110 ++
 libraries/BLE/src/BLEDescriptor.cpp           |  297 ++--
 libraries/BLE/src/BLEDescriptor.h             |  127 +-
 libraries/BLE/src/BLEDescriptorMap.cpp        |  102 +-
 libraries/BLE/src/BLEDevice.cpp               |  869 ++++++++----
 libraries/BLE/src/BLEDevice.h                 |  246 +++-
 libraries/BLE/src/BLEEddystoneTLM.cpp         |    8 +-
 .../BLE/src/BLEEddystoneTLM.cppwithheadder    |  202 ---
 libraries/BLE/src/BLEEddystoneTLM.h           |   10 +-
 libraries/BLE/src/BLEEddystoneURL.cpp         |   12 +-
 libraries/BLE/src/BLEEddystoneURL.h           |    8 +
 libraries/BLE/src/BLEEddystoneURL.h.orig      |   66 -
 libraries/BLE/src/BLEExceptions.cpp           |    5 +
 libraries/BLE/src/BLEHIDDevice.cpp            |   39 +-
 libraries/BLE/src/BLEHIDDevice.h              |    8 +-
 libraries/BLE/src/BLERemoteCharacteristic.cpp |  975 ++++++++++----
 libraries/BLE/src/BLERemoteCharacteristic.h   |  140 +-
 libraries/BLE/src/BLERemoteDescriptor.cpp     |  393 +++++-
 libraries/BLE/src/BLERemoteDescriptor.h       |   76 +-
 libraries/BLE/src/BLERemoteService.cpp        |  369 +++--
 libraries/BLE/src/BLERemoteService.h          |   87 +-
 libraries/BLE/src/BLEScan.cpp                 |  690 +++++++---
 libraries/BLE/src/BLEScan.h                   |  148 +-
 libraries/BLE/src/BLESecurity.cpp             |  140 +-
 libraries/BLE/src/BLESecurity.h               |  144 +-
 libraries/BLE/src/BLEServer.cpp               |  748 ++++++++--
 libraries/BLE/src/BLEServer.h                 |  217 ++-
 libraries/BLE/src/BLEService.cpp              |  429 ++++--
 libraries/BLE/src/BLEService.h                |  126 +-
 libraries/BLE/src/BLEServiceMap.cpp           |   40 +-
 libraries/BLE/src/BLEUUID.cpp                 |  375 +++---
 libraries/BLE/src/BLEUUID.h                   |  101 +-
 libraries/BLE/src/BLEUtils.cpp                |  682 ++++++++--
 libraries/BLE/src/BLEUtils.h                  |  113 +-
 libraries/BLE/src/BLEValue.cpp                |   18 +-
 libraries/BLE/src/BLEValue.h                  |   25 +-
 72 files changed, 9898 insertions(+), 3211 deletions(-)
 create mode 100644 libraries/BLE/src/BLEConnInfo.h
 delete mode 100644 libraries/BLE/src/BLEEddystoneTLM.cppwithheadder
 delete mode 100644 libraries/BLE/src/BLEEddystoneURL.h.orig

diff --git a/cores/esp32/esp32-hal-bt.c b/cores/esp32/esp32-hal-bt.c
index 5d512d448a3..a2a603bf5b9 100644
--- a/cores/esp32/esp32-hal-bt.c
+++ b/cores/esp32/esp32-hal-bt.c
@@ -15,7 +15,7 @@
 #include "esp32-hal-bt.h"
 
 #if SOC_BT_SUPPORTED
-#if defined(CONFIG_BT_BLUEDROID_ENABLED) && __has_include("esp_bt.h")
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
 
 #if CONFIG_IDF_TARGET_ESP32
 bool btInUse() {
@@ -116,7 +116,7 @@ bool btStop() {
   return false;
 }
 
-#else  // CONFIG_BT_ENABLED
+#else  // !__has_include("esp_bt.h") || !(defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED))
 bool btStarted() {
   return false;
 }
@@ -129,6 +129,6 @@ bool btStop() {
   return false;
 }
 
-#endif /* CONFIG_BT_ENABLED */
+#endif /* !__has_include("esp_bt.h") || !(defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) */
 
 #endif /* SOC_BT_SUPPORTED */
diff --git a/cores/esp32/esp32-hal-misc.c b/cores/esp32/esp32-hal-misc.c
index 9c1eaf6ba25..4c8a4e5beab 100644
--- a/cores/esp32/esp32-hal-misc.c
+++ b/cores/esp32/esp32-hal-misc.c
@@ -25,12 +25,13 @@
 #include "esp_ota_ops.h"
 #endif  //CONFIG_APP_ROLLBACK_ENABLE
 #include "esp_private/startup_internal.h"
-#if defined(CONFIG_BT_BLUEDROID_ENABLED) && SOC_BT_SUPPORTED && __has_include("esp_bt.h")
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && SOC_BT_SUPPORTED && __has_include("esp_bt.h")
 #include "esp_bt.h"
-#endif  //CONFIG_BT_BLUEDROID_ENABLED
+#endif
 #include <sys/time.h>
 #include "soc/rtc.h"
-#if !defined(CONFIG_IDF_TARGET_ESP32C2) && !defined(CONFIG_IDF_TARGET_ESP32C6) && !defined(CONFIG_IDF_TARGET_ESP32H2) && !defined(CONFIG_IDF_TARGET_ESP32P4) && !defined(CONFIG_IDF_TARGET_ESP32C5)
+#if !defined(CONFIG_IDF_TARGET_ESP32C2) && !defined(CONFIG_IDF_TARGET_ESP32C6) && !defined(CONFIG_IDF_TARGET_ESP32H2) && !defined(CONFIG_IDF_TARGET_ESP32P4) \
+  && !defined(CONFIG_IDF_TARGET_ESP32C5)
 #include "soc/rtc_cntl_reg.h"
 #include "soc/syscon_reg.h"
 #endif
@@ -245,7 +246,7 @@ bool verifyRollbackLater() {
 }
 #endif
 
-#ifdef CONFIG_BT_BLUEDROID_ENABLED
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
 #if CONFIG_IDF_TARGET_ESP32
 //overwritten in esp32-hal-bt.c
 bool btInUse() __attribute__((weak));
@@ -307,7 +308,7 @@ void initArduino() {
   if (err) {
     log_e("Failed to initialize NVS! Error: %u", err);
   }
-#if defined(CONFIG_BT_BLUEDROID_ENABLED) && SOC_BT_SUPPORTED
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && SOC_BT_SUPPORTED
   if (!btInUse()) {
     esp_bt_controller_mem_release(ESP_BT_MODE_BTDM);
   }
diff --git a/libraries/BLE/README.md b/libraries/BLE/README.md
index eb70ee9ff00..759c8526f0f 100644
--- a/libraries/BLE/README.md
+++ b/libraries/BLE/README.md
@@ -1,8 +1,12 @@
 # ESP32 BLE for Arduino
 The Arduino IDE provides an excellent library package manager where versions of libraries can be downloaded and installed. This Github project provides the repository for the ESP32 BLE support for Arduino.
 
-The original source of the project, **which is not maintained anymore**, can be found here: https://github.com/nkolban/esp32-snippets
+The original source of the Bluedroid project, **which is not maintained anymore**, can be found here: https://github.com/nkolban/esp32-snippets
 
-Issues and questions should be raised here: https://github.com/espressif/arduino-esp32/issues <br> (please don't use https://github.com/nkolban/esp32-snippets/issues!)
+Some parts of the NimBLE implementation are based on the work of h2zero, which can be found here: https://github.com/h2zero/NimBLE-Arduino
+
+Issues and questions should be raised here: https://github.com/espressif/arduino-esp32/issues <br> (please don't use https://github.com/nkolban/esp32-snippets/issues or https://github.com/h2zero/NimBLE-Arduino/issues!)
 
 Documentation for using the library can be found here: https://github.com/nkolban/esp32-snippets/tree/master/Documentation
+
+For a more customizable and feature-rich implementation of the NimBLE stack, you can use the [NimBLE-Arduino](https://github.com/h2zero/NimBLE-Arduino) library.
diff --git a/libraries/BLE/examples/BLE5_extended_scan/BLE5_extended_scan.ino b/libraries/BLE/examples/BLE5_extended_scan/BLE5_extended_scan.ino
index 42daff86835..e50d7339df6 100644
--- a/libraries/BLE/examples/BLE5_extended_scan/BLE5_extended_scan.ino
+++ b/libraries/BLE/examples/BLE5_extended_scan/BLE5_extended_scan.ino
@@ -7,8 +7,10 @@
 
    author: chegewara
 */
-#ifndef SOC_BLE_50_SUPPORTED
-#warning "This SoC does not support BLE5. Try using ESP32-C3, or ESP32-S3"
+#ifndef CONFIG_BLUEDROID_ENABLED
+#error "NimBLE does not support extended scan yet. Try using Bluedroid."
+#elif !defined(SOC_BLE_50_SUPPORTED)
+#error "This SoC does not support BLE5. Try using ESP32-C3, or ESP32-S3"
 #else
 
 #include <BLEDevice.h>
diff --git a/libraries/BLE/examples/BLE5_extended_scan/ci.json b/libraries/BLE/examples/BLE5_extended_scan/ci.json
index 184cc25a2b0..8e938055cf2 100644
--- a/libraries/BLE/examples/BLE5_extended_scan/ci.json
+++ b/libraries/BLE/examples/BLE5_extended_scan/ci.json
@@ -1,6 +1,7 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_BLE_50_SUPPORTED=y"
+    "CONFIG_SOC_BLE_50_SUPPORTED=y",
+    "CONFIG_BLUEDROID_ENABLED=y"
   ]
 }
diff --git a/libraries/BLE/examples/BLE5_multi_advertising/BLE5_multi_advertising.ino b/libraries/BLE/examples/BLE5_multi_advertising/BLE5_multi_advertising.ino
index c4d614786b0..ee25f8e95ef 100644
--- a/libraries/BLE/examples/BLE5_multi_advertising/BLE5_multi_advertising.ino
+++ b/libraries/BLE/examples/BLE5_multi_advertising/BLE5_multi_advertising.ino
@@ -6,7 +6,9 @@
    author: chegewara
 */
 
-#ifndef CONFIG_BT_BLE_50_FEATURES_SUPPORTED
+#ifndef CONFIG_BLUEDROID_ENABLED
+#error "NimBLE does not support multi advertising yet. Try using Bluedroid."
+#elif !defined(CONFIG_BT_BLE_50_FEATURES_SUPPORTED)
 #error "This SoC does not support BLE5. Try using ESP32-C3, or ESP32-S3"
 #else
 
diff --git a/libraries/BLE/examples/BLE5_multi_advertising/ci.json b/libraries/BLE/examples/BLE5_multi_advertising/ci.json
index 184cc25a2b0..8e938055cf2 100644
--- a/libraries/BLE/examples/BLE5_multi_advertising/ci.json
+++ b/libraries/BLE/examples/BLE5_multi_advertising/ci.json
@@ -1,6 +1,7 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_BLE_50_SUPPORTED=y"
+    "CONFIG_SOC_BLE_50_SUPPORTED=y",
+    "CONFIG_BLUEDROID_ENABLED=y"
   ]
 }
diff --git a/libraries/BLE/examples/BLE5_periodic_advertising/BLE5_periodic_advertising.ino b/libraries/BLE/examples/BLE5_periodic_advertising/BLE5_periodic_advertising.ino
index 0b9d4f87630..effb7efd241 100644
--- a/libraries/BLE/examples/BLE5_periodic_advertising/BLE5_periodic_advertising.ino
+++ b/libraries/BLE/examples/BLE5_periodic_advertising/BLE5_periodic_advertising.ino
@@ -5,7 +5,9 @@
    author: chegewara
 */
 
-#ifndef CONFIG_BT_BLE_50_FEATURES_SUPPORTED
+#ifndef CONFIG_BLUEDROID_ENABLED
+#error "NimBLE does not support periodic advertising yet. Try using Bluedroid."
+#elif !defined(CONFIG_BT_BLE_50_FEATURES_SUPPORTED)
 #error "This SoC does not support BLE5. Try using ESP32-C3, or ESP32-S3"
 #else
 #include <BLEDevice.h>
diff --git a/libraries/BLE/examples/BLE5_periodic_advertising/ci.json b/libraries/BLE/examples/BLE5_periodic_advertising/ci.json
index 184cc25a2b0..8e938055cf2 100644
--- a/libraries/BLE/examples/BLE5_periodic_advertising/ci.json
+++ b/libraries/BLE/examples/BLE5_periodic_advertising/ci.json
@@ -1,6 +1,7 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_BLE_50_SUPPORTED=y"
+    "CONFIG_SOC_BLE_50_SUPPORTED=y",
+    "CONFIG_BLUEDROID_ENABLED=y"
   ]
 }
diff --git a/libraries/BLE/examples/BLE5_periodic_sync/BLE5_periodic_sync.ino b/libraries/BLE/examples/BLE5_periodic_sync/BLE5_periodic_sync.ino
index 9e976e6ca6a..a93ebcefec3 100644
--- a/libraries/BLE/examples/BLE5_periodic_sync/BLE5_periodic_sync.ino
+++ b/libraries/BLE/examples/BLE5_periodic_sync/BLE5_periodic_sync.ino
@@ -7,8 +7,10 @@
 
    author: chegewara
 */
-#ifndef SOC_BLE_50_SUPPORTED
-#warning "This SoC does not support BLE5. Try using ESP32-C3, or ESP32-S3"
+#ifndef CONFIG_BLUEDROID_ENABLED
+#error "NimBLE does not support periodic sync yet. Try using Bluedroid."
+#elif !defined(SOC_BLE_50_SUPPORTED)
+#error "This SoC does not support BLE5. Try using ESP32-C3, or ESP32-S3"
 #else
 #include <BLEDevice.h>
 #include <BLEUtils.h>
diff --git a/libraries/BLE/examples/BLE5_periodic_sync/ci.json b/libraries/BLE/examples/BLE5_periodic_sync/ci.json
index 184cc25a2b0..8e938055cf2 100644
--- a/libraries/BLE/examples/BLE5_periodic_sync/ci.json
+++ b/libraries/BLE/examples/BLE5_periodic_sync/ci.json
@@ -1,6 +1,7 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_BLE_50_SUPPORTED=y"
+    "CONFIG_SOC_BLE_50_SUPPORTED=y",
+    "CONFIG_BLUEDROID_ENABLED=y"
   ]
 }
diff --git a/libraries/BLE/examples/Beacon_Scanner/Beacon_Scanner.ino b/libraries/BLE/examples/Beacon_Scanner/Beacon_Scanner.ino
index fbbf89ad274..4b4a311a37d 100644
--- a/libraries/BLE/examples/Beacon_Scanner/Beacon_Scanner.ino
+++ b/libraries/BLE/examples/Beacon_Scanner/Beacon_Scanner.ino
@@ -36,25 +36,33 @@ class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
     if (advertisedDevice.haveManufacturerData() == true) {
       String strManufacturerData = advertisedDevice.getManufacturerData();
 
-      uint8_t cManufacturerData[100];
-      memcpy(cManufacturerData, strManufacturerData.c_str(), strManufacturerData.length());
+      // Buffer to store manufacturer data (BLE max is 255 bytes)
+      uint8_t cManufacturerData[255];
+      size_t dataLength = strManufacturerData.length();
 
-      if (strManufacturerData.length() == 25 && cManufacturerData[0] == 0x4C && cManufacturerData[1] == 0x00) {
-        Serial.println("Found an iBeacon!");
-        BLEBeacon oBeacon = BLEBeacon();
-        oBeacon.setData(strManufacturerData);
-        Serial.printf("iBeacon Frame\n");
-        Serial.printf(
-          "ID: %04X Major: %d Minor: %d UUID: %s Power: %d\n", oBeacon.getManufacturerId(), ENDIAN_CHANGE_U16(oBeacon.getMajor()),
-          ENDIAN_CHANGE_U16(oBeacon.getMinor()), oBeacon.getProximityUUID().toString().c_str(), oBeacon.getSignalPower()
-        );
-      } else {
-        Serial.println("Found another manufacturers beacon!");
-        Serial.printf("strManufacturerData: %d ", strManufacturerData.length());
-        for (int i = 0; i < strManufacturerData.length(); i++) {
-          Serial.printf("[%X]", cManufacturerData[i]);
+      // Bounds checking to prevent buffer overflow
+      if (dataLength <= sizeof(cManufacturerData)) {
+        memcpy(cManufacturerData, strManufacturerData.c_str(), dataLength);
+
+        if (dataLength == 25 && cManufacturerData[0] == 0x4C && cManufacturerData[1] == 0x00) {
+          Serial.println("Found an iBeacon!");
+          BLEBeacon oBeacon = BLEBeacon();
+          oBeacon.setData(strManufacturerData);
+          Serial.printf("iBeacon Frame\n");
+          Serial.printf(
+            "ID: %04X Major: %d Minor: %d UUID: %s Power: %d\n", oBeacon.getManufacturerId(), ENDIAN_CHANGE_U16(oBeacon.getMajor()),
+            ENDIAN_CHANGE_U16(oBeacon.getMinor()), oBeacon.getProximityUUID().toString().c_str(), oBeacon.getSignalPower()
+          );
+        } else {
+          Serial.println("Found another manufacturers beacon!");
+          Serial.printf("strManufacturerData: %d ", dataLength);
+          for (int i = 0; i < dataLength; i++) {
+            Serial.printf("[%X]", cManufacturerData[i]);
+          }
+          Serial.printf("\n");
         }
-        Serial.printf("\n");
+      } else {
+        Serial.printf("Manufacturer data too large (%d bytes), skipping\n", dataLength);
       }
     }
 
diff --git a/libraries/BLE/examples/Client/Client.ino b/libraries/BLE/examples/Client/Client.ino
index ce2eb2ff7d1..713bfda8e93 100644
--- a/libraries/BLE/examples/Client/Client.ino
+++ b/libraries/BLE/examples/Client/Client.ino
@@ -19,6 +19,7 @@ static boolean doScan = false;
 static BLERemoteCharacteristic *pRemoteCharacteristic;
 static BLEAdvertisedDevice *myDevice;
 
+// Callback function to handle notifications
 static void notifyCallback(BLERemoteCharacteristic *pBLERemoteCharacteristic, uint8_t *pData, size_t length, bool isNotify) {
   Serial.print("Notify callback for characteristic ");
   Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
@@ -80,6 +81,7 @@ bool connectToServer() {
   }
 
   if (pRemoteCharacteristic->canNotify()) {
+    // Register/Subscribe for notifications
     pRemoteCharacteristic->registerForNotify(notifyCallback);
   }
 
diff --git a/libraries/BLE/examples/Notify/Notify.ino b/libraries/BLE/examples/Notify/Notify.ino
index 6b552b01d11..5f267685dfa 100644
--- a/libraries/BLE/examples/Notify/Notify.ino
+++ b/libraries/BLE/examples/Notify/Notify.ino
@@ -69,6 +69,7 @@ void setup() {
   );
 
   // Creates BLE Descriptor 0x2902: Client Characteristic Configuration Descriptor (CCCD)
+  // Descriptor 2902 is not required when using NimBLE as it is automatically added based on the characteristic properties
   pCharacteristic->addDescriptor(new BLE2902());
   // Adds also the Characteristic User Description - 0x2901 descriptor
   descriptor_2901 = new BLE2901();
diff --git a/libraries/BLE/examples/Server_multiconnect/Server_multiconnect.ino b/libraries/BLE/examples/Server_multiconnect/Server_multiconnect.ino
index afd15e9ae4f..ff8712d8281 100644
--- a/libraries/BLE/examples/Server_multiconnect/Server_multiconnect.ino
+++ b/libraries/BLE/examples/Server_multiconnect/Server_multiconnect.ino
@@ -5,6 +5,9 @@
     updated by chegewara
 
    Create a BLE server that, once we receive a connection, will send periodic notifications.
+   The server will continue advertising for more connections after the first one and will notify
+   the value of a counter to all connected clients.
+
    The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b
    And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8
 
@@ -26,8 +29,8 @@
 
 BLEServer *pServer = NULL;
 BLECharacteristic *pCharacteristic = NULL;
+int connectedClients = 0;
 bool deviceConnected = false;
-bool oldDeviceConnected = false;
 uint32_t value = 0;
 
 // See the following for generating UUIDs:
@@ -38,12 +41,17 @@ uint32_t value = 0;
 
 class MyServerCallbacks : public BLEServerCallbacks {
   void onConnect(BLEServer *pServer) {
-    deviceConnected = true;
+    connectedClients++;
+    Serial.print("Client connected. Total clients: ");
+    Serial.println(connectedClients);
+    // Continue advertising for more connections
     BLEDevice::startAdvertising();
   };
 
   void onDisconnect(BLEServer *pServer) {
-    deviceConnected = false;
+    connectedClients--;
+    Serial.print("Client disconnected. Total clients: ");
+    Serial.println(connectedClients);
   }
 };
 
@@ -66,8 +74,7 @@ void setup() {
     BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY | BLECharacteristic::PROPERTY_INDICATE
   );
 
-  // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
-  // Create a BLE Descriptor
+  // Descriptor 2902 is not required when using NimBLE as it is automatically added based on the characteristic properties
   pCharacteristic->addDescriptor(new BLE2902());
 
   // Start the service
@@ -79,27 +86,38 @@ void setup() {
   pAdvertising->setScanResponse(false);
   pAdvertising->setMinPreferred(0x0);  // set value to 0x00 to not advertise this parameter
   BLEDevice::startAdvertising();
-  Serial.println("Waiting a client connection to notify...");
+  Serial.println("Waiting for client connections to notify...");
 }
 
 void loop() {
-  // notify changed value
-  if (deviceConnected) {
+  // Notify changed value to all connected clients
+  if (connectedClients > 0) {
+    Serial.print("Notifying value: ");
+    Serial.print(value);
+    Serial.print(" to ");
+    Serial.print(connectedClients);
+    Serial.println(" client(s)");
     pCharacteristic->setValue((uint8_t *)&value, 4);
     pCharacteristic->notify();
     value++;
-    delay(10);  // bluetooth stack will go into congestion, if too many packets are sent, in 6 hours test i was able to go as low as 3ms
+    // Bluetooth stack will go into congestion, if too many packets are sent.
+    // In 6 hours of testing, I was able to go as low as 3ms.
+    // When using core debug level "debug" or "verbose", the delay can be increased in
+    // order to reduce the number of debug messages in the serial monitor.
+    delay(100);
   }
-  // disconnecting
-  if (!deviceConnected && oldDeviceConnected) {
+
+  // Disconnecting - restart advertising when no clients are connected
+  if (connectedClients == 0 && deviceConnected) {
     delay(500);                   // give the bluetooth stack the chance to get things ready
     pServer->startAdvertising();  // restart advertising
-    Serial.println("start advertising");
-    oldDeviceConnected = deviceConnected;
+    Serial.println("No clients connected, restarting advertising");
+    deviceConnected = false;
   }
-  // connecting
-  if (deviceConnected && !oldDeviceConnected) {
-    // do stuff here on connecting
-    oldDeviceConnected = deviceConnected;
+
+  // Connecting - update state when first client connects
+  if (connectedClients > 0 && !deviceConnected) {
+    // do stuff here on first connecting
+    deviceConnected = true;
   }
 }
diff --git a/libraries/BLE/examples/UART/UART.ino b/libraries/BLE/examples/UART/UART.ino
index 71cc850db66..d17ab494eca 100644
--- a/libraries/BLE/examples/UART/UART.ino
+++ b/libraries/BLE/examples/UART/UART.ino
@@ -40,10 +40,12 @@ uint8_t txValue = 0;
 class MyServerCallbacks : public BLEServerCallbacks {
   void onConnect(BLEServer *pServer) {
     deviceConnected = true;
+    Serial.println("Device connected");
   };
 
   void onDisconnect(BLEServer *pServer) {
     deviceConnected = false;
+    Serial.println("Device disconnected");
   }
 };
 
@@ -80,6 +82,7 @@ void setup() {
   // Create a BLE Characteristic
   pTxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_NOTIFY);
 
+  // Descriptor 2902 is not required when using NimBLE as it is automatically added based on the characteristic properties
   pTxCharacteristic->addDescriptor(new BLE2902());
 
   BLECharacteristic *pRxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);
@@ -97,22 +100,24 @@ void setup() {
 void loop() {
 
   if (deviceConnected) {
+    Serial.print("Notifying Value: ");
+    Serial.println(txValue);
     pTxCharacteristic->setValue(&txValue, 1);
     pTxCharacteristic->notify();
     txValue++;
-    delay(10);  // bluetooth stack will go into congestion, if too many packets are sent
+    delay(1000);  // Notifying every 1 second
   }
 
   // disconnecting
   if (!deviceConnected && oldDeviceConnected) {
     delay(500);                   // give the bluetooth stack the chance to get things ready
     pServer->startAdvertising();  // restart advertising
-    Serial.println("start advertising");
-    oldDeviceConnected = deviceConnected;
+    Serial.println("Started advertising again...");
+    oldDeviceConnected = false;
   }
   // connecting
   if (deviceConnected && !oldDeviceConnected) {
     // do stuff here on connecting
-    oldDeviceConnected = deviceConnected;
+    oldDeviceConnected = true;
   }
 }
diff --git a/libraries/BLE/library.properties b/libraries/BLE/library.properties
index 7ef636223ec..fe39f5093c4 100644
--- a/libraries/BLE/library.properties
+++ b/libraries/BLE/library.properties
@@ -1,7 +1,7 @@
 name=BLE
 version=3.2.0
 author=Neil Kolban <kolban1@kolban.com>
-maintainer=Dariusz Krempa <esp32@esp32.eu.org>
+maintainer=lucasssvaz
 sentence=BLE functions for ESP32
 paragraph=This library provides an implementation Bluetooth Low Energy support for the ESP32 using the Arduino platform.
 category=Communication
diff --git a/libraries/BLE/src/BLE2901.cpp b/libraries/BLE/src/BLE2901.cpp
index e929262b023..1fa4857ac33 100644
--- a/libraries/BLE/src/BLE2901.cpp
+++ b/libraries/BLE/src/BLE2901.cpp
@@ -1,29 +1,48 @@
 /*
-   BLE2901.h
+  BLE2901.h
 
-     GATT Descriptor 0x2901 Characteristic User Description
+  GATT Descriptor 0x2901 Characteristic User Description
 
-     The value of this description is a user-readable string
-     describing the characteristic.
+  The value of this description is a user-readable string
+  describing the characteristic.
 
-     The Characteristic User Description descriptor
-     provides a textual user description for a characteristic
-     value.
-     If the Writable Auxiliary bit of the Characteristics
-     Properties is set then this descriptor is written. Only one
-     User Description descriptor exists in a characteristic
-     definition.
+  The Characteristic User Description descriptor
+  provides a textual user description for a characteristic
+  value.
+  If the Writable Auxiliary bit of the Characteristics
+  Properties is set then this descriptor is written. Only one
+  User Description descriptor exists in a characteristic
+  definition.
 */
 
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                     Common includes and definitions                     *
+ ***************************************************************************/
 
 #include "BLE2901.h"
 
-BLE2901::BLE2901() : BLEDescriptor(BLEUUID((uint16_t)0x2901)) {}  // BLE2901
+#define BLE2901_UUID 0x2901
+
+/***************************************************************************
+ *                     NimBLE includes and definitions                     *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_att.h>
+#define ESP_GATT_MAX_ATTR_LEN BLE_ATT_ATTR_MAX_LEN
+#endif
+
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
+
+BLE2901::BLE2901() : BLEDescriptor(BLEUUID((uint16_t)BLE2901_UUID)) {}
 
 /**
  * @brief Set the Characteristic User Description
@@ -36,5 +55,5 @@ void BLE2901::setDescription(String userDesc) {
   setValue(userDesc);
 }
 
-#endif
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLE2901.h b/libraries/BLE/src/BLE2901.h
index f5ad7c94add..21e7cc9398c 100644
--- a/libraries/BLE/src/BLE2901.h
+++ b/libraries/BLE/src/BLE2901.h
@@ -1,37 +1,48 @@
 /*
-   BLE2901.h
+  BLE2901.h
 
-     GATT Descriptor 0x2901 Characteristic User Description
+  GATT Descriptor 0x2901 Characteristic User Description
 
-     The value of this description is a user-readable string
-     describing the characteristic.
-
-     The Characteristic User Description descriptor
-     provides a textual user description for a characteristic
-     value.
-     If the Writable Auxiliary bit of the Characteristics
-     Properties is set then this descriptor is written. Only one
-     User Description descriptor exists in a characteristic
-     definition.
+  The value of this description is a user-readable string
+  describing the characteristic.
 
+  The Characteristic User Description descriptor
+  provides a textual user description for a characteristic
+  value.
+  If the Writable Auxiliary bit of the Characteristics
+  Properties is set then this descriptor is written. Only one
+  User Description descriptor exists in a characteristic
+  definition.
 */
 
 #ifndef COMPONENTS_CPP_UTILS_BLE2901_H_
 #define COMPONENTS_CPP_UTILS_BLE2901_H_
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
 #include "BLEDescriptor.h"
 
+/**
+ * @brief GATT Descriptor 0x2901 Characteristic User Description
+ */
 class BLE2901 : public BLEDescriptor {
 public:
+  /***************************************************************************
+   *                         Common public functions                         *
+   ***************************************************************************/
+
   BLE2901();
   void setDescription(String desc);
 };  // BLE2901
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLE2901_H_ */
diff --git a/libraries/BLE/src/BLE2902.cpp b/libraries/BLE/src/BLE2902.cpp
index 90cdf088ff2..3bac9281328 100644
--- a/libraries/BLE/src/BLE2902.cpp
+++ b/libraries/BLE/src/BLE2902.cpp
@@ -3,46 +3,86 @@
  *
  *  Created on: Jun 25, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 /*
  * See also:
  * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                     Common includes and definitions                     *
+ ***************************************************************************/
 
 #include "BLE2902.h"
 
-BLE2902::BLE2902() : BLEDescriptor(BLEUUID((uint16_t)0x2902)) {
+#define BLE2902_UUID 0x2902
+
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
+
+BLE2902::BLE2902() : BLEDescriptor(BLEUUID((uint16_t)BLE2902_UUID)) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
   uint8_t data[2] = {0, 0};
   setValue(data, 2);
-}  // BLE2902
+#endif
+}
 
 /**
  * @brief Get the notifications value.
  * @return The notifications value.  True if notifications are enabled and false if not.
  */
 bool BLE2902::getNotifications() {
+#if defined(CONFIG_BLUEDROID_ENABLED)
   return (getValue()[0] & (1 << 0)) != 0;
-}  // getNotifications
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  if (m_pCharacteristic != nullptr) {
+    return (m_pCharacteristic->getProperties() & BLECharacteristic::PROPERTY_NOTIFY) != 0;
+  } else {
+    log_w("BLE2902::getNotifications() called on an uninitialized descriptor");
+    return false;
+  }
+#endif
+}
 
 /**
  * @brief Get the indications value.
  * @return The indications value.  True if indications are enabled and false if not.
  */
 bool BLE2902::getIndications() {
+#if defined(CONFIG_BLUEDROID_ENABLED)
   return (getValue()[0] & (1 << 1)) != 0;
-}  // getIndications
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  if (m_pCharacteristic != nullptr) {
+    return (m_pCharacteristic->getProperties() & BLECharacteristic::PROPERTY_INDICATE) != 0;
+  } else {
+    log_w("BLE2902::getIndications() called on an uninitialized descriptor");
+    return false;
+  }
+#endif
+}
 
 /**
  * @brief Set the indications flag.
  * @param [in] flag The indications flag.
  */
 void BLE2902::setIndications(bool flag) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
   uint8_t *pValue = getValue();
   if (flag) {
     pValue[0] |= 1 << 1;
@@ -50,13 +90,23 @@ void BLE2902::setIndications(bool flag) {
     pValue[0] &= ~(1 << 1);
   }
   setValue(pValue, 2);
-}  // setIndications
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  if (m_pCharacteristic != nullptr) {
+    m_pCharacteristic->setIndicateProperty(flag);
+  } else {
+    log_w("BLE2902::setIndications() called on an uninitialized descriptor");
+  }
+#endif
+}
 
 /**
  * @brief Set the notifications flag.
  * @param [in] flag The notifications flag.
  */
 void BLE2902::setNotifications(bool flag) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
   uint8_t *pValue = getValue();
   if (flag) {
     pValue[0] |= 1 << 0;
@@ -64,7 +114,16 @@ void BLE2902::setNotifications(bool flag) {
     pValue[0] &= ~(1 << 0);
   }
   setValue(pValue, 2);
-}  // setNotifications
+#endif
 
+#if defined(CONFIG_NIMBLE_ENABLED)
+  if (m_pCharacteristic != nullptr) {
+    m_pCharacteristic->setNotifyProperty(flag);
+  } else {
+    log_w("BLE2902::setNotifications() called on an uninitialized descriptor");
+  }
 #endif
+}
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLE2902.h b/libraries/BLE/src/BLE2902.h
index 74a477f3151..5cbf911ea4a 100644
--- a/libraries/BLE/src/BLE2902.h
+++ b/libraries/BLE/src/BLE2902.h
@@ -3,15 +3,24 @@
  *
  *  Created on: Jun 25, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 28, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLE2902_H_
 #define COMPONENTS_CPP_UTILS_BLE2902_H_
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
 #include "BLEDescriptor.h"
 
@@ -23,16 +32,35 @@
  * See also:
  * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
  */
+
+// Class declaration for Bluedroid
+#if defined(CONFIG_BLUEDROID_ENABLED)
 class BLE2902 : public BLEDescriptor {
-public:
-  BLE2902();
-  bool getNotifications();
-  bool getIndications();
-  void setNotifications(bool flag);
-  void setIndications(bool flag);
+#endif
+
+// Class declaration for NimBLE (deprecated)
+#if defined(CONFIG_NIMBLE_ENABLED)
+  class [[deprecated("NimBLE does not support manually adding 2902 descriptors as they \
+are automatically added when the characteristic has notifications or indications enabled. \
+Get/Set the notifications/indications properties of the characteristic instead. \
+This class will be removed in a future version.")]] BLE2902 : public BLEDescriptor {
+#endif
+
+  public:
+    /***************************************************************************
+   *                         Common public functions                         *
+   ***************************************************************************/
+
+    BLE2902();
+    bool getNotifications();
+    bool getIndications();
+    void setNotifications(bool flag);
+    void setIndications(bool flag);
 
-};  // BLE2902
+  private:
+    friend class BLECharacteristic;
+  };  // BLE2902
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLE2902_H_ */
diff --git a/libraries/BLE/src/BLE2904.cpp b/libraries/BLE/src/BLE2904.cpp
index aeed11ebad1..19658051120 100644
--- a/libraries/BLE/src/BLE2904.cpp
+++ b/libraries/BLE/src/BLE2904.cpp
@@ -3,6 +3,10 @@
  *
  *  Created on: Dec 23, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 /*
@@ -13,18 +17,30 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                     Common includes and definitions                     *
+ ***************************************************************************/
 
 #include "BLE2904.h"
 
-BLE2904::BLE2904() : BLEDescriptor(BLEUUID((uint16_t)0x2904)) {
+#define BLE2904_UUID              0x2904
+#define BLE2904_DEFAULT_NAMESPACE 1       // 1 = Bluetooth SIG Assigned Numbers
+#define BLE2904_DEFAULT_UNIT      0x2700  // 0x2700 = Unitless
+
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
+
+BLE2904::BLE2904() : BLEDescriptor(BLEUUID((uint16_t)BLE2904_UUID)) {
   m_data.m_format = 0;
   m_data.m_exponent = 0;
-  m_data.m_namespace = 1;  // 1 = Bluetooth SIG Assigned Numbers
-  m_data.m_unit = 0;
+  m_data.m_namespace = BLE2904_DEFAULT_NAMESPACE;
+  m_data.m_unit = BLE2904_DEFAULT_UNIT;
   m_data.m_description = 0;
   setValue((uint8_t *)&m_data, sizeof(m_data));
-}  // BLE2902
+}
 
 /**
  * @brief Set the description.
@@ -40,7 +56,7 @@ void BLE2904::setDescription(uint16_t description) {
 void BLE2904::setExponent(int8_t exponent) {
   m_data.m_exponent = exponent;
   setValue((uint8_t *)&m_data, sizeof(m_data));
-}  // setExponent
+}
 
 /**
  * @brief Set the format.
@@ -48,7 +64,7 @@ void BLE2904::setExponent(int8_t exponent) {
 void BLE2904::setFormat(uint8_t format) {
   m_data.m_format = format;
   setValue((uint8_t *)&m_data, sizeof(m_data));
-}  // setFormat
+}
 
 /**
  * @brief Set the namespace.
@@ -56,7 +72,7 @@ void BLE2904::setFormat(uint8_t format) {
 void BLE2904::setNamespace(uint8_t namespace_value) {
   m_data.m_namespace = namespace_value;
   setValue((uint8_t *)&m_data, sizeof(m_data));
-}  // setNamespace
+}
 
 /**
  * @brief Set the units for this value.  It should be one of the encoded values defined here:
@@ -66,7 +82,7 @@ void BLE2904::setNamespace(uint8_t namespace_value) {
 void BLE2904::setUnit(uint16_t unit) {
   m_data.m_unit = unit;
   setValue((uint8_t *)&m_data, sizeof(m_data));
-}  // setUnit
+}
 
-#endif
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLE2904.h b/libraries/BLE/src/BLE2904.h
index 3ba66da0dc8..87e8c03c048 100644
--- a/libraries/BLE/src/BLE2904.h
+++ b/libraries/BLE/src/BLE2904.h
@@ -3,27 +3,43 @@
  *
  *  Created on: Dec 23, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLE2904_H_
 #define COMPONENTS_CPP_UTILS_BLE2904_H_
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
 #include "BLEDescriptor.h"
 
+/***************************************************************************
+ *                            Common types                                 *
+ ***************************************************************************/
+
 struct BLE2904_Data {
   uint8_t m_format;
   int8_t m_exponent;
   uint16_t m_unit;  // See https://www.bluetooth.com/specifications/assigned-numbers/units
   uint8_t m_namespace;
   uint16_t m_description;
-
 } __attribute__((packed));
 
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
+
 /**
  * @brief Descriptor for Characteristic Presentation Format.
  *
@@ -34,7 +50,10 @@ struct BLE2904_Data {
  */
 class BLE2904 : public BLEDescriptor {
 public:
-  BLE2904();
+  /***************************************************************************
+   *                         Common public constants                         *
+   ***************************************************************************/
+
   static const uint8_t FORMAT_BOOLEAN = 1;
   static const uint8_t FORMAT_UINT2 = 2;
   static const uint8_t FORMAT_UINT4 = 3;
@@ -62,7 +81,13 @@ class BLE2904 : public BLEDescriptor {
   static const uint8_t FORMAT_UTF8 = 25;
   static const uint8_t FORMAT_UTF16 = 26;
   static const uint8_t FORMAT_OPAQUE = 27;
+  static const uint8_t FORMAT_MEDASN1 = 28;
+
+  /***************************************************************************
+   *                         Common public functions                         *
+   ***************************************************************************/
 
+  BLE2904();
   void setDescription(uint16_t);
   void setExponent(int8_t exponent);
   void setFormat(uint8_t format);
@@ -70,9 +95,15 @@ class BLE2904 : public BLEDescriptor {
   void setUnit(uint16_t unit);
 
 private:
+  friend class BLECharacteristic;
+
+  /***************************************************************************
+   *                         Common private properties                         *
+   ***************************************************************************/
+
   BLE2904_Data m_data;
 };  // BLE2904
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLE2904_H_ */
diff --git a/libraries/BLE/src/BLEAddress.cpp b/libraries/BLE/src/BLEAddress.cpp
index b91ef3cc4de..11c64850367 100644
--- a/libraries/BLE/src/BLEAddress.cpp
+++ b/libraries/BLE/src/BLEAddress.cpp
@@ -3,12 +3,21 @@
  *
  *  Created on: Jul 2, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
 #include "BLEAddress.h"
 #include <string>
@@ -17,43 +26,33 @@
 #include <string.h>
 #include <stdio.h>
 #include <malloc.h>
+
 #ifdef ARDUINO_ARCH_ESP32
 #include "esp32-hal-log.h"
 #endif
 
-/**
- * @brief Create an address from the native ESP32 representation.
- * @param [in] address The native representation.
- */
-BLEAddress::BLEAddress(esp_bd_addr_t address) {
-  memcpy(m_address, address, ESP_BD_ADDR_LEN);
-}  // BLEAddress
+/***************************************************************************
+ *                           NimBLE includes                               *
+ ***************************************************************************/
 
-/**
- * @brief Create an address from a hex string
- *
- * A hex string is of the format:
- * ```
- * 00:00:00:00:00:00
- * ```
- * which is 17 characters in length.
- *
- * @param [in] stringAddress The hex representation of the address.
- */
-BLEAddress::BLEAddress(String stringAddress) {
-  if (stringAddress.length() != 17) {
-    return;
-  }
+#if defined(CONFIG_NIMBLE_ENABLED)
+/*************************************************
+ * NOTE: NimBLE address bytes are in INVERSE ORDER!
+ * We will accommodate that fact in these methods.
+*************************************************/
+#include <algorithm>
+#endif
 
-  int data[6];
-  sscanf(stringAddress.c_str(), "%x:%x:%x:%x:%x:%x", &data[0], &data[1], &data[2], &data[3], &data[4], &data[5]);
-  m_address[0] = (uint8_t)data[0];
-  m_address[1] = (uint8_t)data[1];
-  m_address[2] = (uint8_t)data[2];
-  m_address[3] = (uint8_t)data[3];
-  m_address[4] = (uint8_t)data[4];
-  m_address[5] = (uint8_t)data[5];
-}  // BLEAddress
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
+
+BLEAddress::BLEAddress() {
+  memset(m_address, 0, ESP_BD_ADDR_LEN);
+#if defined(CONFIG_NIMBLE_ENABLED)
+  m_addrType = 0;
+#endif
+}
 
 /**
  * @brief Determine if this address equals another.
@@ -61,10 +60,20 @@ BLEAddress::BLEAddress(String stringAddress) {
  * @return True if the addresses are equal.
  */
 bool BLEAddress::equals(BLEAddress otherAddress) {
+#if defined(CONFIG_NIMBLE_ENABLED)
+  if (m_addrType != otherAddress.m_addrType) {
+    return false;
+  }
+#endif
   return memcmp(otherAddress.getNative(), m_address, ESP_BD_ADDR_LEN) == 0;
-}  // equals
+}
 
 bool BLEAddress::operator==(const BLEAddress &otherAddress) const {
+#if defined(CONFIG_NIMBLE_ENABLED)
+  if (m_addrType != otherAddress.m_addrType) {
+    return false;
+  }
+#endif
   return memcmp(otherAddress.m_address, m_address, ESP_BD_ADDR_LEN) == 0;
 }
 
@@ -92,9 +101,9 @@ bool BLEAddress::operator>(const BLEAddress &otherAddress) const {
  * @brief Return the native representation of the address.
  * @return The native representation of the address.
  */
-esp_bd_addr_t *BLEAddress::getNative() {
-  return &m_address;
-}  // getNative
+uint8_t *BLEAddress::getNative() {
+  return m_address;
+}
 
 /**
  * @brief Convert a BLE address to a string.
@@ -110,11 +119,112 @@ esp_bd_addr_t *BLEAddress::getNative() {
 String BLEAddress::toString() {
   auto size = 18;
   char *res = (char *)malloc(size);
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
   snprintf(res, size, "%02x:%02x:%02x:%02x:%02x:%02x", m_address[0], m_address[1], m_address[2], m_address[3], m_address[4], m_address[5]);
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  snprintf(res, size, "%02x:%02x:%02x:%02x:%02x:%02x", m_address[5], m_address[4], m_address[3], m_address[2], m_address[1], m_address[0]);
+#endif
+
   String ret(res);
   free(res);
   return ret;
-}  // toString
+}
+
+/***************************************************************************
+ *                          Bluedroid functions                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+
+/**
+ * @brief Create an address from the native ESP32 representation.
+ * @param [in] address The native representation.
+ */
+BLEAddress::BLEAddress(esp_bd_addr_t address) {
+  memcpy(m_address, address, ESP_BD_ADDR_LEN);
+}
+
+/**
+ * @brief Create an address from a hex string
+ *
+ * A hex string is of the format:
+ * ```
+ * 00:00:00:00:00:00
+ * ```
+ * which is 17 characters in length.
+ *
+ * @param [in] stringAddress The hex representation of the address.
+ */
+BLEAddress::BLEAddress(String stringAddress) {
+  if (stringAddress.length() != 17) {
+    return;
+  }
+
+  int data[6];
+  sscanf(stringAddress.c_str(), "%x:%x:%x:%x:%x:%x", &data[0], &data[1], &data[2], &data[3], &data[4], &data[5]);
+
+  for (size_t index = 0; index < sizeof(m_address); index++) {
+    m_address[index] = (uint8_t)data[index];
+  }
+}
+
+#endif
+
+/***************************************************************************
+ *                          NimBLE functions                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+/*************************************************
+ * NOTE: NimBLE address bytes are in INVERSE ORDER!
+ * We will accommodate that fact in these methods.
+*************************************************/
+
+BLEAddress::BLEAddress(uint8_t address[ESP_BD_ADDR_LEN], uint8_t type) {
+  std::reverse_copy(address, address + sizeof(m_address), m_address);
+  m_addrType = type;
+}
+
+BLEAddress::BLEAddress(ble_addr_t address) {
+  memcpy(m_address, address.val, ESP_BD_ADDR_LEN);
+  m_addrType = address.type;
+}
+
+uint8_t BLEAddress::getType() {
+  return m_addrType;
+}
+
+/**
+ * @brief Create an address from a hex string
+ *
+ * A hex string is of the format:
+ * ```
+ * 00:00:00:00:00:00
+ * ```
+ * which is 17 characters in length.
+ *
+ * @param [in] stringAddress The hex representation of the address.
+ * @param [in] type The address type.
+ */
+BLEAddress::BLEAddress(String stringAddress, uint8_t type) {
+  if (stringAddress.length() != 17) {
+    return;
+  }
+
+  int data[6];
+  m_addrType = type;
+  // NimBLE addresses are in INVERSE ORDER!
+  sscanf(stringAddress.c_str(), "%x:%x:%x:%x:%x:%x", &data[5], &data[4], &data[3], &data[2], &data[1], &data[0]);
+
+  for (size_t index = 0; index < sizeof(m_address); index++) {
+    m_address[index] = (uint8_t)data[index];
+  }
+}
 
 #endif
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEAddress.h b/libraries/BLE/src/BLEAddress.h
index f1c8aa9b632..71b3bdfce5f 100644
--- a/libraries/BLE/src/BLEAddress.h
+++ b/libraries/BLE/src/BLEAddress.h
@@ -3,19 +3,53 @@
  *
  *  Created on: Jul 2, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLEADDRESS_H_
 #define COMPONENTS_CPP_UTILS_BLEADDRESS_H_
 #include "soc/soc_caps.h"
-#include "WString.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
-#include <esp_gap_ble_api.h>  // ESP32 BLE
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
+#include "WString.h"
+#include <esp_bt.h>
 #include <string>
 
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gap_ble_api.h>
+#endif
+
+/***************************************************************************
+ *                     NimBLE includes and definitions                     *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <nimble/ble.h>
+#define ESP_BD_ADDR_LEN BLE_DEV_ADDR_LEN
+#endif
+
+/***************************************************************************
+ *                            NimBLE types                                 *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+typedef uint8_t esp_bd_addr_t[ESP_BD_ADDR_LEN];
+#endif
+
 /**
  * @brief A %BLE device address.
  *
@@ -23,8 +57,11 @@
  */
 class BLEAddress {
 public:
-  BLEAddress(esp_bd_addr_t address);
-  BLEAddress(String stringAddress);
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
+  BLEAddress();
   bool equals(BLEAddress otherAddress);
   bool operator==(const BLEAddress &otherAddress) const;
   bool operator!=(const BLEAddress &otherAddress) const;
@@ -32,13 +69,45 @@ class BLEAddress {
   bool operator<=(const BLEAddress &otherAddress) const;
   bool operator>(const BLEAddress &otherAddress) const;
   bool operator>=(const BLEAddress &otherAddress) const;
-  esp_bd_addr_t *getNative();
+  uint8_t *getNative();
   String toString();
 
+  /***************************************************************************
+   *                       Bluedroid public declarations                     *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  BLEAddress(esp_bd_addr_t address);
+  BLEAddress(String stringAddress);
+#endif
+
+  /***************************************************************************
+   *                       NimBLE public declarations                        *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  BLEAddress(ble_addr_t address);
+  BLEAddress(String stringAddress, uint8_t type = BLE_ADDR_PUBLIC);
+  BLEAddress(uint8_t address[ESP_BD_ADDR_LEN], uint8_t type = BLE_ADDR_PUBLIC);
+  uint8_t getType();
+#endif
+
 private:
-  esp_bd_addr_t m_address;
+  /***************************************************************************
+   *                       Common private properties                         *
+   ***************************************************************************/
+
+  uint8_t m_address[ESP_BD_ADDR_LEN];
+
+  /***************************************************************************
+   *                       NimBLE private properties                         *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  uint8_t m_addrType;
+#endif
 };
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLEADDRESS_H_ */
diff --git a/libraries/BLE/src/BLEAdvertisedDevice.cpp b/libraries/BLE/src/BLEAdvertisedDevice.cpp
index 8752d24a199..3ac1dfab5c8 100644
--- a/libraries/BLE/src/BLEAdvertisedDevice.cpp
+++ b/libraries/BLE/src/BLEAdvertisedDevice.cpp
@@ -4,22 +4,35 @@
  * During the scanning procedure, we will be finding advertised BLE devices.  This class
  * models a found device.
  *
- *
  * See also:
  * https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile
  *
  *  Created on: Jul 3, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
 #include <sstream>
 #include "BLEAdvertisedDevice.h"
 #include "BLEUtils.h"
 #include "esp32-hal-log.h"
 
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
+
 BLEAdvertisedDevice::BLEAdvertisedDevice() {
   m_adFlag = 0;
   m_appearance = 0;
@@ -32,15 +45,47 @@ BLEAdvertisedDevice::BLEAdvertisedDevice() {
   m_serviceDataUUIDs = {};
   m_txPower = 0;
   m_pScan = nullptr;
+  m_advType = 0;
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  m_callbackSent = false;
+#endif
 
   m_haveAppearance = false;
   m_haveManufacturerData = false;
   m_haveName = false;
   m_haveRSSI = false;
   m_haveTXPower = false;
-
+  m_isLegacyAdv = true;
 }  // BLEAdvertisedDevice
 
+bool BLEAdvertisedDevice::isLegacyAdvertisement() {
+  return m_isLegacyAdv;
+}
+
+bool BLEAdvertisedDevice::isScannable() {
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  return isLegacyAdvertisement() && (m_advType == ESP_BLE_EVT_CONN_ADV || m_advType == ESP_BLE_EVT_DISC_ADV);
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  return isLegacyAdvertisement() && (m_advType == BLE_HCI_ADV_TYPE_ADV_IND || m_advType == BLE_HCI_ADV_TYPE_ADV_SCAN_IND);
+#endif
+}
+
+bool BLEAdvertisedDevice::isConnectable() {
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  return m_advType == ESP_BLE_EVT_CONN_ADV || m_advType == ESP_BLE_EVT_CONN_DIR_ADV;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  if (m_isLegacyAdv) {
+    return m_advType == BLE_HCI_ADV_RPT_EVTYPE_ADV_IND || m_advType == BLE_HCI_ADV_RPT_EVTYPE_DIR_IND;
+  }
+  return (m_advType & BLE_HCI_ADV_CONN_MASK) || (m_advType & BLE_HCI_ADV_DIRECT_MASK);
+#endif
+}
+
 /**
  * @brief Get the address.
  *
@@ -277,75 +322,75 @@ void BLEAdvertisedDevice::parseAdvertisement(uint8_t *payload, size_t total_len)
       length--;
 
       char *pHex = BLEUtils::buildHexData(nullptr, payload, length);
-      log_d("Type: 0x%.2x (%s), length: %d, data: %s", ad_type, BLEUtils::advTypeToString(ad_type), length, pHex);
+      log_d("Type: 0x%.2x (%s), length: %d, data: %s", ad_type, BLEUtils::advDataTypeToString(ad_type), length, pHex);
       free(pHex);
 
       switch (ad_type) {
-        case ESP_BLE_AD_TYPE_NAME_CMPL:
-        {  // Adv Data Type: 0x09
+        case ESP_BLE_AD_TYPE_NAME_CMPL:  // 0x09
+        {                                // Adv Data Type: ESP_BLE_AD_TYPE_NAME_CMPL
           setName(String(reinterpret_cast<char *>(payload), length));
           break;
-        }  // ESP_BLE_AD_TYPE_NAME_CMPL
+        }  // 0x09
 
-        case ESP_BLE_AD_TYPE_TX_PWR:
-        {  // Adv Data Type: 0x0A
+        case ESP_BLE_AD_TYPE_TX_PWR:  // 0x0A
+        {                             // Adv Data Type: ESP_BLE_AD_TYPE_TX_PWR
           setTXPower(*payload);
           break;
-        }  // ESP_BLE_AD_TYPE_TX_PWR
+        }  // 0x0A
 
-        case ESP_BLE_AD_TYPE_APPEARANCE:
-        {  // Adv Data Type: 0x19
+        case ESP_BLE_AD_TYPE_APPEARANCE:  // 0x19
+        {                                 // Adv Data Type: ESP_BLE_AD_TYPE_APPEARANCE
           setAppearance(*reinterpret_cast<uint16_t *>(payload));
           break;
-        }  // ESP_BLE_AD_TYPE_APPEARANCE
+        }  // 0x19
 
-        case ESP_BLE_AD_TYPE_FLAG:
-        {  // Adv Data Type: 0x01
+        case ESP_BLE_AD_TYPE_FLAG:  // 0x01
+        {                           // Adv Data Type: ESP_BLE_AD_TYPE_FLAG
           setAdFlag(*payload);
           break;
-        }  // ESP_BLE_AD_TYPE_FLAG
+        }  // 0x01
 
-        case ESP_BLE_AD_TYPE_16SRV_CMPL:
-        case ESP_BLE_AD_TYPE_16SRV_PART:
-        {  // Adv Data Type: 0x02
+        case ESP_BLE_AD_TYPE_16SRV_PART:  // 0x02
+        case ESP_BLE_AD_TYPE_16SRV_CMPL:  // 0x03
+        {                                 // Adv Data Type: ESP_BLE_AD_TYPE_16SRV_PART/CMPL
           for (int var = 0; var < length / 2; ++var) {
             setServiceUUID(BLEUUID(*reinterpret_cast<uint16_t *>(payload + var * 2)));
           }
           break;
-        }  // ESP_BLE_AD_TYPE_16SRV_PART
+        }  // 0x02, 0x03
 
-        case ESP_BLE_AD_TYPE_32SRV_CMPL:
-        case ESP_BLE_AD_TYPE_32SRV_PART:
-        {  // Adv Data Type: 0x04
+        case ESP_BLE_AD_TYPE_32SRV_PART:  // 0x04
+        case ESP_BLE_AD_TYPE_32SRV_CMPL:  // 0x05
+        {                                 // Adv Data Type: ESP_BLE_AD_TYPE_32SRV_PART/CMPL
           for (int var = 0; var < length / 4; ++var) {
             setServiceUUID(BLEUUID(*reinterpret_cast<uint32_t *>(payload + var * 4)));
           }
           break;
-        }  // ESP_BLE_AD_TYPE_32SRV_PART
+        }  // 0x04, 0x05
 
-        case ESP_BLE_AD_TYPE_128SRV_CMPL:
-        {  // Adv Data Type: 0x07
+        case ESP_BLE_AD_TYPE_128SRV_CMPL:  // 0x07
+        {                                  // Adv Data Type: ESP_BLE_AD_TYPE_128SRV_CMPL
           setServiceUUID(BLEUUID(payload, 16, false));
           break;
-        }  // ESP_BLE_AD_TYPE_128SRV_CMPL
+        }  // 0x07
 
-        case ESP_BLE_AD_TYPE_128SRV_PART:
-        {  // Adv Data Type: 0x06
+        case ESP_BLE_AD_TYPE_128SRV_PART:  // 0x06
+        {                                  // Adv Data Type: ESP_BLE_AD_TYPE_128SRV_PART
           setServiceUUID(BLEUUID(payload, 16, false));
           break;
-        }  // ESP_BLE_AD_TYPE_128SRV_PART
+        }  // 0x06
 
         // See CSS Part A 1.4 Manufacturer Specific Data
-        case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE:
+        case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE:  // 0xFF
         {
           setManufacturerData(String(reinterpret_cast<char *>(payload), length));
           break;
-        }  // ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE
+        }  // 0xFF
 
-        case ESP_BLE_AD_TYPE_SERVICE_DATA:
-        {  // Adv Data Type: 0x16 (Service Data) - 2 byte UUID
+        case ESP_BLE_AD_TYPE_SERVICE_DATA:  // 0x16
+        {                                   // Adv Data Type: ESP_BLE_AD_TYPE_SERVICE_DATA - 2 byte UUID
           if (length < 2) {
-            log_e("Length too small for ESP_BLE_AD_TYPE_SERVICE_DATA");
+            log_e("Length too small for SERVICE_DATA");
             break;
           }
           uint16_t uuid = *(uint16_t *)payload;
@@ -354,12 +399,12 @@ void BLEAdvertisedDevice::parseAdvertisement(uint8_t *payload, size_t total_len)
             setServiceData(String(reinterpret_cast<char *>(payload + 2), length - 2));
           }
           break;
-        }  //ESP_BLE_AD_TYPE_SERVICE_DATA
+        }  // 0x16
 
-        case ESP_BLE_AD_TYPE_32SERVICE_DATA:
-        {  // Adv Data Type: 0x20 (Service Data) - 4 byte UUID
+        case ESP_BLE_AD_TYPE_32SERVICE_DATA:  // 0x20
+        {                                     // Adv Data Type: ESP_BLE_AD_TYPE_32SERVICE_DATA - 4 byte UUID
           if (length < 4) {
-            log_e("Length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA");
+            log_e("Length too small for 32SERVICE_DATA");
             break;
           }
           uint32_t uuid = *(uint32_t *)payload;
@@ -368,12 +413,12 @@ void BLEAdvertisedDevice::parseAdvertisement(uint8_t *payload, size_t total_len)
             setServiceData(String(reinterpret_cast<char *>(payload + 4), length - 4));
           }
           break;
-        }  //ESP_BLE_AD_TYPE_32SERVICE_DATA
+        }  // 0x20
 
-        case ESP_BLE_AD_TYPE_128SERVICE_DATA:
-        {  // Adv Data Type: 0x21 (Service Data) - 16 byte UUID
+        case ESP_BLE_AD_TYPE_128SERVICE_DATA:  // 0x21
+        {                                      // Adv Data Type: ESP_BLE_AD_TYPE_128SERVICE_DATA - 16 byte UUID
           if (length < 16) {
-            log_e("Length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA");
+            log_e("Length too small for 128SERVICE_DATA");
             break;
           }
 
@@ -382,13 +427,13 @@ void BLEAdvertisedDevice::parseAdvertisement(uint8_t *payload, size_t total_len)
             setServiceData(String(reinterpret_cast<char *>(payload + 16), length - 16));
           }
           break;
-        }  //ESP_BLE_AD_TYPE_32SERVICE_DATA
+        }  // 0x21
 
         default:
         {
           log_d("Unhandled type: adType: %d - 0x%.2x", ad_type, ad_type);
           break;
-        }
+        }  // default
       }  // switch
       payload += length;
     }  // Length <> 0
@@ -405,9 +450,19 @@ void BLEAdvertisedDevice::parseAdvertisement(uint8_t *payload, size_t total_len)
  * @param [in] payload The payload of the advertised device.
  * @param [in] total_len The length of payload
  */
-void BLEAdvertisedDevice::setPayload(uint8_t *payload, size_t total_len) {
-  m_payload = payload;
-  m_payloadLength = total_len;
+void BLEAdvertisedDevice::setPayload(uint8_t *payload, size_t total_len, bool append) {
+  if (m_payload == nullptr || m_payloadLength == 0) {
+    return;
+  }
+
+  if (append) {
+    m_payload = (uint8_t *)realloc(m_payload, m_payloadLength + total_len);
+    memcpy(m_payload + m_payloadLength, payload, total_len);
+    m_payloadLength += total_len;
+  } else {
+    m_payload = payload;
+    m_payloadLength = total_len;
+  }
 }  // setPayload
 
 /**
@@ -567,7 +622,7 @@ uint8_t *BLEAdvertisedDevice::getPayload() {
   return m_payload;
 }
 
-esp_ble_addr_type_t BLEAdvertisedDevice::getAddressType() {
+uint8_t BLEAdvertisedDevice::getAddressType() {
   return m_addressType;
 }
 
@@ -587,7 +642,7 @@ ble_frame_type_t BLEAdvertisedDevice::getFrameType() {
   return BLE_UNKNOWN_FRAME;
 }
 
-void BLEAdvertisedDevice::setAddressType(esp_ble_addr_type_t type) {
+void BLEAdvertisedDevice::setAddressType(uint8_t type) {
   m_addressType = type;
 }
 
@@ -595,5 +650,13 @@ size_t BLEAdvertisedDevice::getPayloadLength() {
   return m_payloadLength;
 }
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+void BLEAdvertisedDevice::setAdvType(uint8_t type) {
+  m_advType = type;
+}
+
+uint8_t BLEAdvertisedDevice::getAdvType() {
+  return m_advType;
+}
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEAdvertisedDevice.h b/libraries/BLE/src/BLEAdvertisedDevice.h
index 700e5704034..2a2fc0c81aa 100644
--- a/libraries/BLE/src/BLEAdvertisedDevice.h
+++ b/libraries/BLE/src/BLEAdvertisedDevice.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Jul 3, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLEADVERTISEDDEVICE_H_
@@ -11,15 +15,38 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
-#include <esp_gattc_api.h>
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
 
-#include <map>
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
+#include <map>
 #include "BLEAddress.h"
 #include "BLEScan.h"
 #include "BLEUUID.h"
 
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gattc_api.h>
+#endif
+
+/***************************************************************************
+ *                           NimBLE includes                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <nimble/ble.h>
+#include <host/ble_gap.h>
+#endif
+
+/***************************************************************************
+ *                            Common types                                 *
+ ***************************************************************************/
+
 typedef enum {
   BLE_UNKNOWN_FRAME,
   BLE_EDDYSTONE_UUID_FRAME,
@@ -28,7 +55,12 @@ typedef enum {
   BLE_FRAME_MAX
 } ble_frame_type_t;
 
+/***************************************************************************
+ *                           Forward declarations                          *
+ ***************************************************************************/
+
 class BLEScan;
+
 /**
  * @brief A representation of a %BLE advertised device found by a scan.
  *
@@ -37,8 +69,11 @@ class BLEScan;
  */
 class BLEAdvertisedDevice {
 public:
-  BLEAdvertisedDevice();
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
 
+  BLEAdvertisedDevice();
   BLEAddress getAddress();
   uint16_t getAppearance();
   String getManufacturerData();
@@ -57,10 +92,15 @@ class BLEAdvertisedDevice {
   int8_t getTXPower();
   uint8_t *getPayload();
   size_t getPayloadLength();
-  esp_ble_addr_type_t getAddressType();
+  uint8_t getAddressType();
   ble_frame_type_t getFrameType();
-  void setAddressType(esp_ble_addr_type_t type);
+  void setAddressType(uint8_t type);
+  void setAdvType(uint8_t type);
+  uint8_t getAdvType();
 
+  bool isLegacyAdvertisement();
+  bool isScannable();
+  bool isConnectable();
   bool isAdvertisingService(BLEUUID uuid);
   bool haveAppearance();
   bool haveManufacturerData();
@@ -75,28 +115,15 @@ class BLEAdvertisedDevice {
 private:
   friend class BLEScan;
 
-  void parseAdvertisement(uint8_t *payload, size_t total_len = 62);
-  void setPayload(uint8_t *payload, size_t total_len = 62);
-  void setAddress(BLEAddress address);
-  void setAdFlag(uint8_t adFlag);
-  void setAdvertizementResult(uint8_t *payload);
-  void setAppearance(uint16_t appearance);
-  void setManufacturerData(String manufacturerData);
-  void setName(String name);
-  void setRSSI(int rssi);
-  void setScan(BLEScan *pScan);
-  void setServiceData(String data);
-  void setServiceDataUUID(BLEUUID uuid);
-  void setServiceUUID(const char *serviceUUID);
-  void setServiceUUID(BLEUUID serviceUUID);
-  void setTXPower(int8_t txPower);
+  /***************************************************************************
+   *                       Common private properties                         *
+   ***************************************************************************/
 
   bool m_haveAppearance;
   bool m_haveManufacturerData;
   bool m_haveName;
   bool m_haveRSSI;
   bool m_haveTXPower;
-
   BLEAddress m_address = BLEAddress((uint8_t *)"\0\0\0\0\0\0");
   uint8_t m_adFlag;
   uint16_t m_appearance;
@@ -111,7 +138,37 @@ class BLEAdvertisedDevice {
   std::vector<BLEUUID> m_serviceDataUUIDs;
   uint8_t *m_payload;
   size_t m_payloadLength = 0;
-  esp_ble_addr_type_t m_addressType;
+  uint8_t m_addressType;
+  uint8_t m_advType;
+  bool m_isLegacyAdv;
+
+  /***************************************************************************
+   *                       NimBLE private properties                         *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  bool m_callbackSent;
+#endif
+
+  /***************************************************************************
+   *                       Common private declarations                       *
+   ***************************************************************************/
+
+  void parseAdvertisement(uint8_t *payload, size_t total_len = 62);
+  void setPayload(uint8_t *payload, size_t total_len = 62, bool append = false);
+  void setAddress(BLEAddress address);
+  void setAdFlag(uint8_t adFlag);
+  void setAdvertizementResult(uint8_t *payload);
+  void setAppearance(uint16_t appearance);
+  void setManufacturerData(String manufacturerData);
+  void setName(String name);
+  void setRSSI(int rssi);
+  void setScan(BLEScan *pScan);
+  void setServiceData(String data);
+  void setServiceDataUUID(BLEUUID uuid);
+  void setServiceUUID(const char *serviceUUID);
+  void setServiceUUID(BLEUUID serviceUUID);
+  void setTXPower(int8_t txPower);
 };
 
 /**
@@ -123,30 +180,55 @@ class BLEAdvertisedDevice {
  */
 class BLEAdvertisedDeviceCallbacks {
 public:
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   virtual ~BLEAdvertisedDeviceCallbacks() {}
   /**
-	 * @brief Called when a new scan result is detected.
-	 *
-	 * As we are scanning, we will find new devices.  When found, this call back is invoked with a reference to the
-	 * device that was found.  During any individual scan, a device will only be detected one time.
-	 */
+   * @brief Called when a new scan result is detected.
+   *
+   * As we are scanning, we will find new devices.  When found, this call back is invoked with a reference to the
+   * device that was found.  During any individual scan, a device will only be detected one time.
+   */
   virtual void onResult(BLEAdvertisedDevice advertisedDevice) = 0;
 };
 
-#ifdef SOC_BLE_50_SUPPORTED
+#if defined(SOC_BLE_50_SUPPORTED) && defined(CONFIG_BLUEDROID_ENABLED)
 class BLEExtAdvertisingCallbacks {
 public:
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   virtual ~BLEExtAdvertisingCallbacks() {}
+
+  /***************************************************************************
+   *                      Bluedroid public declarations                      *
+   ***************************************************************************/
+
   /**
-	 * @brief Called when a new scan result is detected.
-	 *
-	 * As we are scanning, we will find new devices.  When found, this call back is invoked with a reference to the
-	 * device that was found.  During any individual scan, a device will only be detected one time.
-	 */
+   * @brief Called when a new scan result is detected.
+   *
+   * As we are scanning, we will find new devices.  When found, this call back is invoked with a reference to the
+   * device that was found.  During any individual scan, a device will only be detected one time.
+   */
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
   virtual void onResult(esp_ble_gap_ext_adv_report_t report) = 0;
+#endif
+
+  /***************************************************************************
+   *                      NimBLE public declarations                        *
+   ***************************************************************************/
+
+  // Extended advertising for NimBLE is not supported yet.
+#if defined(CONFIG_NIMBLE_ENABLED)
+  virtual void onResult(struct ble_gap_ext_disc_desc report) = 0;
+#endif
 };
-#endif  // SOC_BLE_50_SUPPORTED
+#endif  // SOC_BLE_50_SUPPORTED && CONFIG_BLUEDROID_ENABLED
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLEADVERTISEDDEVICE_H_ */
diff --git a/libraries/BLE/src/BLEAdvertising.cpp b/libraries/BLE/src/BLEAdvertising.cpp
index fe39a69c206..4e76873dcad 100644
--- a/libraries/BLE/src/BLEAdvertising.cpp
+++ b/libraries/BLE/src/BLEAdvertising.cpp
@@ -5,6 +5,10 @@
  *  Created on: Jun 21, 2017
  *      Author: kolban
  *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
+ *
  * The ESP-IDF provides a framework for BLE advertising.  It has determined that there are a common set
  * of properties that are advertised and has built a data structure that can be populated by the programmer.
  * This means that the programmer doesn't have to "mess with" the low level construction of a low level
@@ -16,46 +20,33 @@
  * set in the data will be advertised.
  *
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
 #include "BLEAdvertising.h"
 #include <esp_err.h>
 #include "BLEUtils.h"
+#include "BLEDevice.h"
 #include "GeneralUtils.h"
 #include "esp32-hal-log.h"
 
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
+
 /**
  * @brief Construct a default advertising object.
- *
  */
-BLEAdvertising::BLEAdvertising() : m_scanRespData{} {
-  m_advData.set_scan_rsp = false;
-  m_advData.include_name = true;
-  m_advData.include_txpower = true;
-  m_advData.min_interval = 0x20;
-  m_advData.max_interval = 0x40;
-  m_advData.appearance = 0x00;
-  m_advData.manufacturer_len = 0;
-  m_advData.p_manufacturer_data = nullptr;
-  m_advData.service_data_len = 0;
-  m_advData.p_service_data = nullptr;
-  m_advData.service_uuid_len = 0;
-  m_advData.p_service_uuid = nullptr;
-  m_advData.flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT);
-
-  m_advParams.adv_int_min = 0x20;
-  m_advParams.adv_int_max = 0x40;
-  m_advParams.adv_type = ADV_TYPE_IND;
-  m_advParams.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
-  m_advParams.channel_map = ADV_CHNL_ALL;
-  m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY;
-  m_advParams.peer_addr_type = BLE_ADDR_TYPE_PUBLIC;
-
-  m_customAdvData = false;           // No custom advertising data
-  m_customScanResponseData = false;  // No custom scan response data
+BLEAdvertising::BLEAdvertising() {
+  reset();
 }  // BLEAdvertising
 
 /**
@@ -64,6 +55,9 @@ BLEAdvertising::BLEAdvertising() : m_scanRespData{} {
  */
 void BLEAdvertising::addServiceUUID(BLEUUID serviceUUID) {
   m_serviceUUIDs.push_back(serviceUUID);
+#ifdef CONFIG_NIMBLE_ENABLED
+  m_advDataSet = false;
+#endif
 }  // addServiceUUID
 
 /**
@@ -72,6 +66,9 @@ void BLEAdvertising::addServiceUUID(BLEUUID serviceUUID) {
  */
 void BLEAdvertising::addServiceUUID(const char *serviceUUID) {
   addServiceUUID(BLEUUID(serviceUUID));
+#ifdef CONFIG_NIMBLE_ENABLED
+  m_advDataSet = false;
+#endif
 }  // addServiceUUID
 
 /**
@@ -87,6 +84,9 @@ bool BLEAdvertising::removeServiceUUID(int index) {
   }
 
   m_serviceUUIDs.erase(m_serviceUUIDs.begin() + index);
+#ifdef CONFIG_NIMBLE_ENABLED
+  m_advDataSet = false;
+#endif
   return true;
 }
 
@@ -120,34 +120,107 @@ bool BLEAdvertising::removeServiceUUID(const char *serviceUUID) {
  */
 void BLEAdvertising::setAppearance(uint16_t appearance) {
   m_advData.appearance = appearance;
+#ifdef CONFIG_NIMBLE_ENABLED
+  m_advData.appearance_is_present = 1;
+  m_advDataSet = false;
+#endif
 }  // setAppearance
 
-void BLEAdvertising::setAdvertisementType(esp_ble_adv_type_t adv_type) {
-  m_advParams.adv_type = adv_type;
-}  // setAdvertisementType
+void BLEAdvertising::setAdvertisementType(uint8_t adv_type) {
+#ifdef CONFIG_BLUEDROID_ENABLED
+  m_advParams.adv_type = (esp_ble_adv_type_t)adv_type;
+#endif
 
-void BLEAdvertising::setAdvertisementChannelMap(esp_ble_adv_channel_t channel_map) {
-  m_advParams.channel_map = channel_map;
-}  // setAdvertisementChannelMap
+#if defined(CONFIG_NIMBLE_ENABLED)
+  m_advParams.conn_mode = adv_type;
+#endif
+}  // setAdvertisementType
 
 void BLEAdvertising::setMinInterval(uint16_t mininterval) {
+#ifdef CONFIG_BLUEDROID_ENABLED
   m_advParams.adv_int_min = mininterval;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  m_advParams.itvl_min = mininterval;
+#endif
 }  // setMinInterval
 
 void BLEAdvertising::setMaxInterval(uint16_t maxinterval) {
+#ifdef CONFIG_BLUEDROID_ENABLED
   m_advParams.adv_int_max = maxinterval;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  m_advParams.itvl_max = maxinterval;
+#endif
 }  // setMaxInterval
 
 void BLEAdvertising::setMinPreferred(uint16_t mininterval) {
+#ifdef CONFIG_BLUEDROID_ENABLED
   m_advData.min_interval = mininterval;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  // invalid parameters, set the slave interval to null
+  if (mininterval < 0x0006 || mininterval > 0x0C80) {
+    m_advData.slave_itvl_range = nullptr;
+    return;
+  }
+
+  if (m_advData.slave_itvl_range == nullptr) {
+    m_advData.slave_itvl_range = m_slaveItvl;
+  }
+
+  m_slaveItvl[0] = mininterval;
+  m_slaveItvl[1] = mininterval >> 8;
+
+  uint16_t maxinterval = *(uint16_t *)(m_advData.slave_itvl_range + 2);
+
+  // If mininterval is higher than the maxinterval make them the same
+  if (mininterval > maxinterval) {
+    m_slaveItvl[2] = m_slaveItvl[0];
+    m_slaveItvl[3] = m_slaveItvl[1];
+  }
+
+  m_advDataSet = false;
+#endif
 }  //
 
 void BLEAdvertising::setMaxPreferred(uint16_t maxinterval) {
+#ifdef CONFIG_BLUEDROID_ENABLED
   m_advData.max_interval = maxinterval;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  // invalid parameters, set the slave interval to null
+  if (maxinterval < 0x0006 || maxinterval > 0x0C80) {
+    m_advData.slave_itvl_range = nullptr;
+    return;
+  }
+  if (m_advData.slave_itvl_range == nullptr) {
+    m_advData.slave_itvl_range = m_slaveItvl;
+  }
+  m_slaveItvl[2] = maxinterval;
+  m_slaveItvl[3] = maxinterval >> 8;
+
+  uint16_t mininterval = *(uint16_t *)(m_advData.slave_itvl_range);
+
+  // If mininterval is higher than the maxinterval make them the same
+  if (mininterval > maxinterval) {
+    m_slaveItvl[0] = m_slaveItvl[2];
+    m_slaveItvl[1] = m_slaveItvl[3];
+  }
+
+  m_advDataSet = false;
+#endif
 }  //
 
 void BLEAdvertising::setScanResponse(bool set) {
   m_scanResp = set;
+#ifdef CONFIG_NIMBLE_ENABLED
+  m_advDataSet = false;
+#endif
 }
 
 /**
@@ -158,22 +231,54 @@ void BLEAdvertising::setScanResponse(bool set) {
 void BLEAdvertising::setScanFilter(bool scanRequestWhitelistOnly, bool connectWhitelistOnly) {
   log_v(">> setScanFilter: scanRequestWhitelistOnly: %d, connectWhitelistOnly: %d", scanRequestWhitelistOnly, connectWhitelistOnly);
   if (!scanRequestWhitelistOnly && !connectWhitelistOnly) {
+
+#ifdef CONFIG_BLUEDROID_ENABLED
     m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+    m_advParams.filter_policy = BLE_HCI_ADV_FILT_NONE;
+#endif
+
     log_v("<< setScanFilter");
     return;
   }
   if (scanRequestWhitelistOnly && !connectWhitelistOnly) {
+
+#ifdef CONFIG_BLUEDROID_ENABLED
     m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+    m_advParams.filter_policy = BLE_HCI_ADV_FILT_SCAN;
+#endif
+
     log_v("<< setScanFilter");
     return;
   }
   if (!scanRequestWhitelistOnly && connectWhitelistOnly) {
+
+#ifdef CONFIG_BLUEDROID_ENABLED
     m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+    m_advParams.filter_policy = BLE_HCI_ADV_FILT_CONN;
+#endif
+
     log_v("<< setScanFilter");
     return;
   }
   if (scanRequestWhitelistOnly && connectWhitelistOnly) {
+
+#ifdef CONFIG_BLUEDROID_ENABLED
     m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+    m_advParams.filter_policy = BLE_HCI_ADV_FILT_BOTH;
+#endif
+
     log_v("<< setScanFilter");
     return;
   }
@@ -185,10 +290,21 @@ void BLEAdvertising::setScanFilter(bool scanRequestWhitelistOnly, bool connectWh
  */
 bool BLEAdvertising::setAdvertisementData(BLEAdvertisementData &advertisementData) {
   log_v(">> setAdvertisementData");
+
+#ifdef CONFIG_BLUEDROID_ENABLED
   esp_err_t errRc = ::esp_ble_gap_config_adv_data_raw((uint8_t *)advertisementData.getPayload().c_str(), advertisementData.getPayload().length());
   if (errRc != ESP_OK) {
     log_e("esp_ble_gap_config_adv_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc));
   }
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  esp_err_t errRc = ble_gap_adv_set_data((uint8_t *)advertisementData.getPayload().c_str(), advertisementData.getPayload().length());
+  if (errRc != ESP_OK) {
+    log_e("ble_gap_adv_set_data: %d %s", errRc, BLEUtils::returnCodeToString(errRc));
+  }
+#endif
+
   m_customAdvData = true;  // Set the flag that indicates we are using custom advertising data.
   log_v("<< setAdvertisementData");
   return ESP_OK == errRc;
@@ -200,127 +316,25 @@ bool BLEAdvertising::setAdvertisementData(BLEAdvertisementData &advertisementDat
  */
 bool BLEAdvertising::setScanResponseData(BLEAdvertisementData &advertisementData) {
   log_v(">> setScanResponseData");
+
+#ifdef CONFIG_BLUEDROID_ENABLED
   esp_err_t errRc = ::esp_ble_gap_config_scan_rsp_data_raw((uint8_t *)advertisementData.getPayload().c_str(), advertisementData.getPayload().length());
   if (errRc != ESP_OK) {
     log_e("esp_ble_gap_config_scan_rsp_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc));
   }
-  m_customScanResponseData = true;  // Set the flag that indicates we are using custom scan response data.
-  log_v("<< setScanResponseData");
-  return ESP_OK == errRc;
-}  // setScanResponseData
+#endif
 
-/**
- * @brief Start advertising.
- * Start advertising.
- * @return N/A.
- */
-bool BLEAdvertising::start() {
-  log_v(">> start: customAdvData: %d, customScanResponseData: %d", m_customAdvData, m_customScanResponseData);
-
-  // We have a vector of service UUIDs that we wish to advertise.  In order to use the
-  // ESP-IDF framework, these must be supplied in a contiguous array of their 128bit (16 byte)
-  // representations.  If we have 1 or more services to advertise then we allocate enough
-  // storage to host them and then copy them in one at a time into the contiguous storage.
-  int numServices = m_serviceUUIDs.size();
-  if (numServices > 0) {
-    m_advData.service_uuid_len = 16 * numServices;
-    m_advData.p_service_uuid = (uint8_t *)malloc(m_advData.service_uuid_len);
-    if (!m_advData.p_service_uuid) {
-      log_e(">> start failed: out of memory");
-      return false;
-    }
-
-    uint8_t *p = m_advData.p_service_uuid;
-    for (int i = 0; i < numServices; i++) {
-      log_d("- advertising service: %s", m_serviceUUIDs[i].toString().c_str());
-      BLEUUID serviceUUID128 = m_serviceUUIDs[i].to128();
-      memcpy(p, serviceUUID128.getNative()->uuid.uuid128, 16);
-      p += 16;
-    }
-  } else {
-    m_advData.service_uuid_len = 0;
-    log_d("- no services advertised");
-  }
-
-  esp_err_t errRc;
-
-  if (!m_customAdvData) {
-    // Set the configuration for advertising.
-    m_advData.set_scan_rsp = false;
-    m_advData.include_name = !m_scanResp;
-    m_advData.include_txpower = !m_scanResp;
-    errRc = ::esp_ble_gap_config_adv_data(&m_advData);
-    if (errRc != ESP_OK) {
-      log_e("<< esp_ble_gap_config_adv_data: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-      return false;
-    }
-  }
-
-  if (!m_customScanResponseData && m_scanResp) {
-    // Set the configuration for scan response.
-    memcpy(&m_scanRespData, &m_advData, sizeof(esp_ble_adv_data_t));  // Copy the content of m_advData.
-    m_scanRespData.set_scan_rsp = true;                               // Define this struct as scan response data
-    m_scanRespData.include_name = true;                               // Caution: This may lead to a crash if the device name has more than 29 characters
-    m_scanRespData.include_txpower = true;
-    m_scanRespData.appearance = 0;  // If defined the 'Appearance' attribute is already included in the advertising data
-    m_scanRespData.flag = 0;        // 'Flags' attribute should no be included in the scan response
-
-    errRc = ::esp_ble_gap_config_adv_data(&m_scanRespData);
-    if (errRc != ESP_OK) {
-      log_e("<< esp_ble_gap_config_adv_data (Scan response): rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-      return false;
-    }
-  }
-
-  // If we had services to advertise then we previously allocated some storage for them.
-  // Here we release that storage.
-  free(m_advData.p_service_uuid);  //TODO change this variable to local scope?
-  m_advData.p_service_uuid = nullptr;
-
-  // Start advertising.
-  errRc = ::esp_ble_gap_start_advertising(&m_advParams);
+#if defined(CONFIG_NIMBLE_ENABLED)
+  esp_err_t errRc = ble_gap_adv_rsp_set_data((uint8_t *)advertisementData.getPayload().c_str(), advertisementData.getPayload().length());
   if (errRc != ESP_OK) {
-    log_e("<< esp_ble_gap_start_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-  } else {
-    log_v("<< start");
+    log_e("ble_gap_adv_rsp_set_data: %d %s", errRc, BLEUtils::returnCodeToString(errRc));
   }
-  return ESP_OK == errRc;
-}  // start
-
-/**
- * @brief Stop advertising.
- * Stop advertising.
- * @return N/A.
- */
-bool BLEAdvertising::stop() {
-  log_v(">> stop");
-  esp_err_t errRc = ::esp_ble_gap_stop_advertising();
-  if (errRc != ESP_OK) {
-    log_e("esp_ble_gap_stop_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-  } else {
-    log_v("<< stop");
-  }
-  return ESP_OK == errRc;
-}  // stop
-
-/**
- * @brief Set BLE address.
- * @param [in] Bluetooth address.
- * @param [in] Bluetooth address type.
- * Set BLE address.
- */
-bool BLEAdvertising::setDeviceAddress(esp_bd_addr_t addr, esp_ble_addr_type_t type) {
-  log_v(">> setPrivateAddress");
+#endif
 
-  m_advParams.own_addr_type = type;
-  esp_err_t errRc = esp_ble_gap_set_rand_addr((uint8_t *)addr);
-  if (errRc != ESP_OK) {
-    log_e("esp_ble_gap_set_rand_addr: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-  } else {
-    log_v("<< setPrivateAddress");
-  }
+  m_customScanResponseData = true;  // Set the flag that indicates we are using custom scan response data.
+  log_v("<< setScanResponseData");
   return ESP_OK == errRc;
-}  // setPrivateAddress
+}  // setScanResponseData
 
 /**
  * @brief Add data to the payload to be advertised.
@@ -333,6 +347,13 @@ void BLEAdvertisementData::addData(String data) {
   m_payload.concat(data);
 }  // addData
 
+void BLEAdvertisementData::addData(char *data, size_t length) {
+  if ((m_payload.length() + length) > ESP_BLE_ADV_DATA_LEN_MAX) {
+    return;
+  }
+  m_payload.concat(String(data, length));
+}  // addData
+
 /**
  * @brief Set the appearance.
  * @param [in] appearance The appearance code value.
@@ -359,7 +380,12 @@ void BLEAdvertisementData::setCompleteServices(BLEUUID uuid) {
       // [Len] [0x03] [LL] [HH]
       cdata[0] = 3;
       cdata[1] = ESP_BLE_AD_TYPE_16SRV_CMPL;  // 0x03
+#if defined(CONFIG_BLUEDROID_ENABLED)
       addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid16, 2));
+#endif
+#if defined(CONFIG_NIMBLE_ENABLED)
+      addData(String(cdata, 2) + String((char *)&uuid.getNative()->u16.value, 2));
+#endif
       break;
     }
 
@@ -368,7 +394,12 @@ void BLEAdvertisementData::setCompleteServices(BLEUUID uuid) {
       // [Len] [0x05] [LL] [LL] [HH] [HH]
       cdata[0] = 5;
       cdata[1] = ESP_BLE_AD_TYPE_32SRV_CMPL;  // 0x05
+#if defined(CONFIG_BLUEDROID_ENABLED)
       addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid32, 4));
+#endif
+#if defined(CONFIG_NIMBLE_ENABLED)
+      addData(String(cdata, 2) + String((char *)&uuid.getNative()->u32.value, 4));
+#endif
       break;
     }
 
@@ -377,7 +408,12 @@ void BLEAdvertisementData::setCompleteServices(BLEUUID uuid) {
       // [Len] [0x07] [0] [1] ... [15]
       cdata[0] = 17;
       cdata[1] = ESP_BLE_AD_TYPE_128SRV_CMPL;  // 0x07
+#if defined(CONFIG_BLUEDROID_ENABLED)
       addData(String(cdata, 2) + String((char *)uuid.getNative()->uuid.uuid128, 16));
+#endif
+#if defined(CONFIG_NIMBLE_ENABLED)
+      addData(String(cdata, 2) + String((char *)uuid.getNative()->u128.value, 16));
+#endif
       break;
     }
 
@@ -442,7 +478,12 @@ void BLEAdvertisementData::setPartialServices(BLEUUID uuid) {
       // [Len] [0x02] [LL] [HH]
       cdata[0] = 3;
       cdata[1] = ESP_BLE_AD_TYPE_16SRV_PART;  // 0x02
+#if defined(CONFIG_BLUEDROID_ENABLED)
       addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid16, 2));
+#endif
+#if defined(CONFIG_NIMBLE_ENABLED)
+      addData(String(cdata, 2) + String((char *)&uuid.getNative()->u16.value, 2));
+#endif
       break;
     }
 
@@ -451,7 +492,12 @@ void BLEAdvertisementData::setPartialServices(BLEUUID uuid) {
       // [Len] [0x04] [LL] [LL] [HH] [HH]
       cdata[0] = 5;
       cdata[1] = ESP_BLE_AD_TYPE_32SRV_PART;  // 0x04
+#if defined(CONFIG_BLUEDROID_ENABLED)
       addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid32, 4));
+#endif
+#if defined(CONFIG_NIMBLE_ENABLED)
+      addData(String(cdata, 2) + String((char *)&uuid.getNative()->u32.value, 4));
+#endif
       break;
     }
 
@@ -460,7 +506,12 @@ void BLEAdvertisementData::setPartialServices(BLEUUID uuid) {
       // [Len] [0x06] [0] [1] ... [15]
       cdata[0] = 17;
       cdata[1] = ESP_BLE_AD_TYPE_128SRV_PART;  // 0x06
+#if defined(CONFIG_BLUEDROID_ENABLED)
       addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid128, 16));
+#endif
+#if defined(CONFIG_NIMBLE_ENABLED)
+      addData(String(cdata, 2) + String((char *)&uuid.getNative()->u128.value, 16));
+#endif
       break;
     }
 
@@ -481,7 +532,12 @@ void BLEAdvertisementData::setServiceData(BLEUUID uuid, String data) {
       // [Len] [0x16] [UUID16] data
       cdata[0] = data.length() + 3;
       cdata[1] = ESP_BLE_AD_TYPE_SERVICE_DATA;  // 0x16
+#if defined(CONFIG_BLUEDROID_ENABLED)
       addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid16, 2) + data);
+#endif
+#if defined(CONFIG_NIMBLE_ENABLED)
+      addData(String(cdata, 2) + String((char *)&uuid.getNative()->u16.value, 2) + data);
+#endif
       break;
     }
 
@@ -490,7 +546,12 @@ void BLEAdvertisementData::setServiceData(BLEUUID uuid, String data) {
       // [Len] [0x20] [UUID32] data
       cdata[0] = data.length() + 5;
       cdata[1] = ESP_BLE_AD_TYPE_32SERVICE_DATA;  // 0x20
+#if defined(CONFIG_BLUEDROID_ENABLED)
       addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid32, 4) + data);
+#endif
+#if defined(CONFIG_NIMBLE_ENABLED)
+      addData(String(cdata, 2) + String((char *)&uuid.getNative()->u32.value, 4) + data);
+#endif
       break;
     }
 
@@ -499,7 +560,12 @@ void BLEAdvertisementData::setServiceData(BLEUUID uuid, String data) {
       // [Len] [0x21] [UUID128] data
       cdata[0] = data.length() + 17;
       cdata[1] = ESP_BLE_AD_TYPE_128SERVICE_DATA;  // 0x21
+#if defined(CONFIG_BLUEDROID_ENABLED)
       addData(String(cdata, 2) + String((char *)&uuid.getNative()->uuid.uuid128, 16) + data);
+#endif
+#if defined(CONFIG_NIMBLE_ENABLED)
+      addData(String(cdata, 2) + String((char *)&uuid.getNative()->u128.value, 16) + data);
+#endif
       break;
     }
 
@@ -520,6 +586,33 @@ void BLEAdvertisementData::setShortName(String name) {
   log_d("BLEAdvertisementData", "<< setShortName");
 }  // setShortName
 
+/**
+ * @brief Adds Tx power level to the advertisement data.
+ */
+void BLEAdvertisementData::addTxPower() {
+  char cdata[3];
+  cdata[0] = 2;  // length
+  cdata[1] = ESP_BLE_AD_TYPE_TX_PWR;
+  cdata[2] = BLEDevice::getPower();
+  addData(cdata, 3);
+}  // addTxPower
+
+/**
+ * @brief Set the preferred connection interval parameters.
+ * @param [in] min The minimum interval desired.
+ * @param [in] max The maximum interval desired.
+ */
+void BLEAdvertisementData::setPreferredParams(uint16_t min, uint16_t max) {
+  char cdata[6];
+  cdata[0] = 5;  // length
+  cdata[1] = ESP_BLE_AD_TYPE_INT_RANGE;
+  cdata[2] = min;
+  cdata[3] = min >> 8;
+  cdata[4] = max;
+  cdata[5] = max >> 8;
+  addData(cdata, 6);
+}  // setPreferredParams
+
 /**
  * @brief Retrieve the payload that is to be advertised.
  * @return The payload that is to be advertised.
@@ -528,8 +621,146 @@ String BLEAdvertisementData::getPayload() {
   return m_payload;
 }  // getPayload
 
-void BLEAdvertising::handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
+/***************************************************************************
+ *                           Bluedroid functions                           *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+
+void BLEAdvertising::reset() {
+  if (BLEDevice::getInitialized()) {
+    stop();
+  }
+
+  memset(&m_scanRespData, 0, sizeof(esp_ble_adv_data_t));
+  memset(&m_advData, 0, sizeof(esp_ble_adv_data_t));
+  memset(&m_advParams, 0, sizeof(esp_ble_adv_params_t));
+
+  m_advData.set_scan_rsp = false;
+  m_advData.include_name = true;
+  m_advData.include_txpower = true;
+  m_advData.min_interval = 0x20;
+  m_advData.max_interval = 0x40;
+  m_advData.appearance = 0x00;
+  m_advData.manufacturer_len = 0;
+  m_advData.p_manufacturer_data = nullptr;
+  m_advData.service_data_len = 0;
+  m_advData.p_service_data = nullptr;
+  m_advData.service_uuid_len = 0;
+  m_advData.p_service_uuid = nullptr;
+  m_advData.flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT);
+
+  m_advParams.adv_int_min = 0x20;
+  m_advParams.adv_int_max = 0x40;
+  m_advParams.adv_type = ADV_TYPE_IND;
+  m_advParams.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
+  m_advParams.channel_map = ADV_CHNL_ALL;
+  m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY;
+  m_advParams.peer_addr_type = BLE_ADDR_TYPE_PUBLIC;
 
+  m_customAdvData = false;           // No custom advertising data
+  m_customScanResponseData = false;  // No custom scan response data
+}  // BLEAdvertising
+
+void BLEAdvertising::setAdvertisementChannelMap(esp_ble_adv_channel_t channel_map) {
+  m_advParams.channel_map = channel_map;
+}  // setAdvertisementChannelMap
+
+/**
+ * @brief Start advertising.
+ * Start advertising.
+ * @return N/A.
+ */
+bool BLEAdvertising::start() {
+  log_v(">> start: customAdvData: %d, customScanResponseData: %d", m_customAdvData, m_customScanResponseData);
+
+  // We have a vector of service UUIDs that we wish to advertise.  In order to use the
+  // ESP-IDF framework, these must be supplied in a contiguous array of their 128bit (16 byte)
+  // representations.  If we have 1 or more services to advertise then we allocate enough
+  // storage to host them and then copy them in one at a time into the contiguous storage.
+  int numServices = m_serviceUUIDs.size();
+  if (numServices > 0) {
+    m_advData.service_uuid_len = 16 * numServices;
+    m_advData.p_service_uuid = (uint8_t *)malloc(m_advData.service_uuid_len);
+    if (!m_advData.p_service_uuid) {
+      log_e(">> start failed: out of memory");
+      return false;
+    }
+
+    uint8_t *p = m_advData.p_service_uuid;
+    for (int i = 0; i < numServices; i++) {
+      log_d("- advertising service: %s", m_serviceUUIDs[i].toString().c_str());
+      BLEUUID serviceUUID128 = m_serviceUUIDs[i].to128();
+      memcpy(p, serviceUUID128.getNative()->uuid.uuid128, 16);
+      p += 16;
+    }
+  } else {
+    m_advData.service_uuid_len = 0;
+    log_d("- no services advertised");
+  }
+
+  esp_err_t errRc;
+
+  if (!m_customAdvData) {
+    // Set the configuration for advertising.
+    m_advData.set_scan_rsp = false;
+    m_advData.include_name = !m_scanResp;
+    m_advData.include_txpower = !m_scanResp;
+    errRc = ::esp_ble_gap_config_adv_data(&m_advData);
+    if (errRc != ESP_OK) {
+      log_e("<< esp_ble_gap_config_adv_data: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+      return false;
+    }
+  }
+
+  if (!m_customScanResponseData && m_scanResp) {
+    // Set the configuration for scan response.
+    memcpy(&m_scanRespData, &m_advData, sizeof(esp_ble_adv_data_t));  // Copy the content of m_advData.
+    m_scanRespData.set_scan_rsp = true;                               // Define this struct as scan response data
+    m_scanRespData.include_name = true;                               // Caution: This may lead to a crash if the device name has more than 29 characters
+    m_scanRespData.include_txpower = true;
+    m_scanRespData.appearance = 0;  // If defined the 'Appearance' attribute is already included in the advertising data
+    m_scanRespData.flag = 0;        // 'Flags' attribute should no be included in the scan response
+
+    errRc = ::esp_ble_gap_config_adv_data(&m_scanRespData);
+    if (errRc != ESP_OK) {
+      log_e("<< esp_ble_gap_config_adv_data (Scan response): rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+      return false;
+    }
+  }
+
+  // If we had services to advertise then we previously allocated some storage for them.
+  // Here we release that storage.
+  free(m_advData.p_service_uuid);  //TODO change this variable to local scope?
+  m_advData.p_service_uuid = nullptr;
+
+  // Start advertising.
+  errRc = ::esp_ble_gap_start_advertising(&m_advParams);
+  if (errRc != ESP_OK) {
+    log_e("<< esp_ble_gap_start_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+  } else {
+    log_v("<< start");
+  }
+  return ESP_OK == errRc;
+}  // start
+
+/**
+ * @brief Stop advertising.
+ * Stop advertising.
+ * @return N/A.
+ */
+bool BLEAdvertising::stop() {
+  log_v(">> stop");
+  esp_err_t errRc = ::esp_ble_gap_stop_advertising();
+  if (errRc != ESP_OK) {
+    log_e("esp_ble_gap_stop_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+  } else {
+    log_v("<< stop");
+  }
+  return ESP_OK == errRc;
+}  // stop
+
+void BLEAdvertising::handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
   log_d("handleGAPEvent [event no: %d]", (int)event);
 
   switch (event) {
@@ -558,7 +789,26 @@ void BLEAdvertising::handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb
   }
 }
 
-#ifdef SOC_BLE_50_SUPPORTED
+/**
+ * @brief Set BLE address.
+ * @param [in] Bluetooth address.
+ * @param [in] Bluetooth address type.
+ * Set BLE address.
+ */
+bool BLEAdvertising::setDeviceAddress(esp_bd_addr_t addr, esp_ble_addr_type_t type) {
+  log_v(">> setPrivateAddress");
+
+  m_advParams.own_addr_type = type;
+  esp_err_t errRc = esp_ble_gap_set_rand_addr((uint8_t *)addr);
+  if (errRc != ESP_OK) {
+    log_e("esp_ble_gap_set_rand_addr: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+  } else {
+    log_v("<< setPrivateAddress");
+  }
+  return ESP_OK == errRc;
+}  // setPrivateAddress
+
+#if defined(SOC_BLE_50_SUPPORTED)
 
 /**
 * @brief           Creator
@@ -803,7 +1053,376 @@ void BLEMultiAdvertising::setDuration(uint8_t instance, int duration, int max_ev
   ext_adv[instance] = {instance, duration, max_events};
 }
 
-#endif  // SOC_BLE_50_SUPPORTED
+#endif /* SOC_BLE_50_SUPPORTED */
 
 #endif /* CONFIG_BLUEDROID_ENABLED */
+
+/***************************************************************************
+ *                           NimBLE functions                              *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
+void BLEAdvertising::reset() {
+  if (BLEDevice::getInitialized() && isAdvertising()) {
+    stop();
+  }
+  memset(&m_advData, 0, sizeof m_advData);
+  memset(&m_scanData, 0, sizeof m_scanData);
+  memset(&m_advParams, 0, sizeof m_advParams);
+  memset(&m_slaveItvl, 0, sizeof m_slaveItvl);
+  const char *name = ble_svc_gap_device_name();
+
+  m_advData.name = (uint8_t *)name;
+  m_advData.name_len = strlen(name);
+  m_advData.name_is_complete = 1;
+  m_advData.tx_pwr_lvl = BLEDevice::getPower();
+  m_advData.flags = (BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP);
+  m_advParams.conn_mode = BLE_GAP_CONN_MODE_UND;
+  m_advParams.disc_mode = BLE_GAP_DISC_MODE_GEN;
+  m_customAdvData = false;
+  m_customScanResponseData = false;
+  m_scanResp = true;
+  m_advDataSet = false;
+  // Set this to non-zero to prevent auto start if host reset before started by app.
+  m_duration = BLE_HS_FOREVER;
+  m_advCompCB = nullptr;
+}  // BLEAdvertising
+
+void BLEAdvertising::setName(String name) {
+  m_name = name;
+  m_advData.name = (uint8_t *)m_name.c_str();
+  m_advData.name_len = m_name.length();
+  m_advDataSet = false;
+}
+
+/**
+ * @brief Add the transmission power level to the advertisement packet.
+ */
+void BLEAdvertising::addTxPower() {
+  m_advData.tx_pwr_lvl_is_present = 1;
+  m_advDataSet = false;
+}  // addTxPower
+
+/**
+ * @brief Handles the callback when advertising stops.
+ */
+void BLEAdvertising::advCompleteCB() {
+  if (m_advCompCB != nullptr) {
+    m_advCompCB(this);
+  }
+}  // advCompleteCB
+
+/**
+ * @brief Check if currently advertising.
+ * @return true if advertising is active.
+ */
+bool BLEAdvertising::isAdvertising() {
+  return ble_gap_adv_active();
+}  // isAdvertising
+
+/*
+ * Host reset seems to clear advertising data,
+ * we need clear the flag so it reloads it.
+ */
+void BLEAdvertising::onHostSync() {
+  log_v("Host re-synced");
+
+  m_advDataSet = false;
+  // If we were advertising forever, restart it now
+  if (m_duration == 0) {
+    start(m_duration, m_advCompCB);
+  } else {
+    // Otherwise we should tell the app that advertising stopped.
+    advCompleteCB();
+  }
+}  // onHostSync
+
+/**
+ * @brief Handler for gap events when not using peripheral role.
+ * @param [in] event the event data.
+ * @param [in] arg pointer to the advertising instance.
+ */
+int BLEAdvertising::handleGAPEvent(struct ble_gap_event *event, void *arg) {
+  BLEAdvertising *pAdv = (BLEAdvertising *)arg;
+
+  if (event->type == BLE_GAP_EVENT_ADV_COMPLETE) {
+    switch (event->adv_complete.reason) {
+      // Don't call the callback if host reset, we want to
+      // preserve the active flag until re-sync to restart advertising.
+      case BLE_HS_ETIMEOUT_HCI:
+      case BLE_HS_EOS:
+      case BLE_HS_ECONTROLLER:
+      case BLE_HS_ENOTSYNCED:
+        log_e("host reset, rc=%d", event->adv_complete.reason);
+        BLEDevice::onReset(event->adv_complete.reason);
+        return 0;
+      default: break;
+    }
+    pAdv->advCompleteCB();
+  }
+  return 0;
+}
+
+/**
+ * @brief Start advertising.
+ * @param [in] duration The duration, in seconds, to advertise, 0 == advertise forever.
+ * @param [in] advCompleteCB A pointer to a callback to be invoked when advertising ends.
+ * @return True if advertising started successfully.
+ */
+bool BLEAdvertising::start(uint32_t duration, void (*advCompleteCB)(BLEAdvertising *pAdv)) {
+  log_v(">> Advertising start: customAdvData: %d, customScanResponseData: %d", m_customAdvData, m_customScanResponseData);
+
+  // If Host is not synced we cannot start advertising.
+  if (!BLEDevice::m_synced) {
+    log_e("Host reset, wait for sync.");
+    return false;
+  }
+
+  // If already advertising just return
+  if (ble_gap_adv_active()) {
+    log_w("Advertising already active");
+    return true;
+  }
+
+  BLEServer *pServer = BLEDevice::getServer();
+  if (pServer != nullptr) {
+    if (!pServer->m_gattsStarted) {
+      pServer->start();
+    } else if (pServer->getConnectedCount() >= CONFIG_BT_NIMBLE_MAX_CONNECTIONS) {
+      log_e("Max connections reached - not advertising");
+      return false;
+    }
+  }
+
+  // Save the duration in case of host reset so we can restart with the same parameters
+  m_duration = duration;
+
+  if (duration == 0) {
+    duration = BLE_HS_FOREVER;
+  } else {
+    duration = duration * 1000;  // convert duration to milliseconds
+  }
+
+  m_advCompCB = advCompleteCB;
+
+  m_advParams.disc_mode = BLE_GAP_DISC_MODE_GEN;
+  m_advData.flags = (BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP);
+  if (m_advParams.conn_mode == BLE_GAP_CONN_MODE_NON) {
+    if (!m_scanResp) {
+      m_advParams.disc_mode = BLE_GAP_DISC_MODE_NON;
+      m_advData.flags = BLE_HS_ADV_F_BREDR_UNSUP;
+    }
+  }
+
+  int rc = 0;
+
+  if (!m_customAdvData && !m_advDataSet) {
+    //start with 3 bytes for the flags data
+    uint8_t payloadLen = (2 + 1);
+    if (m_advData.mfg_data_len > 0) {
+      payloadLen += (2 + m_advData.mfg_data_len);
+    }
+
+    if (m_advData.svc_data_uuid16_len > 0) {
+      payloadLen += (2 + m_advData.svc_data_uuid16_len);
+    }
+
+    if (m_advData.svc_data_uuid32_len > 0) {
+      payloadLen += (2 + m_advData.svc_data_uuid32_len);
+    }
+
+    if (m_advData.svc_data_uuid128_len > 0) {
+      payloadLen += (2 + m_advData.svc_data_uuid128_len);
+    }
+
+    if (m_advData.uri_len > 0) {
+      payloadLen += (2 + m_advData.uri_len);
+    }
+
+    if (m_advData.appearance_is_present) {
+      payloadLen += (2 + BLE_HS_ADV_APPEARANCE_LEN);
+    }
+
+    if (m_advData.tx_pwr_lvl_is_present) {
+      payloadLen += (2 + BLE_HS_ADV_TX_PWR_LVL_LEN);
+    }
+
+    if (m_advData.slave_itvl_range != nullptr) {
+      payloadLen += (2 + BLE_HS_ADV_SLAVE_ITVL_RANGE_LEN);
+    }
+
+    for (auto &it : m_serviceUUIDs) {
+      if (it.getNative()->u.type == BLE_UUID_TYPE_16) {
+        int add = (m_advData.num_uuids16 > 0) ? 2 : 4;
+        if ((payloadLen + add) > BLE_HS_ADV_MAX_SZ) {
+          m_advData.uuids16_is_complete = 0;
+          continue;
+        }
+        payloadLen += add;
+
+        if (nullptr == (m_advData.uuids16 = (ble_uuid16_t *)realloc((void *)m_advData.uuids16, (m_advData.num_uuids16 + 1) * sizeof(ble_uuid16_t)))) {
+          log_e("Error, no mem");
+          abort();
+        }
+        memcpy((void *)&m_advData.uuids16[m_advData.num_uuids16], &it.getNative()->u16, sizeof(ble_uuid16_t));
+        m_advData.uuids16_is_complete = 1;
+        m_advData.num_uuids16++;
+      }
+      if (it.getNative()->u.type == BLE_UUID_TYPE_32) {
+        int add = (m_advData.num_uuids32 > 0) ? 4 : 6;
+        if ((payloadLen + add) > BLE_HS_ADV_MAX_SZ) {
+          m_advData.uuids32_is_complete = 0;
+          continue;
+        }
+        payloadLen += add;
+
+        if (nullptr == (m_advData.uuids32 = (ble_uuid32_t *)realloc((void *)m_advData.uuids32, (m_advData.num_uuids32 + 1) * sizeof(ble_uuid32_t)))) {
+          log_e("Error, no mem");
+          abort();
+        }
+        memcpy((void *)&m_advData.uuids32[m_advData.num_uuids32], &it.getNative()->u32, sizeof(ble_uuid32_t));
+        m_advData.uuids32_is_complete = 1;
+        m_advData.num_uuids32++;
+      }
+      if (it.getNative()->u.type == BLE_UUID_TYPE_128) {
+        int add = (m_advData.num_uuids128 > 0) ? 16 : 18;
+        if ((payloadLen + add) > BLE_HS_ADV_MAX_SZ) {
+          m_advData.uuids128_is_complete = 0;
+          continue;
+        }
+        payloadLen += add;
+
+        if (nullptr == (m_advData.uuids128 = (ble_uuid128_t *)realloc((void *)m_advData.uuids128, (m_advData.num_uuids128 + 1) * sizeof(ble_uuid128_t)))) {
+          log_e("Error, no mem");
+          abort();
+        }
+        memcpy((void *)&m_advData.uuids128[m_advData.num_uuids128], &it.getNative()->u128, sizeof(ble_uuid128_t));
+        m_advData.uuids128_is_complete = 1;
+        m_advData.num_uuids128++;
+      }
+    }
+
+    // check if there is room for the name, if not put it in scan data
+    if ((payloadLen + (2 + m_advData.name_len)) > BLE_HS_ADV_MAX_SZ) {
+      if (m_scanResp && !m_customScanResponseData) {
+        m_scanData.name = m_advData.name;
+        m_scanData.name_len = m_advData.name_len;
+        if (m_scanData.name_len > BLE_HS_ADV_MAX_SZ - 2) {
+          m_scanData.name_len = BLE_HS_ADV_MAX_SZ - 2;
+          m_scanData.name_is_complete = 0;
+        } else {
+          m_scanData.name_is_complete = 1;
+        }
+        m_advData.name = nullptr;
+        m_advData.name_len = 0;
+        m_advData.name_is_complete = 0;
+      } else {
+        if (m_advData.tx_pwr_lvl_is_present) {
+          m_advData.tx_pwr_lvl_is_present = 0;
+          payloadLen -= (2 + 1);
+        }
+        // if not using scan response just cut the name down
+        // leaving 2 bytes for the data specifier.
+        if (m_advData.name_len > (BLE_HS_ADV_MAX_SZ - payloadLen - 2)) {
+          m_advData.name_len = (BLE_HS_ADV_MAX_SZ - payloadLen - 2);
+          m_advData.name_is_complete = 0;
+        }
+      }
+    }
+
+    if (m_scanResp && !m_customScanResponseData) {
+      rc = ble_gap_adv_rsp_set_fields(&m_scanData);
+      switch (rc) {
+        case 0: break;
+
+        case BLE_HS_EBUSY: log_e("Already advertising"); break;
+
+        case BLE_HS_EMSGSIZE: log_e("Scan data too long"); break;
+
+        default: log_e("Error setting scan response data; rc=%d, %s", rc, BLEUtils::returnCodeToString(rc)); break;
+      }
+    }
+
+    if (rc == 0) {
+      rc = ble_gap_adv_set_fields(&m_advData);
+      switch (rc) {
+        case 0: break;
+
+        case BLE_HS_EBUSY: log_e("Already advertising"); break;
+
+        case BLE_HS_EMSGSIZE: log_e("Advertisement data too long"); break;
+
+        default: log_e("Error setting advertisement data; rc=%d, %s", rc, BLEUtils::returnCodeToString(rc)); break;
+      }
+    }
+
+    if (m_advData.num_uuids128 > 0) {
+      free((void *)m_advData.uuids128);
+      m_advData.uuids128 = nullptr;
+      m_advData.num_uuids128 = 0;
+    }
+
+    if (m_advData.num_uuids32 > 0) {
+      free((void *)m_advData.uuids32);
+      m_advData.uuids32 = nullptr;
+      m_advData.num_uuids32 = 0;
+    }
+
+    if (m_advData.num_uuids16 > 0) {
+      free((void *)m_advData.uuids16);
+      m_advData.uuids16 = nullptr;
+      m_advData.num_uuids16 = 0;
+    }
+
+    if (rc != 0) {
+      return false;
+    }
+
+    m_advDataSet = true;
+  }
+
+  rc = ble_gap_adv_start(
+    BLEDevice::m_ownAddrType, NULL, duration, &m_advParams, (pServer != nullptr) ? BLEServer::handleGATTServerEvent : BLEAdvertising::handleGAPEvent,
+    (pServer != nullptr) ? (void *)pServer : (void *)this
+  );
+
+  switch (rc) {
+    case 0: break;
+
+    case BLE_HS_EINVAL: log_e("Unable to advertise - Duration too long"); break;
+
+    case BLE_HS_EPREEMPTED: log_e("Unable to advertise - busy"); break;
+
+    case BLE_HS_ETIMEOUT_HCI:
+    case BLE_HS_EOS:
+    case BLE_HS_ECONTROLLER:
+    case BLE_HS_ENOTSYNCED:   log_e("Unable to advertise - Host Reset"); break;
+
+    default: log_e("Error enabling advertising; rc=%d, %s", rc, BLEUtils::returnCodeToString(rc)); break;
+  }
+
+  log_d("<< Advertising start");
+  return (rc == 0);
+}  // start
+
+/**
+ * @brief Stop advertising.
+ */
+bool BLEAdvertising::stop() {
+  log_d(">> stop");
+
+  int rc = ble_gap_adv_stop();
+  if (rc != 0 && rc != BLE_HS_EALREADY) {
+    log_e("ble_gap_adv_stop rc=%d %s", rc, BLEUtils::returnCodeToString(rc));
+    return false;
+  }
+
+  log_d("<< stop");
+  return true;
+}  // stop
+
+#endif /* CONFIG_NIMBLE_ENABLED */
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEAdvertising.h b/libraries/BLE/src/BLEAdvertising.h
index 1e573ac814f..cf68768ec91 100644
--- a/libraries/BLE/src/BLEAdvertising.h
+++ b/libraries/BLE/src/BLEAdvertising.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Jun 21, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLEADVERTISING_H_
@@ -11,20 +15,97 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
-#include <esp_gap_ble_api.h>
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
 #include "BLEUUID.h"
 #include <vector>
 #include "RTOS.h"
+#include "BLEUtils.h"
+
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gap_ble_api.h>
+#endif
+
+/***************************************************************************
+ *                      NimBLE includes and definitions                    *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_gap.h>
+#include <services/gap/ble_svc_gap.h>
+#include <host/ble_hs_adv.h>
+
+#define ESP_BLE_ADV_DATA_LEN_MAX            BLE_HS_ADV_MAX_SZ
+#define ESP_BLE_ADV_FLAG_LIMIT_DISC         (0x01 << 0)
+#define ESP_BLE_ADV_FLAG_GEN_DISC           (0x01 << 1)
+#define ESP_BLE_ADV_FLAG_BREDR_NOT_SPT      (0x01 << 2)
+#define ESP_BLE_ADV_FLAG_DMT_CONTROLLER_SPT (0x01 << 3)
+#define ESP_BLE_ADV_FLAG_DMT_HOST_SPT       (0x01 << 4)
+#define ESP_BLE_ADV_FLAG_NON_LIMIT_DISC     (0x00)
+#endif /* CONFIG_NIMBLE_ENABLED */
+
+/***************************************************************************
+ *                             NimBLE types                                *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+typedef enum {
+  ESP_BLE_AD_TYPE_FLAG = 0x01,
+  ESP_BLE_AD_TYPE_16SRV_PART = 0x02,
+  ESP_BLE_AD_TYPE_16SRV_CMPL = 0x03,
+  ESP_BLE_AD_TYPE_32SRV_PART = 0x04,
+  ESP_BLE_AD_TYPE_32SRV_CMPL = 0x05,
+  ESP_BLE_AD_TYPE_128SRV_PART = 0x06,
+  ESP_BLE_AD_TYPE_128SRV_CMPL = 0x07,
+  ESP_BLE_AD_TYPE_NAME_SHORT = 0x08,
+  ESP_BLE_AD_TYPE_NAME_CMPL = 0x09,
+  ESP_BLE_AD_TYPE_TX_PWR = 0x0A,
+  ESP_BLE_AD_TYPE_DEV_CLASS = 0x0D,
+  ESP_BLE_AD_TYPE_SM_TK = 0x10,
+  ESP_BLE_AD_TYPE_SM_OOB_FLAG = 0x11,
+  ESP_BLE_AD_TYPE_INT_RANGE = 0x12,
+  ESP_BLE_AD_TYPE_SOL_SRV_UUID = 0x14,
+  ESP_BLE_AD_TYPE_128SOL_SRV_UUID = 0x15,
+  ESP_BLE_AD_TYPE_SERVICE_DATA = 0x16,
+  ESP_BLE_AD_TYPE_PUBLIC_TARGET = 0x17,
+  ESP_BLE_AD_TYPE_RANDOM_TARGET = 0x18,
+  ESP_BLE_AD_TYPE_APPEARANCE = 0x19,
+  ESP_BLE_AD_TYPE_ADV_INT = 0x1A,
+  ESP_BLE_AD_TYPE_LE_DEV_ADDR = 0x1b,
+  ESP_BLE_AD_TYPE_LE_ROLE = 0x1c,
+  ESP_BLE_AD_TYPE_SPAIR_C256 = 0x1d,
+  ESP_BLE_AD_TYPE_SPAIR_R256 = 0x1e,
+  ESP_BLE_AD_TYPE_32SOL_SRV_UUID = 0x1f,
+  ESP_BLE_AD_TYPE_32SERVICE_DATA = 0x20,
+  ESP_BLE_AD_TYPE_128SERVICE_DATA = 0x21,
+  ESP_BLE_AD_TYPE_LE_SECURE_CONFIRM = 0x22,
+  ESP_BLE_AD_TYPE_LE_SECURE_RANDOM = 0x23,
+  ESP_BLE_AD_TYPE_URI = 0x24,
+  ESP_BLE_AD_TYPE_INDOOR_POSITION = 0x25,
+  ESP_BLE_AD_TYPE_TRANS_DISC_DATA = 0x26,
+  ESP_BLE_AD_TYPE_LE_SUPPORT_FEATURE = 0x27,
+  ESP_BLE_AD_TYPE_CHAN_MAP_UPDATE = 0x28,
+  ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE = 0xFF,
+} esp_ble_adv_data_type;
+#endif
 
 /**
  * @brief Advertisement data set by the programmer to be published by the %BLE server.
  */
 class BLEAdvertisementData {
-  // Only a subset of the possible BLE architected advertisement fields are currently exposed.  Others will
-  // be exposed on demand/request or as time permits.
-  //
 public:
+  /***************************************************************************
+   *                           Common public declarations                    *
+   ***************************************************************************/
+
   void setAppearance(uint16_t appearance);
   void setCompleteServices(BLEUUID uuid);
   void setFlags(uint8_t);
@@ -33,85 +114,144 @@ class BLEAdvertisementData {
   void setPartialServices(BLEUUID uuid);
   void setServiceData(BLEUUID uuid, String data);
   void setShortName(String name);
-  void addData(String data);  // Add data to the payload.
-  String getPayload();        // Retrieve the current advert payload.
+  void setPreferredParams(uint16_t min, uint16_t max);
+  void addTxPower();
+  void addData(String data);
+  void addData(char *data, size_t length);
+  String getPayload();
 
 private:
   friend class BLEAdvertising;
-  String m_payload;  // The payload of the advertisement.
-};  // BLEAdvertisementData
+
+  /***************************************************************************
+   *                           Common private declarations                   *
+   ***************************************************************************/
+
+  String m_payload;
+};
 
 /**
  * @brief Perform and manage %BLE advertising.
- *
- * A %BLE server will want to perform advertising in order to make itself known to %BLE clients.
  */
 class BLEAdvertising {
 public:
+  /***************************************************************************
+   *                           Common public declarations                    *
+   ***************************************************************************/
+
   BLEAdvertising();
   void addServiceUUID(BLEUUID serviceUUID);
   void addServiceUUID(const char *serviceUUID);
   bool removeServiceUUID(int index);
   bool removeServiceUUID(BLEUUID serviceUUID);
   bool removeServiceUUID(const char *serviceUUID);
-  bool start();
   bool stop();
+  void reset();
   void setAppearance(uint16_t appearance);
-  void setAdvertisementType(esp_ble_adv_type_t adv_type);
-  void setAdvertisementChannelMap(esp_ble_adv_channel_t channel_map);
+  void setAdvertisementType(uint8_t adv_type);
   void setMaxInterval(uint16_t maxinterval);
   void setMinInterval(uint16_t mininterval);
   bool setAdvertisementData(BLEAdvertisementData &advertisementData);
   void setScanFilter(bool scanRequestWhitelistOnly, bool connectWhitelistOnly);
   bool setScanResponseData(BLEAdvertisementData &advertisementData);
-  void setPrivateAddress(esp_ble_addr_type_t type = BLE_ADDR_TYPE_RANDOM);
-  bool setDeviceAddress(esp_bd_addr_t addr, esp_ble_addr_type_t type = BLE_ADDR_TYPE_RANDOM);
-
-  void handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
   void setMinPreferred(uint16_t);
   void setMaxPreferred(uint16_t);
   void setScanResponse(bool);
 
+  /***************************************************************************
+   *                           Bluedroid public declarations                 *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  void setPrivateAddress(esp_ble_addr_type_t type = BLE_ADDR_TYPE_RANDOM);
+  bool setDeviceAddress(esp_bd_addr_t addr, esp_ble_addr_type_t type = BLE_ADDR_TYPE_RANDOM);
+  void setAdvertisementChannelMap(esp_ble_adv_channel_t channel_map);
+  void handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
+  bool start();
+#endif
+
+  /***************************************************************************
+   *                           NimBLE public declarations                    *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  void setName(String name);
+  void addTxPower();
+  void advCompleteCB();
+  bool isAdvertising();
+  void onHostSync();
+  bool start(uint32_t duration = 0, void (*advCompleteCB)(BLEAdvertising *pAdv) = nullptr);
+  static int handleGAPEvent(ble_gap_event *event, void *arg);
+#endif
+
 private:
-  esp_ble_adv_data_t m_advData;
-  esp_ble_adv_data_t m_scanRespData;  // Used for configuration of scan response data when m_scanResp is true
-  esp_ble_adv_params_t m_advParams;
+  /***************************************************************************
+   *                          Common private properties                      *
+   ***************************************************************************/
+
   std::vector<BLEUUID> m_serviceUUIDs;
-  bool m_customAdvData = false;           // Are we using custom advertising data?
-  bool m_customScanResponseData = false;  // Are we using custom scan response data?
+  bool m_customAdvData = false;
+  bool m_customScanResponseData = false;
   FreeRTOS::Semaphore m_semaphoreSetAdv = FreeRTOS::Semaphore("startAdvert");
   bool m_scanResp = true;
+
+  /***************************************************************************
+   *                          Bluedroid private properties                   *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  esp_ble_adv_data_t m_advData;
+  esp_ble_adv_data_t m_scanRespData;
+  esp_ble_adv_params_t m_advParams;
+#endif
+
+  /***************************************************************************
+   *                          NimBLE private properties                      *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  ble_hs_adv_fields m_advData;
+  ble_hs_adv_fields m_scanData;
+  ble_gap_adv_params m_advParams;
+  bool m_advDataSet;
+  void (*m_advCompCB)(BLEAdvertising *pAdv);
+  uint8_t m_slaveItvl[4];
+  uint32_t m_duration;
+  String m_name;
+#endif
 };
 
-#ifdef SOC_BLE_50_SUPPORTED
+/***************************************************************************
+ *                          Bluedroid 5.0 specific classes                 *
+ ***************************************************************************/
 
+#if defined(SOC_BLE_50_SUPPORTED) && defined(CONFIG_BLUEDROID_ENABLED)
 class BLEMultiAdvertising {
-private:
-  esp_ble_gap_ext_adv_params_t *params_arrays;
-  esp_ble_gap_ext_adv_t *ext_adv;
-  uint8_t count;
-
 public:
   BLEMultiAdvertising(uint8_t num = 1);
   ~BLEMultiAdvertising() {}
 
-  bool setAdvertisingParams(uint8_t instance, const esp_ble_gap_ext_adv_params_t *params);
   bool setAdvertisingData(uint8_t instance, uint16_t length, const uint8_t *data);
   bool setScanRspData(uint8_t instance, uint16_t length, const uint8_t *data);
   bool start();
   bool start(uint8_t num, uint8_t from);
   void setDuration(uint8_t instance, int duration = 0, int max_events = 0);
-  bool setInstanceAddress(uint8_t instance, esp_bd_addr_t rand_addr);
+  bool setInstanceAddress(uint8_t instance, uint8_t *rand_addr);
   bool stop(uint8_t num_adv, const uint8_t *ext_adv_inst);
   bool remove(uint8_t instance);
   bool clear();
-  bool setPeriodicAdvertisingParams(uint8_t instance, const esp_ble_gap_periodic_adv_params_t *params);
   bool setPeriodicAdvertisingData(uint8_t instance, uint16_t length, const uint8_t *data);
   bool startPeriodicAdvertising(uint8_t instance);
-};
+  bool setAdvertisingParams(uint8_t instance, const esp_ble_gap_ext_adv_params_t *params);
+  bool setPeriodicAdvertisingParams(uint8_t instance, const esp_ble_gap_periodic_adv_params_t *params);
 
-#endif  // SOC_BLE_50_SUPPORTED
+private:
+  esp_ble_gap_ext_adv_params_t *params_arrays;
+  esp_ble_gap_ext_adv_t *ext_adv;
+  uint8_t count;
+};
+#endif
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLEADVERTISING_H_ */
diff --git a/libraries/BLE/src/BLEBeacon.cpp b/libraries/BLE/src/BLEBeacon.cpp
index 43366a7b2d9..0a6c6b05258 100644
--- a/libraries/BLE/src/BLEBeacon.cpp
+++ b/libraries/BLE/src/BLEBeacon.cpp
@@ -3,17 +3,31 @@
  *
  *  Created on: Jan 4, 2018
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                       Common includes and definitions                   *
+ ***************************************************************************/
+
 #include "BLEBeacon.h"
 #include "esp32-hal-log.h"
 
 #define ENDIAN_CHANGE_U16(x) ((((x) & 0xFF00) >> 8) + (((x) & 0xFF) << 8))
 
+/***************************************************************************
+ *                              Common functions                           *
+ ***************************************************************************/
+
 BLEBeacon::BLEBeacon() {
   m_beaconData.manufacturerId = 0x4c00;
   m_beaconData.subType = 0x02;
@@ -22,11 +36,11 @@ BLEBeacon::BLEBeacon() {
   m_beaconData.minor = 0;
   m_beaconData.signalPower = 0;
   memset(m_beaconData.proximityUUID, 0, sizeof(m_beaconData.proximityUUID));
-}  // BLEBeacon
+}
 
 String BLEBeacon::getData() {
   return String((char *)&m_beaconData, sizeof(m_beaconData));
-}  // getData
+}
 
 uint16_t BLEBeacon::getMajor() {
   return m_beaconData.major;
@@ -48,37 +62,38 @@ int8_t BLEBeacon::getSignalPower() {
   return m_beaconData.signalPower;
 }
 
-/**
- * Set the raw data for the beacon record.
- */
 void BLEBeacon::setData(String data) {
   if (data.length() != sizeof(m_beaconData)) {
     log_e("Unable to set the data ... length passed in was %d and expected %d", data.length(), sizeof(m_beaconData));
     return;
   }
   memcpy(&m_beaconData, data.c_str(), sizeof(m_beaconData));
-}  // setData
+}
 
 void BLEBeacon::setMajor(uint16_t major) {
   m_beaconData.major = ENDIAN_CHANGE_U16(major);
-}  // setMajor
+}
 
 void BLEBeacon::setManufacturerId(uint16_t manufacturerId) {
   m_beaconData.manufacturerId = ENDIAN_CHANGE_U16(manufacturerId);
-}  // setManufacturerId
+}
 
 void BLEBeacon::setMinor(uint16_t minor) {
   m_beaconData.minor = ENDIAN_CHANGE_U16(minor);
-}  // setMinior
-
-void BLEBeacon::setProximityUUID(BLEUUID uuid) {
-  uuid = uuid.to128();
-  memcpy(m_beaconData.proximityUUID, uuid.getNative()->uuid.uuid128, 16);
-}  // setProximityUUID
+}
 
 void BLEBeacon::setSignalPower(int8_t signalPower) {
   m_beaconData.signalPower = signalPower;
-}  // setSignalPower
+}
 
+void BLEBeacon::setProximityUUID(BLEUUID uuid) {
+  uuid = uuid.to128();
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  memcpy(m_beaconData.proximityUUID, uuid.getNative()->uuid.uuid128, 16);
+#elif defined(CONFIG_NIMBLE_ENABLED)
+  memcpy(m_beaconData.proximityUUID, uuid.getNative()->u128.value, 16);
 #endif
+}
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEBeacon.h b/libraries/BLE/src/BLEBeacon.h
index dcc41aafeb4..e0eaddda6e4 100644
--- a/libraries/BLE/src/BLEBeacon.h
+++ b/libraries/BLE/src/BLEBeacon.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Jan 4, 2018
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLEBEACON_H_
@@ -10,6 +14,13 @@
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
+#include "sdkconfig.h"
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
 #include "BLEUUID.h"
 /**
  * @brief Representation of a beacon.
@@ -18,6 +29,10 @@
  */
 class BLEBeacon {
 private:
+  /***************************************************************************
+   *                           Common types                                  *
+   ***************************************************************************/
+
   struct {
     uint16_t manufacturerId;
     uint8_t subType;
@@ -29,6 +44,10 @@ class BLEBeacon {
   } __attribute__((packed)) m_beaconData;
 
 public:
+  /***************************************************************************
+   *                           Common public declarations                    *
+   ***************************************************************************/
+
   BLEBeacon();
   String getData();
   uint16_t getMajor();
@@ -44,5 +63,6 @@ class BLEBeacon {
   void setSignalPower(int8_t signalPower);
 };  // BLEBeacon
 
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLEBEACON_H_ */
diff --git a/libraries/BLE/src/BLECharacteristic.cpp b/libraries/BLE/src/BLECharacteristic.cpp
index b03d524a6a5..0234cd11cca 100644
--- a/libraries/BLE/src/BLECharacteristic.cpp
+++ b/libraries/BLE/src/BLECharacteristic.cpp
@@ -3,12 +3,22 @@
  *
  *  Created on: Jun 22, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
 #include <sstream>
 #include <string.h>
 #include <iomanip>
@@ -23,10 +33,31 @@
 #include "GeneralUtils.h"
 #include "esp32-hal-log.h"
 
+/***************************************************************************
+ *                           Common definitions                            *
+ ***************************************************************************/
+
 #define NULL_HANDLE (0xffff)
 
+/***************************************************************************
+ *                           NimBLE definitions                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#define NIMBLE_SUB_NOTIFY   0x0001
+#define NIMBLE_SUB_INDICATE 0x0002
+#endif
+
+/***************************************************************************
+ *                           Common global variables                       *
+ ***************************************************************************/
+
 static BLECharacteristicCallbacks defaultCallback;  //null-object-pattern
 
+/***************************************************************************
+ *                              Common functions                           *
+ ***************************************************************************/
+
 /**
  * @brief Construct a characteristic
  * @param [in] uuid - UUID (const char*) for the characteristic.
@@ -42,15 +73,23 @@ BLECharacteristic::BLECharacteristic(const char *uuid, uint32_t properties) : BL
 BLECharacteristic::BLECharacteristic(BLEUUID uuid, uint32_t properties) {
   m_bleUUID = uuid;
   m_handle = NULL_HANDLE;
-  m_properties = (esp_gatt_char_prop_t)0;
   m_pCallbacks = &defaultCallback;
 
-  setBroadcastProperty((properties & PROPERTY_BROADCAST) != 0);
-  setReadProperty((properties & PROPERTY_READ) != 0);
-  setWriteProperty((properties & PROPERTY_WRITE) != 0);
-  setNotifyProperty((properties & PROPERTY_NOTIFY) != 0);
-  setIndicateProperty((properties & PROPERTY_INDICATE) != 0);
-  setWriteNoResponseProperty((properties & PROPERTY_WRITE_NR) != 0);
+#ifdef CONFIG_BLUEDROID_ENABLED
+  m_properties = 0;
+  setBroadcastProperty((properties & BLECharacteristic::PROPERTY_BROADCAST) != 0);
+  setReadProperty((properties & BLECharacteristic::PROPERTY_READ) != 0);
+  setWriteProperty((properties & BLECharacteristic::PROPERTY_WRITE) != 0);
+  setNotifyProperty((properties & BLECharacteristic::PROPERTY_NOTIFY) != 0);
+  setIndicateProperty((properties & BLECharacteristic::PROPERTY_INDICATE) != 0);
+  setWriteNoResponseProperty((properties & BLECharacteristic::PROPERTY_WRITE_NR) != 0);
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  m_readMux = portMUX_INITIALIZER_UNLOCKED;
+  m_removed = 0;
+  m_properties = properties;
+#endif
 }  // BLECharacteristic
 
 /**
@@ -66,51 +105,20 @@ BLECharacteristic::~BLECharacteristic() {
  * @return N/A.
  */
 void BLECharacteristic::addDescriptor(BLEDescriptor *pDescriptor) {
+#ifdef CONFIG_NIMBLE_ENABLED
+  if (pDescriptor->getUUID() == BLEUUID(uint16_t(0x2902))) {
+    log_i("NimBLE automatically creates the 0x2902 descriptor if a characteristic has a notification or indication property assigned to it.\n"
+          "You should check the characteristic properties for notification or indication rather than adding the descriptor manually.\n"
+          "This will be removed in a future version of the library.");
+    pDescriptor->executeCreate(this);
+    return;
+  }
+#endif
   log_v(">> addDescriptor(): Adding %s to %s", pDescriptor->toString().c_str(), toString().c_str());
   m_descriptorMap.setByUUID(pDescriptor->getUUID(), pDescriptor);
   log_v("<< addDescriptor()");
 }  // addDescriptor
 
-/**
- * @brief Register a new characteristic with the ESP runtime.
- * @param [in] pService The service with which to associate this characteristic.
- */
-void BLECharacteristic::executeCreate(BLEService *pService) {
-  log_v(">> executeCreate()");
-
-  if (m_handle != NULL_HANDLE) {
-    log_e("Characteristic already has a handle.");
-    return;
-  }
-
-  m_pService = pService;  // Save the service to which this characteristic belongs.
-
-  log_d("Registering characteristic (esp_ble_gatts_add_char): uuid: %s, service: %s", getUUID().toString().c_str(), m_pService->toString().c_str());
-
-  esp_attr_control_t control;
-  control.auto_rsp = ESP_GATT_RSP_BY_APP;
-
-  m_semaphoreCreateEvt.take("executeCreate");
-  esp_err_t errRc = ::esp_ble_gatts_add_char(
-    m_pService->getHandle(), getUUID().getNative(), static_cast<esp_gatt_perm_t>(m_permissions), getProperties(), nullptr,
-    &control
-  );  // Whether to auto respond or not.
-
-  if (errRc != ESP_OK) {
-    log_e("<< esp_ble_gatts_add_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-    return;
-  }
-  m_semaphoreCreateEvt.wait("executeCreate");
-
-  BLEDescriptor *pDescriptor = m_descriptorMap.getFirst();
-  while (pDescriptor != nullptr) {
-    pDescriptor->executeCreate(this);
-    pDescriptor = m_descriptorMap.getNext();
-  }  // End while
-
-  log_v("<< executeCreate");
-}  // executeCreate
-
 /**
  * @brief Return the BLE Descriptor for the given UUID if associated with this characteristic.
  * @param [in] descriptorUUID The UUID of the descriptor that we wish to retrieve.
@@ -137,8 +145,10 @@ uint16_t BLECharacteristic::getHandle() {
   return m_handle;
 }  // getHandle
 
-void BLECharacteristic::setAccessPermissions(esp_gatt_perm_t perm) {
+void BLECharacteristic::setAccessPermissions(uint8_t perm) {
+#ifdef CONFIG_BLUEDROID_ENABLED
   m_permissions = perm;
+#endif
 }
 
 esp_gatt_char_prop_t BLECharacteristic::getProperties() {
@@ -185,390 +195,76 @@ size_t BLECharacteristic::getLength() {
 }  // getLength
 
 /**
- * Handle a GATT server event.
+ * @brief Register a new characteristic with the ESP runtime.
+ * @param [in] pService The service with which to associate this characteristic.
  */
-void BLECharacteristic::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) {
-  log_v(">> handleGATTServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str());
+void BLECharacteristic::executeCreate(BLEService *pService) {
+  log_v(">> executeCreate()");
 
-  switch (event) {
-      // Events handled:
-      //
-      // ESP_GATTS_ADD_CHAR_EVT
-      // ESP_GATTS_CONF_EVT
-      // ESP_GATTS_CONNECT_EVT
-      // ESP_GATTS_DISCONNECT_EVT
-      // ESP_GATTS_EXEC_WRITE_EVT
-      // ESP_GATTS_READ_EVT
-      // ESP_GATTS_WRITE_EVT
+  if (m_handle != NULL_HANDLE) {
+    log_e("Characteristic already has a handle.");
+    return;
+  }
 
-    //
-    // ESP_GATTS_EXEC_WRITE_EVT
-    // When we receive this event it is an indication that a previous write long needs to be committed.
-    //
-    // exec_write:
-    // - uint16_t conn_id
-    // - uint32_t trans_id
-    // - esp_bd_addr_t bda
-    // - uint8_t exec_write_flag - Either ESP_GATT_PREP_WRITE_EXEC or ESP_GATT_PREP_WRITE_CANCEL
-    //
-    case ESP_GATTS_EXEC_WRITE_EVT:
-    {
-      if (m_writeEvt) {
-        m_writeEvt = false;
-        if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC) {
-          m_value.commit();
-          // Invoke the onWrite callback handler.
-          m_pCallbacks->onWrite(this, param);
-        } else {
-          m_value.cancel();
-        }
-        // ???
-        esp_err_t errRc = ::esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, nullptr);
-        if (errRc != ESP_OK) {
-          log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-        }
-      }
-      break;
-    }  // ESP_GATTS_EXEC_WRITE_EVT
+  m_pService = pService;  // Save the service to which this characteristic belongs.
 
-    // ESP_GATTS_ADD_CHAR_EVT - Indicate that a characteristic was added to the service.
-    // add_char:
-    // - esp_gatt_status_t status
-    // - uint16_t attr_handle
-    // - uint16_t service_handle
-    // - esp_bt_uuid_t char_uuid
-    case ESP_GATTS_ADD_CHAR_EVT:
-    {
-      if (getHandle() == param->add_char.attr_handle) {
-        // we have created characteristic, now we can create descriptors
-        // BLEDescriptor* pDescriptor = m_descriptorMap.getFirst();
-        // while (pDescriptor != nullptr) {
-        // 	pDescriptor->executeCreate(this);
-        // 	pDescriptor = m_descriptorMap.getNext();
-        // } // End while
-        m_semaphoreCreateEvt.give();
-      }
-      break;
-    }  // ESP_GATTS_ADD_CHAR_EVT
+#ifdef CONFIG_BLUEDROID_ENABLED
+  log_d("Registering characteristic (esp_ble_gatts_add_char): uuid: %s, service: %s", getUUID().toString().c_str(), m_pService->toString().c_str());
 
-    // ESP_GATTS_WRITE_EVT - A request to write the value of a characteristic has arrived.
-    //
-    // write:
-    // - uint16_t      conn_id
-    // - uint16_t      trans_id
-    // - esp_bd_addr_t bda
-    // - uint16_t      handle
-    // - uint16_t      offset
-    // - bool          need_rsp
-    // - bool          is_prep
-    // - uint16_t      len
-    // - uint8_t      *value
-    //
-    case ESP_GATTS_WRITE_EVT:
-    {
-      // We check if this write request is for us by comparing the handles in the event.  If it is for us
-      // we save the new value.  Next we look at the need_rsp flag which indicates whether or not we need
-      // to send a response.  If we do, then we formulate a response and send it.
-      if (param->write.handle == m_handle) {
-        if (param->write.is_prep) {
-          m_value.addPart(param->write.value, param->write.len);
-          m_writeEvt = true;
-        } else {
-          setValue(param->write.value, param->write.len);
-        }
+  esp_attr_control_t control;
+  control.auto_rsp = ESP_GATT_RSP_BY_APP;
 
-        log_d(" - Response to write event: New value: handle: %.2x, uuid: %s", getHandle(), getUUID().toString().c_str());
+  m_semaphoreCreateEvt.take("executeCreate");
+  esp_err_t errRc = ::esp_ble_gatts_add_char(
+    m_pService->getHandle(), getUUID().getNative(), static_cast<esp_gatt_perm_t>(m_permissions), getProperties(), nullptr,
+    &control
+  );  // Whether to auto respond or not.
+
+  if (errRc != ESP_OK) {
+    log_e("<< esp_ble_gatts_add_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+    return;
+  }
+  m_semaphoreCreateEvt.wait("executeCreate");
 
-// The call to BLEUtils::buildHexData() doesn't output anything if the log level is not
-// "DEBUG". As it is quite CPU intensive, it is much better to not call it if not needed.
-#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
-        char *pHexData = BLEUtils::buildHexData(nullptr, param->write.value, param->write.len);
-        log_d(" - Data: length: %d, data: %s", param->write.len, pHexData);
-        free(pHexData);
 #endif
 
-        if (param->write.need_rsp) {
-          esp_gatt_rsp_t rsp;
+  BLEDescriptor *pDescriptor = m_descriptorMap.getFirst();
+  while (pDescriptor != nullptr) {
+    pDescriptor->executeCreate(this);
+    pDescriptor = m_descriptorMap.getNext();
+  }  // End while
 
-          rsp.attr_value.len = param->write.len;
-          rsp.attr_value.handle = m_handle;
-          rsp.attr_value.offset = param->write.offset;
-          rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
-          memcpy(rsp.attr_value.value, param->write.value, param->write.len);
+  log_v("<< executeCreate");
+}  // executeCreate
 
-          esp_err_t errRc = ::esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, &rsp);
-          if (errRc != ESP_OK) {
-            log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-          }
-        }  // Response needed
+/**
+ * @brief Send an indication.
+ * An indication is a transmission of up to the first 20 bytes of the characteristic value.  An indication
+ * will block waiting a positive confirmation from the client.
+ * @return N/A
+ */
+void BLECharacteristic::indicate() {
 
-        if (param->write.is_prep != true) {
-          // Invoke the onWrite callback handler.
-          m_pCallbacks->onWrite(this, param);
-        }
-      }  // Match on handles.
-      break;
-    }  // ESP_GATTS_WRITE_EVT
+  log_v(">> indicate: length: %d", m_value.getValue().length());
+  notify(false);
+  log_v("<< indicate");
+}  // indicate
 
-    // ESP_GATTS_READ_EVT - A request to read the value of a characteristic has arrived.
-    //
-    // read:
-    // - uint16_t      conn_id
-    // - uint32_t      trans_id
-    // - esp_bd_addr_t bda
-    // - uint16_t      handle
-    // - uint16_t      offset
-    // - bool          is_long
-    // - bool          need_rsp
-    //
-    case ESP_GATTS_READ_EVT:
-    {
-      if (param->read.handle == m_handle) {
-
-        // Here's an interesting thing.  The read request has the option of saying whether we need a response
-        // or not.  What would it "mean" to receive a read request and NOT send a response back?  That feels like
-        // a very strange read.
-        //
-        // We have to handle the case where the data we wish to send back to the client is greater than the maximum
-        // packet size of 22 bytes.  In this case, we become responsible for chunking the data into units of 22 bytes.
-        // The apparent algorithm is as follows:
-        //
-        // If the is_long flag is set then this is a follow on from an original read and we will already have sent at least 22 bytes.
-        // If the is_long flag is not set then we need to check how much data we are going to send.  If we are sending LESS than
-        // 22 bytes, then we "just" send it and that's the end of the story.
-        // If we are sending 22 bytes exactly, we just send it BUT we will get a follow on request.
-        // If we are sending more than 22 bytes, we send the first 22 bytes and we will get a follow on request.
-        // Because of follow on request processing, we need to maintain an offset of how much data we have already sent
-        // so that when a follow on request arrives, we know where to start in the data to send the next sequence.
-        // Note that the indication that the client will send a follow on request is that we sent exactly 22 bytes as a response.
-        // If our payload is divisible by 22 then the last response will be a response of 0 bytes in length.
-        //
-        // The following code has deliberately not been factored to make it fewer statements because this would cloud the
-        // the logic flow comprehension.
-        //
-
-        // get mtu for peer device that we are sending read request to
-        uint16_t maxOffset = getService()->getServer()->getPeerMTU(param->read.conn_id) - 1;
-        log_d("mtu value: %d", maxOffset);
-        if (param->read.need_rsp) {
-          log_d("Sending a response (esp_ble_gatts_send_response)");
-          esp_gatt_rsp_t rsp;
-
-          if (param->read.is_long) {
-            String value = m_value.getValue();
-
-            if (value.length() - m_value.getReadOffset() < maxOffset) {
-              // This is the last in the chain
-              rsp.attr_value.len = value.length() - m_value.getReadOffset();
-              rsp.attr_value.offset = m_value.getReadOffset();
-              memcpy(rsp.attr_value.value, value.c_str() + rsp.attr_value.offset, rsp.attr_value.len);
-              m_value.setReadOffset(0);
-            } else {
-              // There will be more to come.
-              rsp.attr_value.len = maxOffset;
-              rsp.attr_value.offset = m_value.getReadOffset();
-              memcpy(rsp.attr_value.value, value.c_str() + rsp.attr_value.offset, rsp.attr_value.len);
-              m_value.setReadOffset(rsp.attr_value.offset + maxOffset);
-            }
-          } else {  // read.is_long == false
-
-            // If is.long is false then this is the first (or only) request to read data, so invoke the callback
-            // Invoke the read callback.
-            m_pCallbacks->onRead(this, param);
-
-            String value = m_value.getValue();
-
-            if (value.length() + 1 > maxOffset) {
-              // Too big for a single shot entry.
-              m_value.setReadOffset(maxOffset);
-              rsp.attr_value.len = maxOffset;
-              rsp.attr_value.offset = 0;
-              memcpy(rsp.attr_value.value, value.c_str(), rsp.attr_value.len);
-            } else {
-              // Will fit in a single packet with no callbacks required.
-              rsp.attr_value.len = value.length();
-              rsp.attr_value.offset = 0;
-              memcpy(rsp.attr_value.value, value.c_str(), rsp.attr_value.len);
-            }
-          }
-          rsp.attr_value.handle = param->read.handle;
-          rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
-
-// The call to BLEUtils::buildHexData() doesn't output anything if the log level is not
-// "DEBUG". As it is quite CPU intensive, it is much better to not call it if not needed.
-#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
-          char *pHexData = BLEUtils::buildHexData(nullptr, rsp.attr_value.value, rsp.attr_value.len);
-          log_d(" - Data: length=%d, data=%s, offset=%d", rsp.attr_value.len, pHexData, rsp.attr_value.offset);
-          free(pHexData);
-#endif
-
-          esp_err_t errRc = ::esp_ble_gatts_send_response(gatts_if, param->read.conn_id, param->read.trans_id, ESP_GATT_OK, &rsp);
-          if (errRc != ESP_OK) {
-            log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-          }
-        }  // Response needed
-      }  // Handle matches this characteristic.
-      break;
-    }  // ESP_GATTS_READ_EVT
-
-    // ESP_GATTS_CONF_EVT
-    //
-    // conf:
-    // - esp_gatt_status_t status  – The status code.
-    // - uint16_t          conn_id – The connection used.
-    //
-    case ESP_GATTS_CONF_EVT:
-    {
-      // log_d("m_handle = %d, conf->handle = %d", m_handle, param->conf.handle);
-      if (param->conf.conn_id
-          == getService()->getServer()->getConnId()) {  // && param->conf.handle == m_handle) // bug in esp-idf and not implemented in arduino yet
-        m_semaphoreConfEvt.give(param->conf.status);
-      }
-      break;
-    }
-
-    case ESP_GATTS_CONNECT_EVT:
-    {
-      break;
-    }
-
-    case ESP_GATTS_DISCONNECT_EVT:
-    {
-      m_semaphoreConfEvt.give();
-      break;
-    }
-
-    default:
-    {
-      break;
-    }  // default
-
-  }  // switch event
-
-  // Give each of the descriptors associated with this characteristic the opportunity to handle the
-  // event.
-
-  m_descriptorMap.handleGATTServerEvent(event, gatts_if, param);
-  log_v("<< handleGATTServerEvent");
-}  // handleGATTServerEvent
-
-/**
- * @brief Send an indication.
- * An indication is a transmission of up to the first 20 bytes of the characteristic value.  An indication
- * will block waiting a positive confirmation from the client.
- * @return N/A
- */
-void BLECharacteristic::indicate() {
-
-  log_v(">> indicate: length: %d", m_value.getValue().length());
-  notify(false);
-  log_v("<< indicate");
-}  // indicate
-
-/**
- * @brief Send a notify.
- * A notification is a transmission of up to the first 20 bytes of the characteristic value.  An notification
- * will not block; it is a fire and forget.
- * @return N/A.
- */
-void BLECharacteristic::notify(bool is_notification) {
-  log_v(">> notify: length: %d", m_value.getValue().length());
-
-  assert(getService() != nullptr);
-  assert(getService()->getServer() != nullptr);
-
-  m_pCallbacks->onNotify(this);  // Invoke the notify callback.
-
-  // GeneralUtils::hexDump() doesn't output anything if the log level is not
-  // "VERBOSE". Additionally, it is very CPU intensive, even when it doesn't
-  // output anything! So it is much better to *not* call it at all if not needed.
-  // In a simple program which calls BLECharacteristic::notify() every 50 ms,
-  // the performance gain of this little optimization is 37% in release mode
-  // (-O3) and 57% in debug mode.
-  // Of course, the "#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE" guard
-  // could also be put inside the GeneralUtils::hexDump() function itself. But
-  // it's better to put it here also, as it is clearer (indicating a verbose log
-  // thing) and it allows to remove the "m_value.getValue().c_str()" call, which
-  // is, in itself, quite CPU intensive.
-#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
-  GeneralUtils::hexDump((uint8_t *)m_value.getValue().c_str(), m_value.getValue().length());
-#endif
-
-  if (getService()->getServer()->getConnectedCount() == 0) {
-    log_v("<< notify: No connected clients.");
-    m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NO_CLIENT, 0);
-    return;
-  }
-
-  // Test to see if we have a 0x2902 descriptor.  If we do, then check to see if notification is enabled
-  // and, if not, prevent the notification.
-
-  BLE2902 *p2902 = (BLE2902 *)getDescriptorByUUID((uint16_t)0x2902);
-  if (is_notification) {
-    if (p2902 != nullptr && !p2902->getNotifications()) {
-      log_v("<< notifications disabled; ignoring");
-      m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NOTIFY_DISABLED, 0);  // Invoke the notify callback.
-      return;
-    }
-  } else {
-    if (p2902 != nullptr && !p2902->getIndications()) {
-      log_v("<< indications disabled; ignoring");
-      m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_DISABLED, 0);  // Invoke the notify callback.
-      return;
-    }
-  }
-  for (auto &myPair : getService()->getServer()->getPeerDevices(false)) {
-    uint16_t _mtu = (myPair.second.mtu);
-    if (m_value.getValue().length() > _mtu - 3) {
-      log_w("- Truncating to %d bytes (maximum notify size)", _mtu - 3);
-    }
-
-    size_t length = m_value.getValue().length();
-    if (!is_notification) {  // is indication
-      m_semaphoreConfEvt.take("indicate");
-    }
-    esp_err_t errRc = ::esp_ble_gatts_send_indicate(
-      getService()->getServer()->getGattsIf(), myPair.first, getHandle(), length, (uint8_t *)m_value.getValue().c_str(), !is_notification
-    );  // The need_confirm = false makes this a notify.
-    if (errRc != ESP_OK) {
-      log_e("<< esp_ble_gatts_send_ %s: rc=%d %s", is_notification ? "notify" : "indicate", errRc, GeneralUtils::errorToString(errRc));
-      m_semaphoreConfEvt.give();
-      m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_GATT, errRc);  // Invoke the notify callback.
-      return;
-    }
-    if (!is_notification) {  // is indication
-      if (!m_semaphoreConfEvt.timedWait("indicate", indicationTimeout)) {
-        m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_TIMEOUT, 0);  // Invoke the notify callback.
-      } else {
-        auto code = (esp_gatt_status_t)m_semaphoreConfEvt.value();
-        if (code == ESP_GATT_OK) {
-          m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::SUCCESS_INDICATE, code);  // Invoke the notify callback.
-        } else {
-          m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_FAILURE, code);
-        }
-      }
-    } else {
-      m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::SUCCESS_NOTIFY, 0);  // Invoke the notify callback.
-    }
-  }
-  log_v("<< notify");
-}  // Notify
-
-/**
- * @brief Set the permission to broadcast.
- * A characteristics has properties associated with it which define what it is capable of doing.
- * One of these is the broadcast flag.
- * @param [in] value The flag value of the property.
- * @return N/A
- */
-void BLECharacteristic::setBroadcastProperty(bool value) {
-  //log_d("setBroadcastProperty(%d)", value);
-  if (value) {
-    m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_BROADCAST);
-  } else {
-    m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_BROADCAST);
-  }
-}  // setBroadcastProperty
+/**
+ * @brief Set the permission to broadcast.
+ * A characteristics has properties associated with it which define what it is capable of doing.
+ * One of these is the broadcast flag.
+ * @param [in] value The flag value of the property.
+ * @return N/A
+ */
+void BLECharacteristic::setBroadcastProperty(bool value) {
+  //log_d("setBroadcastProperty(%d)", value);
+  if (value) {
+    m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_BROADCAST);
+  } else {
+    m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_BROADCAST);
+  }
+}  // setBroadcastProperty
 
 /**
  * @brief Set the callback handlers for this characteristic.
@@ -595,9 +291,15 @@ void BLECharacteristic::setCallbacks(BLECharacteristicCallbacks *pCallbacks) {
  * @param [in] handle The handle associated with this characteristic.
  */
 void BLECharacteristic::setHandle(uint16_t handle) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
   log_v(">> setHandle: handle=0x%.2x, characteristic uuid=%s", handle, getUUID().toString().c_str());
   m_handle = handle;
   log_v("<< setHandle");
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  log_w("NimBLE does not support manually setting the handle of a characteristic. Ignoring request.");
+#endif
 }  // setHandle
 
 /**
@@ -767,19 +469,12 @@ String BLECharacteristic::toString() {
 
 BLECharacteristicCallbacks::~BLECharacteristicCallbacks() {}
 
-void BLECharacteristicCallbacks::onRead(BLECharacteristic *pCharacteristic, esp_ble_gatts_cb_param_t *param) {
-  onRead(pCharacteristic);
-}  // onRead
-
+// Common callbacks
 void BLECharacteristicCallbacks::onRead(BLECharacteristic *pCharacteristic) {
   log_d(">> onRead: default");
   log_d("<< onRead");
 }  // onRead
 
-void BLECharacteristicCallbacks::onWrite(BLECharacteristic *pCharacteristic, esp_ble_gatts_cb_param_t *param) {
-  onWrite(pCharacteristic);
-}  // onWrite
-
 void BLECharacteristicCallbacks::onWrite(BLECharacteristic *pCharacteristic) {
   log_d(">> onWrite: default");
   log_d("<< onWrite");
@@ -795,5 +490,650 @@ void BLECharacteristicCallbacks::onStatus(BLECharacteristic *pCharacteristic, St
   log_d("<< onStatus");
 }  // onStatus
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+/***************************************************************************
+ *                             Bluedroid functions                         *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+
+/**
+ * Handle a GATT server event.
+ */
+void BLECharacteristic::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) {
+  log_v(">> handleGATTServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str());
+
+  switch (event) {
+      // Events handled:
+      //
+      // ESP_GATTS_ADD_CHAR_EVT
+      // ESP_GATTS_CONF_EVT
+      // ESP_GATTS_CONNECT_EVT
+      // ESP_GATTS_DISCONNECT_EVT
+      // ESP_GATTS_EXEC_WRITE_EVT
+      // ESP_GATTS_READ_EVT
+      // ESP_GATTS_WRITE_EVT
+
+    //
+    // ESP_GATTS_EXEC_WRITE_EVT
+    // When we receive this event it is an indication that a previous write long needs to be committed.
+    //
+    // exec_write:
+    // - uint16_t conn_id
+    // - uint32_t trans_id
+    // - esp_bd_addr_t bda
+    // - uint8_t exec_write_flag - Either ESP_GATT_PREP_WRITE_EXEC or ESP_GATT_PREP_WRITE_CANCEL
+    //
+    case ESP_GATTS_EXEC_WRITE_EVT:
+    {
+      if (m_writeEvt) {
+        m_writeEvt = false;
+        if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC) {
+          m_value.commit();
+          // Invoke the onWrite callback handler.
+          m_pCallbacks->onWrite(this, param);
+        } else {
+          m_value.cancel();
+        }
+        // ???
+        esp_err_t errRc = ::esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, nullptr);
+        if (errRc != ESP_OK) {
+          log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+        }
+      }
+      break;
+    }  // ESP_GATTS_EXEC_WRITE_EVT
+
+    // ESP_GATTS_ADD_CHAR_EVT - Indicate that a characteristic was added to the service.
+    // add_char:
+    // - esp_gatt_status_t status
+    // - uint16_t attr_handle
+    // - uint16_t service_handle
+    // - esp_bt_uuid_t char_uuid
+    case ESP_GATTS_ADD_CHAR_EVT:
+    {
+      if (getHandle() == param->add_char.attr_handle) {
+        // we have created characteristic, now we can create descriptors
+        // BLEDescriptor* pDescriptor = m_descriptorMap.getFirst();
+        // while (pDescriptor != nullptr) {
+        // 	pDescriptor->executeCreate(this);
+        // 	pDescriptor = m_descriptorMap.getNext();
+        // } // End while
+        m_semaphoreCreateEvt.give();
+      }
+      break;
+    }  // ESP_GATTS_ADD_CHAR_EVT
+
+    // ESP_GATTS_WRITE_EVT - A request to write the value of a characteristic has arrived.
+    //
+    // write:
+    // - uint16_t      conn_id
+    // - uint16_t      trans_id
+    // - esp_bd_addr_t bda
+    // - uint16_t      handle
+    // - uint16_t      offset
+    // - bool          need_rsp
+    // - bool          is_prep
+    // - uint16_t      len
+    // - uint8_t      *value
+    //
+    case ESP_GATTS_WRITE_EVT:
+    {
+      // We check if this write request is for us by comparing the handles in the event.  If it is for us
+      // we save the new value.  Next we look at the need_rsp flag which indicates whether or not we need
+      // to send a response.  If we do, then we formulate a response and send it.
+      if (param->write.handle == m_handle) {
+        if (param->write.is_prep) {
+          m_value.addPart(param->write.value, param->write.len);
+          m_writeEvt = true;
+        } else {
+          setValue(param->write.value, param->write.len);
+        }
+
+        log_d(" - Response to write event: New value: handle: %.2x, uuid: %s", getHandle(), getUUID().toString().c_str());
+
+// The call to BLEUtils::buildHexData() doesn't output anything if the log level is not
+// "DEBUG". As it is quite CPU intensive, it is much better to not call it if not needed.
+#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
+        char *pHexData = BLEUtils::buildHexData(nullptr, param->write.value, param->write.len);
+        log_d(" - Data: length: %d, data: %s", param->write.len, pHexData);
+        free(pHexData);
+#endif
+
+        if (param->write.need_rsp) {
+          esp_gatt_rsp_t rsp;
+
+          rsp.attr_value.len = param->write.len;
+          rsp.attr_value.handle = m_handle;
+          rsp.attr_value.offset = param->write.offset;
+          rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
+          memcpy(rsp.attr_value.value, param->write.value, param->write.len);
+
+          esp_err_t errRc = ::esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, ESP_GATT_OK, &rsp);
+          if (errRc != ESP_OK) {
+            log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+          }
+        }  // Response needed
+
+        if (param->write.is_prep != true) {
+          // Invoke the onWrite callback handler.
+          m_pCallbacks->onWrite(this, param);
+        }
+      }  // Match on handles.
+      break;
+    }  // ESP_GATTS_WRITE_EVT
+
+    // ESP_GATTS_READ_EVT - A request to read the value of a characteristic has arrived.
+    //
+    // read:
+    // - uint16_t      conn_id
+    // - uint32_t      trans_id
+    // - esp_bd_addr_t bda
+    // - uint16_t      handle
+    // - uint16_t      offset
+    // - bool          is_long
+    // - bool          need_rsp
+    //
+    case ESP_GATTS_READ_EVT:
+    {
+      if (param->read.handle == m_handle) {
+
+        // Here's an interesting thing.  The read request has the option of saying whether we need a response
+        // or not.  What would it "mean" to receive a read request and NOT send a response back?  That feels like
+        // a very strange read.
+        //
+        // We have to handle the case where the data we wish to send back to the client is greater than the maximum
+        // packet size of 22 bytes.  In this case, we become responsible for chunking the data into units of 22 bytes.
+        // The apparent algorithm is as follows:
+        //
+        // If the is_long flag is set then this is a follow on from an original read and we will already have sent at least 22 bytes.
+        // If the is_long flag is not set then we need to check how much data we are going to send.  If we are sending LESS than
+        // 22 bytes, then we "just" send it and that's the end of the story.
+        // If we are sending 22 bytes exactly, we just send it BUT we will get a follow on request.
+        // If we are sending more than 22 bytes, we send the first 22 bytes and we will get a follow on request.
+        // Because of follow on request processing, we need to maintain an offset of how much data we have already sent
+        // so that when a follow on request arrives, we know where to start in the data to send the next sequence.
+        // Note that the indication that the client will send a follow on request is that we sent exactly 22 bytes as a response.
+        // If our payload is divisible by 22 then the last response will be a response of 0 bytes in length.
+        //
+        // The following code has deliberately not been factored to make it fewer statements because this would cloud the
+        // the logic flow comprehension.
+        //
+
+        // get mtu for peer device that we are sending read request to
+        uint16_t maxOffset = getService()->getServer()->getPeerMTU(param->read.conn_id) - 1;
+        log_d("mtu value: %d", maxOffset);
+        if (param->read.need_rsp) {
+          log_d("Sending a response (esp_ble_gatts_send_response)");
+          esp_gatt_rsp_t rsp;
+
+          if (param->read.is_long) {
+            String value = m_value.getValue();
+
+            if (value.length() - m_value.getReadOffset() < maxOffset) {
+              // This is the last in the chain
+              rsp.attr_value.len = value.length() - m_value.getReadOffset();
+              rsp.attr_value.offset = m_value.getReadOffset();
+              memcpy(rsp.attr_value.value, value.c_str() + rsp.attr_value.offset, rsp.attr_value.len);
+              m_value.setReadOffset(0);
+            } else {
+              // There will be more to come.
+              rsp.attr_value.len = maxOffset;
+              rsp.attr_value.offset = m_value.getReadOffset();
+              memcpy(rsp.attr_value.value, value.c_str() + rsp.attr_value.offset, rsp.attr_value.len);
+              m_value.setReadOffset(rsp.attr_value.offset + maxOffset);
+            }
+          } else {  // read.is_long == false
+
+            // If is.long is false then this is the first (or only) request to read data, so invoke the callback
+            // Invoke the read callback.
+            m_pCallbacks->onRead(this, param);
+
+            String value = m_value.getValue();
+
+            if (value.length() + 1 > maxOffset) {
+              // Too big for a single shot entry.
+              m_value.setReadOffset(maxOffset);
+              rsp.attr_value.len = maxOffset;
+              rsp.attr_value.offset = 0;
+              memcpy(rsp.attr_value.value, value.c_str(), rsp.attr_value.len);
+            } else {
+              // Will fit in a single packet with no callbacks required.
+              rsp.attr_value.len = value.length();
+              rsp.attr_value.offset = 0;
+              memcpy(rsp.attr_value.value, value.c_str(), rsp.attr_value.len);
+            }
+          }
+          rsp.attr_value.handle = param->read.handle;
+          rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
+
+// The call to BLEUtils::buildHexData() doesn't output anything if the log level is not
+// "DEBUG". As it is quite CPU intensive, it is much better to not call it if not needed.
+#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
+          char *pHexData = BLEUtils::buildHexData(nullptr, rsp.attr_value.value, rsp.attr_value.len);
+          log_d(" - Data: length=%d, data=%s, offset=%d", rsp.attr_value.len, pHexData, rsp.attr_value.offset);
+          free(pHexData);
+#endif
+
+          esp_err_t errRc = ::esp_ble_gatts_send_response(gatts_if, param->read.conn_id, param->read.trans_id, ESP_GATT_OK, &rsp);
+          if (errRc != ESP_OK) {
+            log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+          }
+        }  // Response needed
+      }  // Handle matches this characteristic.
+      break;
+    }  // ESP_GATTS_READ_EVT
+
+    // ESP_GATTS_CONF_EVT
+    //
+    // conf:
+    // - esp_gatt_status_t status  – The status code.
+    // - uint16_t          conn_id – The connection used.
+    //
+    case ESP_GATTS_CONF_EVT:
+    {
+      // log_d("m_handle = %d, conf->handle = %d", m_handle, param->conf.handle);
+      if (param->conf.conn_id
+          == getService()->getServer()->getConnId()) {  // && param->conf.handle == m_handle) // bug in esp-idf and not implemented in arduino yet
+        m_semaphoreConfEvt.give(param->conf.status);
+      }
+      break;
+    }
+
+    case ESP_GATTS_CONNECT_EVT:
+    {
+      break;
+    }
+
+    case ESP_GATTS_DISCONNECT_EVT:
+    {
+      m_semaphoreConfEvt.give();
+      break;
+    }
+
+    default:
+    {
+      break;
+    }  // default
+
+  }  // switch event
+
+  // Give each of the descriptors associated with this characteristic the opportunity to handle the
+  // event.
+
+  m_descriptorMap.handleGATTServerEvent(event, gatts_if, param);
+  log_v("<< handleGATTServerEvent");
+}  // handleGATTServerEvent
+
+/**
+ * @brief Send a notify.
+ * A notification is a transmission of up to the first 20 bytes of the characteristic value.  An notification
+ * will not block; it is a fire and forget.
+ * @return N/A.
+ */
+void BLECharacteristic::notify(bool is_notification) {
+  log_v(">> notify: length: %d", m_value.getValue().length());
+
+  assert(getService() != nullptr);
+  assert(getService()->getServer() != nullptr);
+
+  m_pCallbacks->onNotify(this);  // Invoke the notify callback.
+
+  // GeneralUtils::hexDump() doesn't output anything if the log level is not
+  // "VERBOSE". Additionally, it is very CPU intensive, even when it doesn't
+  // output anything! So it is much better to *not* call it at all if not needed.
+  // In a simple program which calls BLECharacteristic::notify() every 50 ms,
+  // the performance gain of this little optimization is 37% in release mode
+  // (-O3) and 57% in debug mode.
+  // Of course, the "#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE" guard
+  // could also be put inside the GeneralUtils::hexDump() function itself. But
+  // it's better to put it here also, as it is clearer (indicating a verbose log
+  // thing) and it allows to remove the "m_value.getValue().c_str()" call, which
+  // is, in itself, quite CPU intensive.
+#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
+  GeneralUtils::hexDump((uint8_t *)m_value.getValue().c_str(), m_value.getValue().length());
+#endif
+
+  if (getService()->getServer()->getConnectedCount() == 0) {
+    log_v("<< notify: No connected clients.");
+    m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NO_CLIENT, 0);
+    return;
+  }
+
+  // Test to see if we have a 0x2902 descriptor.  If we do, then check to see if notification is enabled
+  // and, if not, prevent the notification.
+
+  BLE2902 *p2902 = (BLE2902 *)getDescriptorByUUID((uint16_t)0x2902);
+  if (is_notification) {
+    if (p2902 != nullptr && !p2902->getNotifications()) {
+      log_v("<< notifications disabled; ignoring");
+      m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NOTIFY_DISABLED, 0);  // Invoke the notify callback.
+      return;
+    }
+  } else {
+    if (p2902 != nullptr && !p2902->getIndications()) {
+      log_v("<< indications disabled; ignoring");
+      m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_DISABLED, 0);  // Invoke the notify callback.
+      return;
+    }
+  }
+  for (auto &myPair : getService()->getServer()->getPeerDevices(false)) {
+    uint16_t _mtu = (myPair.second.mtu);
+    if (m_value.getValue().length() > _mtu - 3) {
+      log_w("- Truncating to %d bytes (maximum notify size)", _mtu - 3);
+    }
+
+    size_t length = m_value.getValue().length();
+    if (!is_notification) {  // is indication
+      m_semaphoreConfEvt.take("indicate");
+    }
+    esp_err_t errRc = ::esp_ble_gatts_send_indicate(
+      getService()->getServer()->getGattsIf(), myPair.first, getHandle(), length, (uint8_t *)m_value.getValue().c_str(), !is_notification
+    );  // The need_confirm = false makes this a notify.
+    if (errRc != ESP_OK) {
+      log_e("<< esp_ble_gatts_send_ %s: rc=%d %s", is_notification ? "notify" : "indicate", errRc, GeneralUtils::errorToString(errRc));
+      m_semaphoreConfEvt.give();
+      m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_GATT, errRc);  // Invoke the notify callback.
+      return;
+    }
+    if (!is_notification) {  // is indication
+      if (!m_semaphoreConfEvt.timedWait("indicate", indicationTimeout)) {
+        m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_TIMEOUT, 0);  // Invoke the notify callback.
+      } else {
+        auto code = (esp_gatt_status_t)m_semaphoreConfEvt.value();
+        if (code == ESP_GATT_OK) {
+          m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::SUCCESS_INDICATE, code);  // Invoke the notify callback.
+        } else {
+          m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_FAILURE, code);
+        }
+      }
+    } else {
+      m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::SUCCESS_NOTIFY, 0);  // Invoke the notify callback.
+    }
+  }
+  log_v("<< notify");
+}  // Notify
+
+void BLECharacteristicCallbacks::onRead(BLECharacteristic *pCharacteristic, esp_ble_gatts_cb_param_t *param) {
+  onRead(pCharacteristic);
+}  // onRead
+
+void BLECharacteristicCallbacks::onWrite(BLECharacteristic *pCharacteristic, esp_ble_gatts_cb_param_t *param) {
+  onWrite(pCharacteristic);
+}  // onWrite
+
+#endif /* CONFIG_BLUEDROID_ENABLED */
+
+/***************************************************************************
+ *                             NimBLE functions                           *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
+int BLECharacteristic::handleGATTServerEvent(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt *ctxt, void *arg) {
+  const ble_uuid_t *uuid;
+  int rc;
+  struct ble_gap_conn_desc desc;
+  BLECharacteristic *pCharacteristic = (BLECharacteristic *)arg;
+
+  log_d("Characteristic %s %s event", pCharacteristic->getUUID().toString().c_str(), ctxt->op == BLE_GATT_ACCESS_OP_READ_CHR ? "Read" : "Write");
+
+  uuid = ctxt->chr->uuid;
+  if (ble_uuid_cmp(uuid, &pCharacteristic->getUUID().getNative()->u) == 0) {
+    switch (ctxt->op) {
+      case BLE_GATT_ACCESS_OP_READ_CHR:
+      {
+        // If the packet header is only 8 bytes this is a follow up of a long read
+        // so we don't want to call the onRead() callback again.
+        if (ctxt->om->om_pkthdr_len > 8) {
+          rc = ble_gap_conn_find(conn_handle, &desc);
+          assert(rc == 0);
+          pCharacteristic->m_pCallbacks->onRead(pCharacteristic);
+          pCharacteristic->m_pCallbacks->onRead(pCharacteristic, &desc);
+        }
+
+        portENTER_CRITICAL(&pCharacteristic->m_readMux);
+        rc = os_mbuf_append(ctxt->om, (uint8_t *)pCharacteristic->m_value.getValue().c_str(), pCharacteristic->m_value.getValue().length());
+        portEXIT_CRITICAL(&pCharacteristic->m_readMux);
+
+        return rc == 0 ? 0 : BLE_ATT_ERR_INSUFFICIENT_RES;
+      }
+
+      case BLE_GATT_ACCESS_OP_WRITE_CHR:
+      {
+        if (ctxt->om->om_len > BLE_ATT_ATTR_MAX_LEN) {
+          return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
+        }
+
+        uint8_t buf[BLE_ATT_ATTR_MAX_LEN];
+        size_t len = ctxt->om->om_len;
+        memcpy(buf, ctxt->om->om_data, len);
+
+        os_mbuf *next;
+        next = SLIST_NEXT(ctxt->om, om_next);
+        while (next != NULL) {
+          if ((len + next->om_len) > BLE_ATT_ATTR_MAX_LEN) {
+            return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
+          }
+          memcpy(&buf[len], next->om_data, next->om_len);
+          len += next->om_len;
+          next = SLIST_NEXT(next, om_next);
+        }
+        rc = ble_gap_conn_find(conn_handle, &desc);
+        assert(rc == 0);
+        pCharacteristic->setValue(buf, len);
+        pCharacteristic->m_pCallbacks->onWrite(pCharacteristic);
+        pCharacteristic->m_pCallbacks->onWrite(pCharacteristic, &desc);
+
+        return 0;
+      }
+
+      default: break;
+    }
+  }
+
+  return BLE_ATT_ERR_UNLIKELY;
+
+  //m_descriptorMap.handleGATTServerEvent(conn_handle, attr_handle, ctxt, arg);
+}
+
+/**
+ * @brief Set the subscribe status for this characteristic.\n
+ * This will maintain a vector of subscribed clients and their indicate/notify status.
+ */
+void BLECharacteristic::setSubscribe(struct ble_gap_event *event) {
+  ble_gap_conn_desc desc;
+  if (ble_gap_conn_find(event->subscribe.conn_handle, &desc) != 0) {
+    return;
+  }
+
+  uint16_t subVal = 0;
+  if (event->subscribe.cur_notify > 0 && (m_properties & BLECharacteristic::PROPERTY_NOTIFY)) {
+    subVal |= NIMBLE_SUB_NOTIFY;
+  }
+  if (event->subscribe.cur_indicate && (m_properties & BLECharacteristic::PROPERTY_INDICATE)) {
+    subVal |= NIMBLE_SUB_INDICATE;
+  }
+
+  log_i("New subscribe value for conn: %d val: %d", event->subscribe.conn_handle, subVal);
+
+  if (!event->subscribe.cur_indicate && event->subscribe.prev_indicate) {
+    BLEDevice::getServer()->clearIndicateWait(event->subscribe.conn_handle);
+  }
+
+  auto it = m_subscribedVec.begin();
+  for (; it != m_subscribedVec.end(); ++it) {
+    if ((*it).first == event->subscribe.conn_handle) {
+      break;
+    }
+  }
+
+  if (subVal > 0) {
+    if (it == m_subscribedVec.end()) {
+      m_subscribedVec.push_back({event->subscribe.conn_handle, subVal});
+    } else {
+      (*it).second = subVal;
+    }
+  } else if (it != m_subscribedVec.end()) {
+    m_subscribedVec.erase(it);
+  }
+
+  m_pCallbacks->onSubscribe(this, &desc, subVal);
+}
+
+/**
+ * @brief Send a notify.
+ * A notification is a transmission of up to the first 20 bytes of the characteristic value.  An notification
+ * will not block; it is a fire and forget.
+ * @return N/A.
+ */
+void BLECharacteristic::notify(bool is_notification) {
+  log_v(">> notify: length: %d", m_value.getValue().length());
+
+  assert(getService() != nullptr);
+  assert(getService()->getServer() != nullptr);
+
+  int rc = 0;
+  m_pCallbacks->onNotify(this);  // Invoke the notify callback.
+
+  // GeneralUtils::hexDump() doesn't output anything if the log level is not
+  // "VERBOSE". Additionally, it is very CPU intensive, even when it doesn't
+  // output anything! So it is much better to *not* call it at all if not needed.
+  // In a simple program which calls BLECharacteristic::notify() every 50 ms,
+  // the performance gain of this little optimization is 37% in release mode
+  // (-O3) and 57% in debug mode.
+  // Of course, the "#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE" guard
+  // could also be put inside the GeneralUtils::hexDump() function itself. But
+  // it's better to put it here also, as it is clearer (indicating a verbose log
+  // thing) and it allows to remove the "m_value.getValue().c_str()" call, which
+  // is, in itself, quite CPU intensive.
+#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
+  GeneralUtils::hexDump((uint8_t *)m_value.getValue().c_str(), m_value.getValue().length());
+#endif
+
+  if (getService()->getServer()->getConnectedCount() == 0) {
+    log_v("<< notify: No connected clients.");
+    m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NO_CLIENT, 0);
+    return;
+  }
+
+  if (m_subscribedVec.size() == 0) {
+    log_v("<< notify: No clients subscribed.");
+    m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NO_SUBSCRIBER, 0);
+    return;
+  }
+
+  if (is_notification) {
+    if (!(m_properties & BLECharacteristic::PROPERTY_NOTIFY)) {
+      log_v("<< notifications disabled; ignoring");
+      m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NOTIFY_DISABLED, 0);  // Invoke the notify callback.
+      return;
+    }
+  } else {
+    if (!(m_properties & BLECharacteristic::PROPERTY_INDICATE)) {
+      log_v("<< indications disabled; ignoring");
+      m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_DISABLED, 0);  // Invoke the notify callback.
+      return;
+    }
+  }
+
+  bool reqSec = (m_properties & BLE_GATT_CHR_F_READ_AUTHEN) || (m_properties & BLE_GATT_CHR_F_READ_AUTHOR) || (m_properties & BLE_GATT_CHR_F_READ_ENC);
+
+  for (auto &myPair : m_subscribedVec) {
+    uint16_t _mtu = getService()->getServer()->getPeerMTU(myPair.first);
+
+    // check if connected and subscribed
+    if (_mtu == 0 || myPair.second == 0) {
+      continue;
+    }
+
+    if (reqSec) {
+      struct ble_gap_conn_desc desc;
+      rc = ble_gap_conn_find(myPair.first, &desc);
+      if (rc != 0 || !desc.sec_state.encrypted) {
+        continue;
+      }
+    }
+
+    String value = getValue();
+    size_t length = value.length();
+
+    if (length > _mtu - 3) {
+      log_w("- Truncating to %d bytes (maximum notify size)", _mtu - 3);
+    }
+
+    if (is_notification && (!(myPair.second & NIMBLE_SUB_NOTIFY))) {
+      log_w("Sending notification to client subscribed to indications, sending indication instead");
+      is_notification = false;
+    }
+
+    if (!is_notification && (!(myPair.second & NIMBLE_SUB_INDICATE))) {
+      log_w("Sending indication to client subscribed to notification, sending notification instead");
+      is_notification = true;
+    }
+
+    if (!is_notification) {  // is indication
+      m_semaphoreConfEvt.take("indicate");
+    }
+
+    // don't create the m_buf until we are sure to send the data or else
+    // we could be allocating a buffer that doesn't get released.
+    // We also must create it in each loop iteration because it is consumed with each host call.
+    os_mbuf *om = ble_hs_mbuf_from_flat((uint8_t *)value.c_str(), length);
+
+    if (!is_notification && (m_properties & BLECharacteristic::PROPERTY_INDICATE)) {
+      if (!BLEDevice::getServer()->setIndicateWait(myPair.first)) {
+        log_e("prior Indication in progress");
+        os_mbuf_free_chain(om);
+        return;
+      }
+
+      rc = ble_gatts_indicate_custom(myPair.first, m_handle, om);
+      if (rc != 0) {
+        BLEDevice::getServer()->clearIndicateWait(myPair.first);
+      }
+    } else {
+      rc = ble_gatts_notify_custom(myPair.first, m_handle, om);
+    }
+
+    if (rc != 0) {
+      log_e("<< ble_gatts_%s_custom: rc=%d %s", is_notification ? "notify" : "indicate", rc, GeneralUtils::errorToString(rc));
+      m_semaphoreConfEvt.give();
+      m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_GATT, rc);  // Invoke the notify callback.
+      return;
+    }
+
+    if (!is_notification) {  // is indication
+      if (!m_semaphoreConfEvt.timedWait("indicate", indicationTimeout)) {
+        m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_TIMEOUT, 0);  // Invoke the notify callback.
+      } else {
+        auto code = m_semaphoreConfEvt.value();
+        if (code == ESP_OK) {
+          m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::SUCCESS_INDICATE, code);  // Invoke the notify callback.
+        } else {
+          m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_FAILURE, code);
+        }
+      }
+    } else {
+      m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::SUCCESS_NOTIFY, 0);  // Invoke the notify callback.
+    }
+  }
+  log_v("<< notify");
+}  // Notify
+
+void BLECharacteristicCallbacks::onRead(BLECharacteristic *pCharacteristic, ble_gap_conn_desc *desc) {
+  onRead(pCharacteristic);
+}  // onRead
+
+void BLECharacteristicCallbacks::onWrite(BLECharacteristic *pCharacteristic, ble_gap_conn_desc *desc) {
+  onWrite(pCharacteristic);
+}  // onWrite
+
+void BLECharacteristicCallbacks::onSubscribe(BLECharacteristic *pCharacteristic, ble_gap_conn_desc *desc, uint16_t subValue) {
+  log_d(">> onSubscribe: default");
+  log_d("<< onSubscribe");
+}  // onSubscribe
+
+#endif /* CONFIG_NIMBLE_ENABLED */
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLECharacteristic.h b/libraries/BLE/src/BLECharacteristic.h
index 29f105868fd..27df5a30c3e 100644
--- a/libraries/BLE/src/BLECharacteristic.h
+++ b/libraries/BLE/src/BLECharacteristic.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Jun 22, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLECHARACTERISTIC_H_
@@ -11,15 +15,59 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
 #include <string>
 #include <map>
 #include "BLEUUID.h"
-#include <esp_gatts_api.h>
-#include <esp_gap_ble_api.h>
 #include "BLEDescriptor.h"
 #include "BLEValue.h"
 #include "RTOS.h"
+#include "BLEUtils.h"
+
+/***************************************************************************
+ *                          Bluedroid includes                             *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gatts_api.h>
+#include <esp_gap_ble_api.h>
+#endif
+
+/***************************************************************************
+ *                     NimBLE includes and definitions                     *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <vector>
+#include <host/ble_gatt.h>
+#include <host/ble_att.h>
+#include "BLEConnInfo.h"
+#define ESP_GATT_MAX_ATTR_LEN            BLE_ATT_ATTR_MAX_LEN
+#define ESP_GATT_CHAR_PROP_BIT_READ      BLE_GATT_CHR_PROP_READ
+#define ESP_GATT_CHAR_PROP_BIT_WRITE     BLE_GATT_CHR_PROP_WRITE
+#define ESP_GATT_CHAR_PROP_BIT_WRITE_NR  BLE_GATT_CHR_PROP_WRITE_NO_RSP
+#define ESP_GATT_CHAR_PROP_BIT_BROADCAST BLE_GATT_CHR_PROP_BROADCAST
+#define ESP_GATT_CHAR_PROP_BIT_NOTIFY    BLE_GATT_CHR_PROP_NOTIFY
+#define ESP_GATT_CHAR_PROP_BIT_INDICATE  BLE_GATT_CHR_PROP_INDICATE
+#endif
+
+/***************************************************************************
+ *                              NimBLE types                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+typedef uint16_t esp_gatt_char_prop_t;
+typedef uint8_t esp_gatt_perm_t;
+#endif
+
+/***************************************************************************
+ *                           Forward declarations                          *
+ ***************************************************************************/
 
 class BLEService;
 class BLEDescriptor;
@@ -30,6 +78,10 @@ class BLECharacteristicCallbacks;
  */
 class BLEDescriptorMap {
 public:
+  /***************************************************************************
+   *                        Common public declarations                       *
+   ***************************************************************************/
+
   void setByUUID(const char *uuid, BLEDescriptor *pDescriptor);
   void setByUUID(BLEUUID uuid, BLEDescriptor *pDescriptor);
   void setByHandle(uint16_t handle, BLEDescriptor *pDescriptor);
@@ -37,11 +89,32 @@ class BLEDescriptorMap {
   BLEDescriptor *getByUUID(BLEUUID uuid);
   BLEDescriptor *getByHandle(uint16_t handle);
   String toString();
-  void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
   BLEDescriptor *getFirst();
   BLEDescriptor *getNext();
+  int getRegisteredDescriptorCount();
+  void removeDescriptor(BLEDescriptor *pDescriptor);
+
+  /***************************************************************************
+   *                        Bluedroid public declarations                    *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
+#endif
+
+  /***************************************************************************
+   *                        NimBLE public declarations                       *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  void handleGATTServerEvent(uint16_t conn_handle, uint16_t attr_handle, ble_gatt_access_ctxt *ctxt, void *arg);
+#endif
 
 private:
+  /***************************************************************************
+   *                        Common private properties                        *
+   ***************************************************************************/
+
   std::map<BLEDescriptor *, String> m_uuidMap;
   std::map<uint16_t, BLEDescriptor *> m_handleMap;
   std::map<BLEDescriptor *, String>::iterator m_iterator;
@@ -55,6 +128,48 @@ class BLEDescriptorMap {
  */
 class BLECharacteristic {
 public:
+  /***************************************************************************
+   *                        Common properties                                *
+   ***************************************************************************/
+
+  static const uint32_t indicationTimeout = 1000;
+
+  /***************************************************************************
+   *                    Bluedroid public properties                        *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  static const uint32_t PROPERTY_READ = 1 << 0;
+  static const uint32_t PROPERTY_WRITE = 1 << 1;
+  static const uint32_t PROPERTY_NOTIFY = 1 << 2;
+  static const uint32_t PROPERTY_BROADCAST = 1 << 3;
+  static const uint32_t PROPERTY_INDICATE = 1 << 4;
+  static const uint32_t PROPERTY_WRITE_NR = 1 << 5;
+#endif
+
+  /***************************************************************************
+   *                     NimBLE public properties                            *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  static const uint32_t PROPERTY_READ = BLE_GATT_CHR_F_READ;
+  static const uint32_t PROPERTY_READ_ENC = BLE_GATT_CHR_F_READ_ENC;
+  static const uint32_t PROPERTY_READ_AUTHEN = BLE_GATT_CHR_F_READ_AUTHEN;
+  static const uint32_t PROPERTY_READ_AUTHOR = BLE_GATT_CHR_F_READ_AUTHOR;
+  static const uint32_t PROPERTY_WRITE = BLE_GATT_CHR_F_WRITE;
+  static const uint32_t PROPERTY_WRITE_NR = BLE_GATT_CHR_F_WRITE_NO_RSP;
+  static const uint32_t PROPERTY_WRITE_ENC = BLE_GATT_CHR_F_WRITE_ENC;
+  static const uint32_t PROPERTY_WRITE_AUTHEN = BLE_GATT_CHR_F_WRITE_AUTHEN;
+  static const uint32_t PROPERTY_WRITE_AUTHOR = BLE_GATT_CHR_F_WRITE_AUTHOR;
+  static const uint32_t PROPERTY_BROADCAST = BLE_GATT_CHR_F_BROADCAST;
+  static const uint32_t PROPERTY_NOTIFY = BLE_GATT_CHR_F_NOTIFY;
+  static const uint32_t PROPERTY_INDICATE = BLE_GATT_CHR_F_INDICATE;
+#endif
+
+  /***************************************************************************
+   *                        Common public declarations                       *
+   ***************************************************************************/
+
   BLECharacteristic(const char *uuid, uint32_t properties = 0);
   BLECharacteristic(BLEUUID uuid, uint32_t properties = 0);
   virtual ~BLECharacteristic();
@@ -66,14 +181,9 @@ class BLECharacteristic {
   String getValue();
   uint8_t *getData();
   size_t getLength();
-
   void indicate();
   void notify(bool is_notification = true);
-  void setBroadcastProperty(bool value);
   void setCallbacks(BLECharacteristicCallbacks *pCallbacks);
-  void setIndicateProperty(bool value);
-  void setNotifyProperty(bool value);
-  void setReadProperty(bool value);
   void setValue(uint8_t *data, size_t size);
   void setValue(String value);
   void setValue(uint16_t &data16);
@@ -81,20 +191,16 @@ class BLECharacteristic {
   void setValue(int &data32);
   void setValue(float &data32);
   void setValue(double &data64);
-  void setWriteProperty(bool value);
-  void setWriteNoResponseProperty(bool value);
   String toString();
   uint16_t getHandle();
-  void setAccessPermissions(esp_gatt_perm_t perm);
-
-  static const uint32_t PROPERTY_READ = 1 << 0;
-  static const uint32_t PROPERTY_WRITE = 1 << 1;
-  static const uint32_t PROPERTY_NOTIFY = 1 << 2;
-  static const uint32_t PROPERTY_BROADCAST = 1 << 3;
-  static const uint32_t PROPERTY_INDICATE = 1 << 4;
-  static const uint32_t PROPERTY_WRITE_NR = 1 << 5;
-
-  static const uint32_t indicationTimeout = 1000;
+  void setAccessPermissions(uint8_t perm);
+  esp_gatt_char_prop_t getProperties();
+  void setReadProperty(bool value);
+  void setWriteProperty(bool value);
+  void setNotifyProperty(bool value);
+  void setBroadcastProperty(bool value);
+  void setIndicateProperty(bool value);
+  void setWriteNoResponseProperty(bool value);
 
 private:
   friend class BLEServer;
@@ -102,6 +208,10 @@ class BLECharacteristic {
   friend class BLEDescriptor;
   friend class BLECharacteristicMap;
 
+  /***************************************************************************
+   *                        Common private properties                        *
+   ***************************************************************************/
+
   BLEUUID m_bleUUID;
   BLEDescriptorMap m_descriptorMap;
   uint16_t m_handle;
@@ -109,18 +219,53 @@ class BLECharacteristic {
   BLECharacteristicCallbacks *m_pCallbacks;
   BLEService *m_pService;
   BLEValue m_value;
+  bool m_writeEvt = false;
+  FreeRTOS::Semaphore m_semaphoreConfEvt = FreeRTOS::Semaphore("ConfEvt");
+  FreeRTOS::Semaphore m_semaphoreSetValue = FreeRTOS::Semaphore("SetValue");
+
+  /***************************************************************************
+   *                        Bluedroid private properties                      *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt");
   esp_gatt_perm_t m_permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE;
-  bool m_writeEvt = false;  // If we have started a long write, this tells the commit code that we were the target
+#endif
 
-  void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
+  /***************************************************************************
+   *                        NimBLE private properties                        *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  portMUX_TYPE m_readMux;
+  uint8_t m_removed;
+  std::vector<std::pair<uint16_t, uint16_t>> m_subscribedVec;
+#endif
+
+  /***************************************************************************
+   *                        Common private declarations                      *
+   ***************************************************************************/
 
   void executeCreate(BLEService *pService);
-  esp_gatt_char_prop_t getProperties();
   BLEService *getService();
   void setHandle(uint16_t handle);
-  FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt");
-  FreeRTOS::Semaphore m_semaphoreConfEvt = FreeRTOS::Semaphore("ConfEvt");
-  FreeRTOS::Semaphore m_semaphoreSetValue = FreeRTOS::Semaphore("SetValue");
+
+  /***************************************************************************
+   *                        Bluedroid private declarations                    *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
+#endif
+
+  /***************************************************************************
+   *                        NimBLE private declarations                      *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  void setSubscribe(struct ble_gap_event *event);
+  static int handleGATTServerEvent(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt *ctxt, void *arg);
+#endif
 };  // BLECharacteristic
 
 /**
@@ -132,6 +277,10 @@ class BLECharacteristic {
  */
 class BLECharacteristicCallbacks {
 public:
+  /***************************************************************************
+   *                        Common public types                              *
+   ***************************************************************************/
+
   typedef enum {
     SUCCESS_INDICATE,
     SUCCESS_NOTIFY,
@@ -139,51 +288,41 @@ class BLECharacteristicCallbacks {
     ERROR_NOTIFY_DISABLED,
     ERROR_GATT,
     ERROR_NO_CLIENT,
+    ERROR_NO_SUBSCRIBER,
     ERROR_INDICATE_TIMEOUT,
     ERROR_INDICATE_FAILURE
   } Status;
 
-  virtual ~BLECharacteristicCallbacks();
+  /***************************************************************************
+   *                        Common public declarations                       *
+   ***************************************************************************/
 
-  /**
-	 * @brief Callback function to support a read request.
-	 * @param [in] pCharacteristic The characteristic that is the source of the event.
-	 * @param [in] param The BLE GATTS param. Use param->read.
-	 */
-  virtual void onRead(BLECharacteristic *pCharacteristic, esp_ble_gatts_cb_param_t *param);
-  /**
-	 * @brief DEPRECATED! Callback function to support a read request. Called only if onRead(,) is not overridden
-	 * @param [in] pCharacteristic The characteristic that is the source of the event.
-	 */
+  virtual ~BLECharacteristicCallbacks();
   virtual void onRead(BLECharacteristic *pCharacteristic);
+  virtual void onWrite(BLECharacteristic *pCharacteristic);
+  virtual void onNotify(BLECharacteristic *pCharacteristic);
+  virtual void onStatus(BLECharacteristic *pCharacteristic, Status s, uint32_t code);
 
-  /**
-	 * @brief Callback function to support a write request.
-	 * @param [in] pCharacteristic The characteristic that is the source of the event.
-	 * @param [in] param The BLE GATTS param. Use param->write.
-	 */
+  /***************************************************************************
+   *                        Bluedroid public declarations                    *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  virtual void onRead(BLECharacteristic *pCharacteristic, esp_ble_gatts_cb_param_t *param);
   virtual void onWrite(BLECharacteristic *pCharacteristic, esp_ble_gatts_cb_param_t *param);
-  /**
-	 * @brief DEPRECATED! Callback function to support a write request. Called only if onWrite(,) is not overridden.
-	 * @param [in] pCharacteristic The characteristic that is the source of the event.
-	 */
-  virtual void onWrite(BLECharacteristic *pCharacteristic);
+#endif
 
-  /**
-	 * @brief Callback function to support a Notify request.
-	 * @param [in] pCharacteristic The characteristic that is the source of the event.
-	 */
-  virtual void onNotify(BLECharacteristic *pCharacteristic);
+  /***************************************************************************
+   *                        NimBLE public declarations                       *
+   ***************************************************************************/
 
-  /**
-	 * @brief Callback function to support a Notify/Indicate Status report.
-	 * @param [in] pCharacteristic The characteristic that is the source of the event.
-	 * @param [in] s Status of the notification/indication
-	 * @param [in] code Additional code of underlying errors
-	 */
-  virtual void onStatus(BLECharacteristic *pCharacteristic, Status s, uint32_t code);
+#if defined(CONFIG_NIMBLE_ENABLED)
+  virtual void onRead(BLECharacteristic *pCharacteristic, ble_gap_conn_desc *desc);
+  virtual void onWrite(BLECharacteristic *pCharacteristic, ble_gap_conn_desc *desc);
+  virtual void onSubscribe(BLECharacteristic *pCharacteristic, ble_gap_conn_desc *desc, uint16_t subValue);
+#endif
 };
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLECHARACTERISTIC_H_ */
diff --git a/libraries/BLE/src/BLECharacteristicMap.cpp b/libraries/BLE/src/BLECharacteristicMap.cpp
index 6f2c0bb1154..ec3588bcde4 100644
--- a/libraries/BLE/src/BLECharacteristicMap.cpp
+++ b/libraries/BLE/src/BLECharacteristicMap.cpp
@@ -3,19 +3,34 @@
  *
  *  Created on: Jun 22, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
 #include <sstream>
 #include <iomanip>
 #include "BLEService.h"
+#include "BLEUtils.h"
 #ifdef ARDUINO_ARCH_ESP32
 #include "esp32-hal-log.h"
 #endif
 
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
+
 /**
  * @brief Return the characteristic by handle.
  * @param [in] handle The handle to look up the characteristic.
@@ -77,17 +92,22 @@ BLECharacteristic *BLECharacteristicMap::getNext() {
 }  // getNext
 
 /**
- * @brief Pass the GATT server event onwards to each of the characteristics found in the mapping
- * @param [in] event
- * @param [in] gatts_if
- * @param [in] param
+ * @brief Get the number of registered characteristics.
+ * @return The number of registered characteristics.
  */
-void BLECharacteristicMap::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) {
-  // Invoke the handler for every Service we have.
-  for (auto &myPair : m_uuidMap) {
-    myPair.first->handleGATTServerEvent(event, gatts_if, param);
-  }
-}  // handleGATTServerEvent
+int BLECharacteristicMap::getRegisteredCharacteristicCount() {
+  return m_uuidMap.size();
+}  // getRegisteredCharacteristicCount
+
+/**
+ * @brief Removes characteristic from maps.
+ * @param [in] characteristic The characteristic to remove.
+ * @return N/A.
+ */
+void BLECharacteristicMap::removeCharacteristic(BLECharacteristic *characteristic) {
+  m_handleMap.erase(characteristic->getHandle());
+  m_uuidMap.erase(characteristic);
+}  // removeCharacteristic
 
 /**
  * @brief Set the characteristic by handle.
@@ -130,5 +150,37 @@ String BLECharacteristicMap::toString() {
   return res;
 }  // toString
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+/***************************************************************************
+ *                           Bluedroid functions                           *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+/**
+ * @brief Pass the GATT server event onwards to each of the characteristics found in the mapping
+ * @param [in] event
+ * @param [in] gatts_if
+ * @param [in] param
+ */
+void BLECharacteristicMap::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) {
+  // Invoke the handler for every Service we have.
+  for (auto &myPair : m_uuidMap) {
+    myPair.first->handleGATTServerEvent(event, gatts_if, param);
+  }
+}  // handleGATTServerEvent
+#endif  // CONFIG_BLUEDROID_ENABLED
+
+/***************************************************************************
+ *                           NimBLE functions                              *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+void BLECharacteristicMap::handleGATTServerEvent(uint16_t conn_handle, uint16_t attr_handle, ble_gatt_access_ctxt *ctxt, void *arg) {
+  // Invoke the handler for every Service we have.
+  for (auto &myPair : m_uuidMap) {
+    myPair.first->handleGATTServerEvent(conn_handle, attr_handle, ctxt, arg);
+  }
+}
+#endif  // CONFIG_NIMBLE_ENABLED
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEClient.cpp b/libraries/BLE/src/BLEClient.cpp
index 29fa0fbc140..c101993d002 100644
--- a/libraries/BLE/src/BLEClient.cpp
+++ b/libraries/BLE/src/BLEClient.cpp
@@ -3,17 +3,23 @@
  *
  *  Created on: Mar 22, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
 #include <esp_bt.h>
-#include <esp_bt_main.h>
-#include <esp_gap_ble_api.h>
-#include <esp_gattc_api.h>
-#include <esp_gatt_common_api.h>  // ESP32 BLE
 #include "BLEClient.h"
 #include "BLEUtils.h"
 #include "BLEService.h"
@@ -24,6 +30,39 @@
 #include "BLEDevice.h"
 #include "esp32-hal-log.h"
 
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_bt_main.h>
+#include <esp_gap_ble_api.h>
+#include <esp_gattc_api.h>
+#include <esp_gatt_common_api.h>
+#endif
+
+/***************************************************************************
+ *                           NimBLE includes                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_hs.h>
+#include <host/ble_gap.h>
+#include <nimble/ble.h>
+#include <nimble/nimble_npl_os.h>
+#include <nimble/nimble_port.h>
+#endif
+
+/***************************************************************************
+ *                           Common global variables                       *
+ ***************************************************************************/
+
+static BLEClientCallbacks defaultCallbacks;
+
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
+
 /*
  * Design
  * ------
@@ -46,11 +85,30 @@
  */
 
 BLEClient::BLEClient() {
-  m_pClientCallbacks = nullptr;
+  m_pClientCallbacks = &defaultCallbacks;
   m_conn_id = ESP_GATT_IF_NONE;
-  m_gattc_if = ESP_GATT_IF_NONE;
   m_haveServices = false;
   m_isConnected = false;  // Initially, we are flagged as not connected.
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  m_gattc_if = ESP_GATT_IF_NONE;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  m_connectTimeout = 30000;
+  m_pTaskData = nullptr;
+  m_lastErr = 0;
+  m_terminateFailCount = 0;
+
+  m_pConnParams.scan_itvl = 16;                                             // Scan interval in 0.625ms units (NimBLE Default)
+  m_pConnParams.scan_window = 16;                                           // Scan window in 0.625ms units (NimBLE Default)
+  m_pConnParams.itvl_min = BLE_GAP_INITIAL_CONN_ITVL_MIN;                   // min_int = 0x10*1.25ms = 20ms
+  m_pConnParams.itvl_max = BLE_GAP_INITIAL_CONN_ITVL_MAX;                   // max_int = 0x20*1.25ms = 40ms
+  m_pConnParams.latency = BLE_GAP_INITIAL_CONN_LATENCY;                     // number of packets allowed to skip (extends max interval)
+  m_pConnParams.supervision_timeout = BLE_GAP_INITIAL_SUPERVISION_TIMEOUT;  // timeout = 400*10ms = 4000ms
+  m_pConnParams.min_ce_len = BLE_GAP_INITIAL_CONN_MIN_CE_LEN;               // Minimum length of connection event in 0.625ms units
+  m_pConnParams.max_ce_len = BLE_GAP_INITIAL_CONN_MAX_CE_LEN;               // Maximum length of connection event in 0.625ms units
+#endif
 }  // BLEClient
 
 /**
@@ -86,7 +144,7 @@ void BLEClient::clearServices() {
  */
 bool BLEClient::connect(BLEAdvertisedDevice *device) {
   BLEAddress address = device->getAddress();
-  esp_ble_addr_type_t type = device->getAddressType();
+  uint8_t type = device->getAddressType();
   return connect(address, type);
 }
 
@@ -95,10 +153,262 @@ bool BLEClient::connect(BLEAdvertisedDevice *device) {
  */
 bool BLEClient::connectTimeout(BLEAdvertisedDevice *device, uint32_t timeoutMs) {
   BLEAddress address = device->getAddress();
-  esp_ble_addr_type_t type = device->getAddressType();
+  uint8_t type = device->getAddressType();
   return connect(address, type, timeoutMs);
 }
 
+esp_gatt_if_t BLEClient::getGattcIf() {
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  return m_gattc_if;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  log_e("NimBLE does not support getGattcIf()");
+  return ESP_GATT_IF_NONE;
+#endif
+}  // getGattcIf
+
+/**
+ * @brief Initiate a secure connection (pair/bond) with the server.\n
+ * Called automatically when a characteristic or descriptor requires encryption or authentication to access it.
+ * @return True on success.
+ */
+bool BLEClient::secureConnection() {
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  log_i("secureConnection() does not need to be called for Bluedroid");
+  return true;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  int retryCount = 1;
+  BLETaskData taskData(const_cast<BLEClient *>(this), BLE_HS_ENOTCONN);
+  m_pTaskData = &taskData;
+
+  do {
+    if (BLESecurity::startSecurity(m_conn_id)) {
+      BLEUtils::taskWait(taskData, BLE_NPL_TIME_FOREVER);
+    }
+
+  } while (taskData.m_flags == (BLE_HS_ERR_HCI_BASE + BLE_ERR_PINKEY_MISSING) && retryCount--);
+
+  m_pTaskData = nullptr;
+
+  if (taskData.m_flags == 0) {
+    log_d("<< secureConnection: success");
+    return true;
+  }
+
+  m_lastErr = taskData.m_flags;
+  log_e("secureConnection: failed rc=%d", taskData.m_flags);
+  return false;
+#endif
+}  // secureConnection
+
+uint16_t BLEClient::getConnId() {
+  return m_conn_id;
+}  // getConnId
+
+/**
+ * @brief Retrieve the address of the peer.
+ *
+ * Returns the Bluetooth device address of the %BLE peer to which this client is connected.
+ */
+BLEAddress BLEClient::getPeerAddress() {
+  return m_peerAddress;
+}  // getAddress
+
+/**
+ * @brief Ask the BLE server for the RSSI value.
+ * @return The RSSI value.
+ */
+int BLEClient::getRssi() {
+  log_v(">> getRssi()");
+  if (!isConnected()) {
+    log_v("<< getRssi(): Not connected");
+    return 0;
+  }
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  // We make the API call to read the RSSI value which is an asynchronous operation.  We expect to receive
+  // an ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT to indicate completion.
+  //
+  m_semaphoreRssiCmplEvt.take("getRssi");
+  esp_err_t rc = ::esp_ble_gap_read_rssi(getPeerAddress().getNative());
+  if (rc != ESP_OK) {
+    log_e("<< getRssi: esp_ble_gap_read_rssi: rc=%d %s", rc, GeneralUtils::errorToString(rc));
+    return 0;
+  }
+  int rssiValue = m_semaphoreRssiCmplEvt.wait("getRssi");
+#endif  // CONFIG_BLUEDROID_ENABLED
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  int8_t rssiValue = 0;
+  int rc = ble_gap_conn_rssi(m_conn_id, &rssiValue);
+  if (rc != 0) {
+    log_e("<< getRssi: ble_gap_conn_rssi: rc=%d %s", rc, BLEUtils::returnCodeToString(rc));
+    return 0;
+  }
+#endif  // CONFIG_BLUEDROID_ENABLED
+  log_v("<< getRssi(): %d", rssiValue);
+  return rssiValue;
+}  // getRssi
+
+/**
+ * @brief Get the service BLE Remote Service instance corresponding to the uuid.
+ * @param [in] uuid The UUID of the service being sought.
+ * @return A reference to the Service or nullptr if don't know about it.
+ */
+BLERemoteService *BLEClient::getService(const char *uuid) {
+  return getService(BLEUUID(uuid));
+}  // getService
+
+/**
+ * @brief Get the service object corresponding to the uuid.
+ * @param [in] uuid The UUID of the service being sought.
+ * @return A reference to the Service or nullptr if don't know about it.
+ * @throws BLEUuidNotFound
+ */
+BLERemoteService *BLEClient::getService(BLEUUID uuid) {
+  log_v(">> getService: uuid: %s", uuid.toString().c_str());
+  // Design
+  // ------
+  // We wish to retrieve the service given its UUID.  It is possible that we have not yet asked the
+  // device what services it has in which case we have nothing to match against.  If we have not
+  // asked the device about its services, then we do that now.  Once we get the results we can then
+  // examine the services map to see if it has the service we are looking for.
+  if (!m_haveServices) {
+    getServices();
+  }
+  std::string uuidStr = uuid.toString().c_str();
+  for (auto &myPair : m_servicesMap) {
+    if (myPair.first == uuidStr) {
+      log_v("<< getService: found the service with uuid: %s", uuid.toString().c_str());
+      return myPair.second;
+    }
+  }  // End of each of the services.
+  log_v("<< getService: not found");
+  return nullptr;
+}  // getService
+
+/**
+ * @brief Get the value of a specific characteristic associated with a specific service.
+ * @param [in] serviceUUID The service that owns the characteristic.
+ * @param [in] characteristicUUID The characteristic whose value we wish to read.
+ * @throws BLEUuidNotFound
+ */
+String BLEClient::getValue(BLEUUID serviceUUID, BLEUUID characteristicUUID) {
+  log_v(">> getValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str());
+  String ret = getService(serviceUUID)->getCharacteristic(characteristicUUID)->readValue();
+  log_v("<<getValue");
+  return ret;
+}  // getValue
+
+/**
+ * @brief Are we connected to a partner?
+ * @return True if we are connected and false if we are not connected.
+ */
+bool BLEClient::isConnected() {
+  return m_isConnected;
+}  // isConnected
+
+/**
+ * @brief Set the callbacks that will be invoked.
+ */
+void BLEClient::setClientCallbacks(BLEClientCallbacks *pClientCallbacks) {
+  m_pClientCallbacks = pClientCallbacks;
+}  // setClientCallbacks
+
+/**
+ * @brief Set the value of a specific characteristic associated with a specific service.
+ * @param [in] serviceUUID The service that owns the characteristic.
+ * @param [in] characteristicUUID The characteristic whose value we wish to write.
+ * @throws BLEUuidNotFound
+ */
+void BLEClient::setValue(BLEUUID serviceUUID, BLEUUID characteristicUUID, String value) {
+  log_v(">> setValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str());
+  getService(serviceUUID)->getCharacteristic(characteristicUUID)->writeValue(value);
+  log_v("<< setValue");
+}  // setValue
+
+uint16_t BLEClient::getMTU() {
+#ifdef CONFIG_BLUEDROID_ENABLED
+  return m_mtu;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  return ble_att_mtu(m_conn_id);
+#endif
+}
+
+/**
+  @brief Set the local and remote MTU size.
+         Should be called once after client connects if MTU size needs to be changed.
+  @return bool indicating if MTU was successfully set locally and on remote.
+*/
+bool BLEClient::setMTU(uint16_t mtu) {
+  log_v(">> setMTU: %d", mtu);
+  esp_err_t err = ESP_OK;
+
+#ifdef CONFIG_BLUEDROID_ENABLED
+  err = esp_ble_gatt_set_local_mtu(mtu);  //First must set local MTU value.
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  err = ble_att_set_preferred_mtu(mtu);
+#endif
+
+  if (err == ESP_OK) {
+#ifdef CONFIG_BLUEDROID_ENABLED
+    err = esp_ble_gattc_send_mtu_req(m_gattc_if, m_conn_id);  //Once local is set successfully set remote size
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+    //err = ble_gattc_exchange_mtu(m_conn_id, nullptr, nullptr);
+#endif
+
+    if (err != ESP_OK) {
+      log_e("Error setting send MTU request MTU: %d err=%d", mtu, err);
+      return false;
+    }
+  } else {
+    log_e("can't set local mtu value: %d", mtu);
+    return false;
+  }
+  log_v("<< setMTU");
+
+  m_mtu = mtu;  //successfully changed
+
+  return true;
+}
+
+/**
+ * @brief Return a string representation of this client.
+ * @return A string representation of this client.
+ */
+String BLEClient::toString() {
+  String res = "peer address: " + m_peerAddress.toString();
+  res += "\nServices:\n";
+  for (auto &myPair : m_servicesMap) {
+    res += myPair.second->toString() + "\n";
+    // myPair.second is the value
+  }
+  return res;
+}  // toString
+
+void BLEClientCallbacks::onConnect(BLEClient *pClient) {
+  log_d("BLEClientCallbacks", "onConnect: default");
+}
+
+void BLEClientCallbacks::onDisconnect(BLEClient *pClient) {
+  log_d("BLEClientCallbacks", "onDisconnect: default");
+}
+
+/***************************************************************************
+ *                           Bluedroid functions                           *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+
 /**
  * @brief Connect to the partner (BLE Server).
  * @param [in] address The address of the partner.
@@ -106,7 +416,7 @@ bool BLEClient::connectTimeout(BLEAdvertisedDevice *device, uint32_t timeoutMs)
  * @param [in] timeoutMs The number of milliseconds to wait for the connection to complete.
  * @return True on success.
  */
-bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type, uint32_t timeoutMs) {
+bool BLEClient::connect(BLEAddress address, uint8_t type, uint32_t timeoutMs) {
   log_v(">> connect(%s)", address.toString().c_str());
 
   // We need the connection handle that we get from registering the application.  We register the app
@@ -141,9 +451,9 @@ bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type, uint32_t t
   m_semaphoreOpenEvt.take("connect");
   errRc = ::esp_ble_gattc_open(
     m_gattc_if,
-    *getPeerAddress().getNative(),  // address
-    type,                           // Note: This was added on 2018-04-03 when the latest ESP-IDF was detected to have changed the signature.
-    1                               // direct connection <-- maybe needs to be changed in case of direct indirect connection???
+    getPeerAddress().getNative(),  // address
+    (esp_ble_addr_type_t)type,     // Note: This was added on 2018-04-03 when the latest ESP-IDF was detected to have changed the signature.
+    1                              // direct connection <-- maybe needs to be changed in case of direct indirect connection???
   );
   if (errRc != ESP_OK) {
     log_e("esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
@@ -165,16 +475,17 @@ bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type, uint32_t t
 
 /**
  * @brief Disconnect from the peer.
- * @return N/A.
+ * @return error code from bluedroid, 0 = success.
  */
-void BLEClient::disconnect() {
+int BLEClient::disconnect(uint8_t reason) {
   log_v(">> disconnect()");
   esp_err_t errRc = ::esp_ble_gattc_close(getGattcIf(), getConnId());
   if (errRc != ESP_OK) {
     log_e("esp_ble_gattc_close: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-    return;
+    return errRc;
   }
   log_v("<< disconnect()");
+  return ESP_OK;
 }  // disconnect
 
 /**
@@ -361,89 +672,11 @@ void BLEClient::gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t
 
 }  // gattClientEventHandler
 
-uint16_t BLEClient::getConnId() {
-  return m_conn_id;
-}  // getConnId
-
-esp_gatt_if_t BLEClient::getGattcIf() {
-  return m_gattc_if;
-}  // getGattcIf
-
-/**
- * @brief Retrieve the address of the peer.
- *
- * Returns the Bluetooth device address of the %BLE peer to which this client is connected.
- */
-BLEAddress BLEClient::getPeerAddress() {
-  return m_peerAddress;
-}  // getAddress
-
 /**
- * @brief Ask the BLE server for the RSSI value.
- * @return The RSSI value.
- */
-int BLEClient::getRssi() {
-  log_v(">> getRssi()");
-  if (!isConnected()) {
-    log_v("<< getRssi(): Not connected");
-    return 0;
-  }
-  // We make the API call to read the RSSI value which is an asynchronous operation.  We expect to receive
-  // an ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT to indicate completion.
-  //
-  m_semaphoreRssiCmplEvt.take("getRssi");
-  esp_err_t rc = ::esp_ble_gap_read_rssi(*getPeerAddress().getNative());
-  if (rc != ESP_OK) {
-    log_e("<< getRssi: esp_ble_gap_read_rssi: rc=%d %s", rc, GeneralUtils::errorToString(rc));
-    return 0;
-  }
-  int rssiValue = m_semaphoreRssiCmplEvt.wait("getRssi");
-  log_v("<< getRssi(): %d", rssiValue);
-  return rssiValue;
-}  // getRssi
-
-/**
- * @brief Get the service BLE Remote Service instance corresponding to the uuid.
- * @param [in] uuid The UUID of the service being sought.
- * @return A reference to the Service or nullptr if don't know about it.
- */
-BLERemoteService *BLEClient::getService(const char *uuid) {
-  return getService(BLEUUID(uuid));
-}  // getService
-
-/**
- * @brief Get the service object corresponding to the uuid.
- * @param [in] uuid The UUID of the service being sought.
- * @return A reference to the Service or nullptr if don't know about it.
- * @throws BLEUuidNotFound
- */
-BLERemoteService *BLEClient::getService(BLEUUID uuid) {
-  log_v(">> getService: uuid: %s", uuid.toString().c_str());
-  // Design
-  // ------
-  // We wish to retrieve the service given its UUID.  It is possible that we have not yet asked the
-  // device what services it has in which case we have nothing to match against.  If we have not
-  // asked the device about its services, then we do that now.  Once we get the results we can then
-  // examine the services map to see if it has the service we are looking for.
-  if (!m_haveServices) {
-    getServices();
-  }
-  std::string uuidStr = uuid.toString().c_str();
-  for (auto &myPair : m_servicesMap) {
-    if (myPair.first == uuidStr) {
-      log_v("<< getService: found the service with uuid: %s", uuid.toString().c_str());
-      return myPair.second;
-    }
-  }  // End of each of the services.
-  log_v("<< getService: not found");
-  return nullptr;
-}  // getService
-
-/**
- * @brief Ask the remote %BLE server for its services.
- * A %BLE Server exposes a set of services for its partners.  Here we ask the server for its set of
- * services and wait until we have received them all.
- * @return N/A
+ * @brief Ask the remote %BLE server for its services.
+ * A %BLE Server exposes a set of services for its partners.  Here we ask the server for its set of
+ * services and wait until we have received them all.
+ * @return N/A
  */
 std::map<std::string, BLERemoteService *> *BLEClient::getServices() {
   /*
@@ -473,19 +706,6 @@ std::map<std::string, BLERemoteService *> *BLEClient::getServices() {
   return &m_servicesMap;
 }  // getServices
 
-/**
- * @brief Get the value of a specific characteristic associated with a specific service.
- * @param [in] serviceUUID The service that owns the characteristic.
- * @param [in] characteristicUUID The characteristic whose value we wish to read.
- * @throws BLEUuidNotFound
- */
-String BLEClient::getValue(BLEUUID serviceUUID, BLEUUID characteristicUUID) {
-  log_v(">> getValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str());
-  String ret = getService(serviceUUID)->getCharacteristic(characteristicUUID)->readValue();
-  log_v("<<getValue");
-  return ret;
-}  // getValue
-
 /**
  * @brief Handle a received GAP event.
  *
@@ -513,74 +733,543 @@ void BLEClient::handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_para
   }
 }  // handleGAPEvent
 
+#endif  // CONFIG_BLUEDROID_ENABLED
+
+/***************************************************************************
+ *                           NimBLE functions                              *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
 /**
- * @brief Are we connected to a partner?
- * @return True if we are connected and false if we are not connected.
+ * @brief If we have asked to disconnect and the event does not
+ * occur within the supervision timeout + added delay, this will
+ * be called to reset the host in the case of a stalled controller.
  */
-bool BLEClient::isConnected() {
-  return m_isConnected;
-}  // isConnected
+void BLEClient::dcTimerCb(ble_npl_event *event) {
+  ble_hs_sched_reset(BLE_HS_ECONTROLLER);
+}
 
 /**
- * @brief Set the callbacks that will be invoked.
+ * @brief Connect to the partner (BLE Server).
+ * @param [in] address The address of the partner.
+ * @param [in] type The type of the address.
+ * @param [in] timeoutMs The number of milliseconds to wait for the connection to complete.
+ * @return True on success.
  */
-void BLEClient::setClientCallbacks(BLEClientCallbacks *pClientCallbacks) {
-  m_pClientCallbacks = pClientCallbacks;
-}  // setClientCallbacks
+bool BLEClient::connect(BLEAddress address, uint8_t type, uint32_t timeoutMs) {
+  log_v(">> connect(%s)", address.toString().c_str());
+
+  if (!BLEDevice::m_synced) {
+    log_d("BLEClient", "Host reset, wait for sync.");
+    return false;
+  }
+
+  if (m_conn_id != BLE_HS_CONN_HANDLE_NONE || m_isConnected || m_pTaskData != nullptr) {
+    log_e("Client busy, connected to %s, id=%d", m_peerAddress.toString().c_str(), getConnId());
+    return false;
+  }
+
+  ble_addr_t peerAddr_t;
+  memcpy(&peerAddr_t.val, address.getNative(), 6);
+  peerAddr_t.type = address.getType();
+  if (ble_gap_conn_find_by_addr(&peerAddr_t, NULL) == 0) {
+    log_e("A connection to %s already exists", address.toString().c_str());
+    return false;
+  }
+
+  if (address == BLEAddress("")) {
+    log_e("Invalid peer address (NULL)");
+    return false;
+  }
+
+  m_appId = BLEDevice::m_appId++;
+  m_peerAddress = address;
+
+  int rc = 0;
+
+  /* Try to connect the the advertiser.  Allow 30 seconds (30000 ms) for
+   *  timeout (default value of m_connectTimeout).
+   *  Loop on BLE_HS_EBUSY if the scan hasn't stopped yet.
+   */
+  do {
+    rc = ble_gap_connect(BLEDevice::m_ownAddrType, &peerAddr_t, m_connectTimeout, &m_pConnParams, BLEClient::handleGAPEvent, this);
+    switch (rc) {
+      case 0: break;
+
+      case BLE_HS_EBUSY:
+        // Scan was still running, stop it and try again
+        if (!BLEDevice::getScan()->stop()) {
+          rc = BLE_HS_EUNKNOWN;
+        }
+        break;
+
+      case BLE_HS_EDONE:
+        // A connection to this device already exists, do not connect twice.
+        log_e("Already connected to device; addr=%s", m_peerAddress.toString().c_str());
+        break;
+
+      case BLE_HS_EALREADY:
+        // Already attempting to connect to this device, cancel the previous
+        // attempt and report failure here so we don't get 2 connections.
+        log_e("Already attempting to connect to %s - canceling", m_peerAddress.toString().c_str());
+        ble_gap_conn_cancel();
+        break;
+
+      default: log_e("Failed to connect to %s, rc=%d; %s", m_peerAddress.toString().c_str(), rc, BLEUtils::returnCodeToString(rc)); break;
+    }
+
+  } while (rc == BLE_HS_EBUSY);
+
+  if (rc != 0) {
+    m_lastErr = rc;
+    return false;
+  }
+
+  BLETaskData taskData(this);
+  m_pTaskData = &taskData;
+
+  // Wait for the connect timeout time +1 second for the connection to complete
+  if (!BLEUtils::taskWait(taskData, m_connectTimeout + 1000)) {
+    // If a connection was made but no response from MTU exchange proceed anyway
+    if (isConnected()) {
+      taskData.m_flags = 0;
+    } else {
+      // workaround; if the controller doesn't cancel the connection at the timeout, cancel it here.
+      log_e("Connect timeout - canceling");
+      ble_gap_conn_cancel();
+      taskData.m_flags = BLE_HS_ETIMEOUT;
+    }
+  }
+
+  m_pTaskData = nullptr;
+  rc = taskData.m_flags;
+
+  if (rc != 0) {
+    log_e("Connection failed; status=%d %s", rc, BLEUtils::returnCodeToString(rc));
+    m_lastErr = rc;
+    return false;
+  }
+
+  m_isConnected = true;
+  m_pClientCallbacks->onConnect(this);
+
+  log_i("<< connect()");
+
+  BLEDevice::addPeerDevice(this, true, m_appId);
+  // Check if still connected before returning
+  return isConnected();
+}
 
 /**
- * @brief Set the value of a specific characteristic associated with a specific service.
- * @param [in] serviceUUID The service that owns the characteristic.
- * @param [in] characteristicUUID The characteristic whose value we wish to write.
- * @throws BLEUuidNotFound
+ * @brief STATIC Callback for the service discovery API function.\n
+ * When a service is found or there is none left or there was an error
+ * the API will call this and report findings.
  */
-void BLEClient::setValue(BLEUUID serviceUUID, BLEUUID characteristicUUID, String value) {
-  log_v(">> setValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str());
-  getService(serviceUUID)->getCharacteristic(characteristicUUID)->writeValue(value);
-  log_v("<< setValue");
-}  // setValue
+int BLEClient::serviceDiscoveredCB(uint16_t conn_handle, const struct ble_gatt_error *error, const struct ble_gatt_svc *service, void *arg) {
+  log_d("Service Discovered >> status: %d handle: %d", error->status, (error->status == 0) ? service->start_handle : -1);
 
-uint16_t BLEClient::getMTU() {
-  return m_mtu;
+  BLETaskData *pTaskData = (BLETaskData *)arg;
+  BLEClient *client = (BLEClient *)pTaskData->m_pInstance;
+
+  if (error->status == BLE_HS_ENOTCONN) {
+    log_e("<< Service Discovered; Disconnected");
+    BLEUtils::taskRelease(*pTaskData, error->status);
+    return error->status;
+  }
+
+  // Make sure the service discovery is for this device
+  if (client->getConnId() != conn_handle) {
+    return 0;
+  }
+
+  if (error->status == 0) {
+    // Found a service - add it to the vector
+    BLERemoteService *pRemoteService = new BLERemoteService(client, service);
+    client->m_servicesMap.insert(std::pair<std::string, BLERemoteService *>(pRemoteService->getUUID().toString().c_str(), pRemoteService));
+    client->m_servicesMapByInstID.insert(std::pair<BLERemoteService *, uint16_t>(pRemoteService, service->start_handle));
+    return 0;
+  }
+
+  BLEUtils::taskRelease(*pTaskData, error->status);
+  log_d("<< Service Discovered");
+  return error->status;
 }
 
+std::map<std::string, BLERemoteService *> *BLEClient::getServices() {
+  log_v(">> getServices");
+
+  clearServices();  // Clear any services that may exist.
+
+  if (!isConnected()) {
+    log_e("Disconnected, could not retrieve services -aborting");
+    return &m_servicesMap;
+  }
+
+  int errRc = 0;
+  BLETaskData taskData(this);
+
+  errRc = ble_gattc_disc_all_svcs(m_conn_id, BLEClient::serviceDiscoveredCB, &taskData);
+
+  if (errRc != 0) {
+    log_e("ble_gattc_disc_all_svcs: rc=%d %s", errRc, BLEUtils::returnCodeToString(errRc));
+    m_lastErr = errRc;
+    return &m_servicesMap;
+  }
+
+  BLEUtils::taskWait(taskData, BLE_NPL_TIME_FOREVER);
+  errRc = taskData.m_flags;
+  if (errRc == 0 || errRc == BLE_HS_EDONE) {
+    // If successful, remember that we now have services.
+    m_haveServices = m_servicesMap.size() > 0;
+    log_v("<< getServices");
+    return &m_servicesMap;
+  }
+
+  m_lastErr = errRc;
+  log_e("Could not retrieve services, rc=%d %s", errRc, BLEUtils::returnCodeToString(errRc));
+  return &m_servicesMap;
+}  // getServices
+
+int BLEClient::handleGAPEvent(struct ble_gap_event *event, void *arg) {
+  BLEClient *client = (BLEClient *)arg;
+  int rc = 0;
+  BLETaskData *pTaskData = client->m_pTaskData;
+
+  log_d("BLEClient", "Got Client event %s", BLEUtils::gapEventToString(event->type));
+
+  switch (event->type) {
+    case BLE_GAP_EVENT_DISCONNECT:
+    {
+      rc = event->disconnect.reason;
+      // If Host reset tell the device now before returning to prevent
+      // any errors caused by calling host functions before resyncing.
+      switch (rc) {
+        case BLE_HS_ECONTROLLER:
+        case BLE_HS_ETIMEOUT_HCI:
+        case BLE_HS_ENOTSYNCED:
+        case BLE_HS_EOS:
+          log_e("BLEClient", "Disconnect - host reset, rc=%d", rc);
+          BLEDevice::onReset(rc);
+          break;
+        default:
+          // Check that the event is for this client.
+          if (client->m_conn_id != event->disconnect.conn.conn_handle) {
+            return 0;
+          }
+          break;
+      }
+
+      // Remove the device from ignore list so we will scan it again
+      // BLEDevice::removeIgnored(client->m_peerAddress);
+
+      // No longer connected, clear the connection ID.
+      client->m_conn_id = BLE_HS_CONN_HANDLE_NONE;
+      client->m_terminateFailCount = 0;
+
+      // If we received a connected event but did not get established (no PDU)
+      // then a disconnect event will be sent but we should not send it to the
+      // app for processing. Instead we will ensure the task is released
+      // and report the error.
+      if (!client->m_isConnected) {
+        break;
+      }
+
+      log_i("BLEClient", "disconnect; reason=%d, %s", rc, BLEUtils::returnCodeToString(rc));
+
+      BLEDevice::removePeerDevice(client->m_appId, true);
+      client->m_isConnected = false;
+      if (client->m_pClientCallbacks != nullptr) {
+        client->m_pClientCallbacks->onDisconnect(client);
+      }
+      break;
+    }  // BLE_GAP_EVENT_DISCONNECT
+
+    case BLE_GAP_EVENT_CONNECT:
+    {
+      // If we aren't waiting for this connection response
+      // we should drop the connection immediately.
+      if (client->isConnected() || client->m_pTaskData == nullptr) {
+        ble_gap_terminate(event->connect.conn_handle, BLE_ERR_REM_USER_CONN_TERM);
+        return 0;
+      }
+
+      rc = event->connect.status;
+      if (rc == 0) {
+        log_i("BLEClient: Connected event. Handle: %d", event->connect.conn_handle);
+
+        client->m_conn_id = event->connect.conn_handle;
+
+        rc = ble_gattc_exchange_mtu(client->m_conn_id, nullptr, nullptr);
+        if (rc != 0) {
+          log_e("BLEClient", "MTU exchange error; rc=%d %s", rc, BLEUtils::returnCodeToString(rc));
+          break;
+        }
+
+        // In the case of a multiconnecting device we ignore this device when
+        // scanning since we are already connected to it
+        // BLEDevice::addIgnored(client->m_peerAddress);
+      } else {
+        client->m_conn_id = BLE_HS_CONN_HANDLE_NONE;
+        break;
+      }
+
+      return 0;
+    }  // BLE_GAP_EVENT_CONNECT
+
+    case BLE_GAP_EVENT_TERM_FAILURE:
+    {
+      if (client->m_conn_id != event->term_failure.conn_handle) {
+        return 0;
+      }
+
+      log_e("Connection termination failure; rc=%d - retrying", event->term_failure.status);
+      if (++client->m_terminateFailCount > 2) {
+        ble_hs_sched_reset(BLE_HS_ECONTROLLER);
+      } else {
+        ble_gap_terminate(event->term_failure.conn_handle, BLE_ERR_REM_USER_CONN_TERM);
+      }
+      return 0;
+    }  // BLE_GAP_EVENT_TERM_FAILURE
+
+    case BLE_GAP_EVENT_NOTIFY_RX:
+    {
+      if (client->m_conn_id != event->notify_rx.conn_handle) {
+        return 0;
+      }
+
+      // If a notification comes before this flag is set we might
+      // access a vector while it is being cleared in connect()
+      if (!client->m_isConnected) {
+        return 0;
+      }
+
+      log_d("BLEClient", "Notify received for handle: %d", event->notify_rx.attr_handle);
+
+      for (auto &myPair : client->m_servicesMap) {
+        // Dont waste cycles searching services without this handle in its range
+        if (myPair.second->getEndHandle() < event->notify_rx.attr_handle) {
+          continue;
+        }
+
+        auto cMap = &myPair.second->m_characteristicMap;
+        log_d("BLEClient", "checking service %s for handle: %d", myPair.second->getUUID().toString().c_str(), event->notify_rx.attr_handle);
+
+        auto characteristic = cMap->cbegin();
+        for (; characteristic != cMap->cend(); ++characteristic) {
+          if (characteristic->second->m_handle == event->notify_rx.attr_handle) {
+            break;
+          }
+        }
+
+        if (characteristic != cMap->cend()) {
+          log_d("BLEClient", "Got Notification for characteristic %s", characteristic->second->toString().c_str());
+
+          characteristic->second->m_semaphoreReadCharEvt.take();
+          characteristic->second->m_value = String((char *)event->notify_rx.om->om_data, event->notify_rx.om->om_len);
+          characteristic->second->m_semaphoreReadCharEvt.give();
+
+          if (characteristic->second->m_notifyCallback != nullptr) {
+            log_d("Invoking callback for notification on characteristic %s", characteristic->second->toString().c_str());
+            characteristic->second->m_notifyCallback(
+              characteristic->second, event->notify_rx.om->om_data, event->notify_rx.om->om_len, !event->notify_rx.indication
+            );
+          }
+          break;
+        }
+      }
+
+      return 0;
+    }  // BLE_GAP_EVENT_NOTIFY_RX
+
+    case BLE_GAP_EVENT_CONN_UPDATE_REQ:
+    case BLE_GAP_EVENT_L2CAP_UPDATE_REQ:
+    {
+      if (client->m_conn_id != event->conn_update_req.conn_handle) {
+        return 0;
+      }
+      log_d("Peer requesting to update connection parameters");
+      log_d(
+        "MinInterval: %d, MaxInterval: %d, Latency: %d, Timeout: %d", event->conn_update_req.peer_params->itvl_min,
+        event->conn_update_req.peer_params->itvl_max, event->conn_update_req.peer_params->latency, event->conn_update_req.peer_params->supervision_timeout
+      );
+
+      rc = client->m_pClientCallbacks->onConnParamsUpdateRequest(client, event->conn_update_req.peer_params) ? 0 : BLE_ERR_CONN_PARMS;
+
+      if (!rc && event->type == BLE_GAP_EVENT_CONN_UPDATE_REQ) {
+        event->conn_update_req.self_params->itvl_min = client->m_pConnParams.itvl_min;
+        event->conn_update_req.self_params->itvl_max = client->m_pConnParams.itvl_max;
+        event->conn_update_req.self_params->latency = client->m_pConnParams.latency;
+        event->conn_update_req.self_params->supervision_timeout = client->m_pConnParams.supervision_timeout;
+      }
+
+      log_d("%s peer params", (rc == 0) ? "Accepted" : "Rejected");
+      return rc;
+    }  // BLE_GAP_EVENT_CONN_UPDATE_REQ, BLE_GAP_EVENT_L2CAP_UPDATE_REQ
+
+    case BLE_GAP_EVENT_CONN_UPDATE:
+    {
+      if (client->m_conn_id != event->conn_update.conn_handle) {
+        return 0;
+      }
+      if (event->conn_update.status == 0) {
+        log_i("Connection parameters updated.");
+      } else {
+        log_e("Update connection parameters failed.");
+      }
+      return 0;
+    }  // BLE_GAP_EVENT_CONN_UPDATE
+
+    case BLE_GAP_EVENT_ENC_CHANGE:
+    {
+      if (client->m_conn_id != event->enc_change.conn_handle) {
+        return 0;
+      }
+
+      if (event->enc_change.status == 0 || event->enc_change.status == (BLE_HS_ERR_HCI_BASE + BLE_ERR_PINKEY_MISSING)) {
+        struct ble_gap_conn_desc desc;
+        rc = ble_gap_conn_find(event->enc_change.conn_handle, &desc);
+        assert(rc == 0);
+
+        if (event->enc_change.status == (BLE_HS_ERR_HCI_BASE + BLE_ERR_PINKEY_MISSING)) {
+          // Key is missing, try deleting.
+          ble_store_util_delete_peer(&desc.peer_id_addr);
+        } else if (BLEDevice::m_securityCallbacks != nullptr) {
+          BLEDevice::m_securityCallbacks->onAuthenticationComplete(&desc);
+        } else {
+          client->m_pClientCallbacks->onAuthenticationComplete(&desc);
+        }
+      }
+
+      rc = event->enc_change.status;
+      break;
+    }  //BLE_GAP_EVENT_ENC_CHANGE
+
+    case BLE_GAP_EVENT_MTU:
+    {
+      if (client->m_conn_id != event->mtu.conn_handle) {
+        return 0;
+      }
+      log_i("mtu update event; conn_handle=%d mtu=%d", event->mtu.conn_handle, event->mtu.value);
+      rc = 0;
+      break;
+    }  // BLE_GAP_EVENT_MTU
+
+    case BLE_GAP_EVENT_PASSKEY_ACTION:
+    {
+      struct ble_sm_io pkey = {0, 0};
+
+      if (client->m_conn_id != event->passkey.conn_handle) {
+        return 0;
+      }
+
+      if (event->passkey.params.action == BLE_SM_IOACT_DISP) {
+        pkey.action = event->passkey.params.action;
+        pkey.passkey = BLESecurity::m_passkey;  // This is the passkey to be entered on peer
+        rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
+        log_d("ble_sm_inject_io result: %d", rc);
+
+      } else if (event->passkey.params.action == BLE_SM_IOACT_NUMCMP) {
+        log_d("Passkey on device's display: %d", event->passkey.params.numcmp);
+        pkey.action = event->passkey.params.action;
+        // Compatibility only - Do not use, should be removed the in future
+        if (BLEDevice::m_securityCallbacks != nullptr) {
+          pkey.numcmp_accept = BLEDevice::m_securityCallbacks->onConfirmPIN(event->passkey.params.numcmp);
+          ////////////////////////////////////////////////////
+        } else {
+          pkey.numcmp_accept = client->m_pClientCallbacks->onConfirmPIN(event->passkey.params.numcmp);
+        }
+
+        rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
+        log_d("ble_sm_inject_io result: %d", rc);
+
+        //TODO: Handle out of band pairing
+      } else if (event->passkey.params.action == BLE_SM_IOACT_OOB) {
+        static uint8_t tem_oob[16] = {0};
+        pkey.action = event->passkey.params.action;
+        for (int i = 0; i < 16; i++) {
+          pkey.oob[i] = tem_oob[i];
+        }
+        rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
+        log_d("ble_sm_inject_io result: %d", rc);
+        ////////
+      } else if (event->passkey.params.action == BLE_SM_IOACT_INPUT) {
+        log_d("Enter the passkey");
+        pkey.action = event->passkey.params.action;
+
+        // Compatibility only - Do not use, should be removed the in future
+        if (BLEDevice::m_securityCallbacks != nullptr) {
+          pkey.passkey = BLEDevice::m_securityCallbacks->onPassKeyRequest();
+          /////////////////////////////////////////////
+        } else {
+          pkey.passkey = client->m_pClientCallbacks->onPassKeyRequest();
+        }
+
+        rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
+        log_d("ble_sm_inject_io result: %d", rc);
+
+      } else if (event->passkey.params.action == BLE_SM_IOACT_NONE) {
+        log_d("No passkey action required");
+      }
+
+      return 0;
+    }  // BLE_GAP_EVENT_PASSKEY_ACTION
+
+    default:
+    {
+      return 0;
+    }
+  }  // Switch
+
+  if (pTaskData != nullptr) {
+    BLEUtils::taskRelease(*pTaskData, rc);
+  }
+
+  return 0;
+}  // handleGAPEvent
+
 /**
-  @brief Set the local and remote MTU size.
-         Should be called once after client connects if MTU size needs to be changed.
-  @return bool indicating if MTU was successfully set locally and on remote.
-*/
-bool BLEClient::setMTU(uint16_t mtu) {
-  esp_err_t err = esp_ble_gatt_set_local_mtu(mtu);  //First must set local MTU value.
-  if (err == ESP_OK) {
-    err = esp_ble_gattc_send_mtu_req(m_gattc_if, m_conn_id);  //Once local is set successfully set remote size
-    if (err != ESP_OK) {
-      log_e("Error setting send MTU request MTU: %d err=%d", mtu, err);
-      return false;
+ * @brief Disconnect from the peer.
+ * @return Error code from NimBLE stack, 0 = success.
+ */
+int BLEClient::disconnect(uint8_t reason) {
+  log_d(">> disconnect()");
+  int rc = 0;
+
+  if (isConnected()) {
+    rc = ble_gap_terminate(m_conn_id, reason);
+    if (rc != 0 && rc != BLE_HS_ENOTCONN && rc != BLE_HS_EALREADY) {
+      m_lastErr = rc;
+      log_e("ble_gap_terminate failed: rc=%d %s", rc, BLEUtils::returnCodeToString(rc));
     }
   } else {
-    log_e("can't set local mtu value: %d", mtu);
-    return false;
+    log_d("Not connected to any peers");
   }
-  log_v("<< setLocalMTU");
 
-  m_mtu = mtu;  //successfully changed
+  log_d("<< disconnect()");
+  return rc;
+}  // disconnect
 
+bool BLEClientCallbacks::onConnParamsUpdateRequest(BLEClient *pClient, const ble_gap_upd_params *params) {
+  log_d("BLEClientCallbacks", "onConnParamsUpdateRequest: default");
   return true;
 }
 
-/**
- * @brief Return a string representation of this client.
- * @return A string representation of this client.
- */
-String BLEClient::toString() {
-  String res = "peer address: " + m_peerAddress.toString();
-  res += "\nServices:\n";
-  for (auto &myPair : m_servicesMap) {
-    res += myPair.second->toString() + "\n";
-    // myPair.second is the value
-  }
-  return res;
-}  // toString
+uint32_t BLEClientCallbacks::onPassKeyRequest() {
+  log_d("onPassKeyRequest: default: 123456");
+  return 123456;
+}
+
+void BLEClientCallbacks::onAuthenticationComplete(ble_gap_conn_desc *desc) {
+  log_d("onAuthenticationComplete: default");
+}
+
+bool BLEClientCallbacks::onConfirmPIN(uint32_t pin) {
+  log_d("onConfirmPIN: default: true");
+  return true;
+}
+
+#endif  // CONFIG_NIMBLE_ENABLED
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEClient.h b/libraries/BLE/src/BLEClient.h
index ddb932fcd95..97ef72f4917 100644
--- a/libraries/BLE/src/BLEClient.h
+++ b/libraries/BLE/src/BLEClient.h
@@ -1,66 +1,128 @@
 /*
- * BLEDevice.h
+ * BLEClient.h
  *
  *  Created on: Mar 22, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
-#ifndef MAIN_BLEDEVICE_H_
-#define MAIN_BLEDEVICE_H_
+#ifndef MAIN_BLECLIENT_H_
+#define MAIN_BLECLIENT_H_
 
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
-#include <esp_gattc_api.h>
 #include <string.h>
 #include <map>
 #include <string>
-//#include "BLEExceptions.h"
 #include "BLERemoteService.h"
 #include "BLEService.h"
 #include "BLEAddress.h"
 #include "BLEAdvertisedDevice.h"
+#include "BLEUtils.h"
+
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gattc_api.h>
+#ifndef BLE_ERR_REM_USER_CONN_TERM
+#define BLE_ERR_REM_USER_CONN_TERM 0x13
+#endif
+#endif
+
+/***************************************************************************
+ *                     NimBLE includes and definitions                     *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <nimble/ble.h>
+#include <host/ble_hs.h>
+#include <nimble/nimble_port.h>
+#define ESP_GATT_IF_NONE BLE_HS_CONN_HANDLE_NONE
+#endif
+
+/***************************************************************************
+ *                              NimBLE types                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+typedef uint16_t esp_gatt_if_t;
+#endif
+
+/***************************************************************************
+ *                           Forward declarations                          *
+ ***************************************************************************/
 
 class BLERemoteService;
 class BLEClientCallbacks;
 class BLEAdvertisedDevice;
+struct BLETaskData;
 
 /**
  * @brief A model of a %BLE client.
  */
 class BLEClient {
 public:
+  /***************************************************************************
+   *                            Common public properties                     *
+   ***************************************************************************/
+
+  uint16_t m_appId;
+
+  /***************************************************************************
+   *                           Common public declarations                    *
+   ***************************************************************************/
+
   BLEClient();
   ~BLEClient();
-
   bool connect(BLEAdvertisedDevice *device);
   bool connectTimeout(BLEAdvertisedDevice *device, uint32_t timeoutMS = portMAX_DELAY);
-  bool connect(BLEAddress address, esp_ble_addr_type_t type = BLE_ADDR_TYPE_PUBLIC, uint32_t timeoutMS = portMAX_DELAY);  // Connect to the remote BLE Server
-  void disconnect();                                                 // Disconnect from the remote BLE Server
-  BLEAddress getPeerAddress();                                       // Get the address of the remote BLE Server
-  int getRssi();                                                     // Get the RSSI of the remote BLE Server
-  std::map<std::string, BLERemoteService *> *getServices();          // Get a map of the services offered by the remote BLE Server
-  BLERemoteService *getService(const char *uuid);                    // Get a reference to a specified service offered by the remote BLE server.
-  BLERemoteService *getService(BLEUUID uuid);                        // Get a reference to a specified service offered by the remote BLE server.
-  String getValue(BLEUUID serviceUUID, BLEUUID characteristicUUID);  // Get the value of a given characteristic at a given service.
-
-  void handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
-
-  bool isConnected();  // Return true if we are connected.
-
+  bool connect(BLEAddress address, uint8_t type = 0, uint32_t timeoutMS = portMAX_DELAY);
+  bool secureConnection();
+  int disconnect(uint8_t reason = BLE_ERR_REM_USER_CONN_TERM);
+  BLEAddress getPeerAddress();
+  int getRssi();
+  std::map<std::string, BLERemoteService *> *getServices();
+  BLERemoteService *getService(const char *uuid);
+  BLERemoteService *getService(BLEUUID uuid);
+  String getValue(BLEUUID serviceUUID, BLEUUID characteristicUUID);
+  bool isConnected();
   void setClientCallbacks(BLEClientCallbacks *pClientCallbacks);
-  void setValue(BLEUUID serviceUUID, BLEUUID characteristicUUID, String value);  // Set the value of a given characteristic at a given service.
-
-  String toString();  // Return a string representation of this client.
+  void setValue(BLEUUID serviceUUID, BLEUUID characteristicUUID, String value);
+  String toString();
   uint16_t getConnId();
   esp_gatt_if_t getGattcIf();
   uint16_t getMTU();
   bool setMTU(uint16_t mtu);
 
-  uint16_t m_appId;
+  /***************************************************************************
+   *                           Bluedroid public declarations                 *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  void handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
+#endif
+
+  /***************************************************************************
+   *                           NimBLE public declarations                    *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  static int handleGAPEvent(struct ble_gap_event *event, void *arg);
+  static int serviceDiscoveredCB(uint16_t conn_handle, const struct ble_gatt_error *error, const struct ble_gatt_svc *service, void *arg);
+#endif
 
 private:
   friend class BLEDevice;
@@ -68,15 +130,14 @@ class BLEClient {
   friend class BLERemoteCharacteristic;
   friend class BLERemoteDescriptor;
 
-  void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
+  /***************************************************************************
+   *                           Common private properties                     *
+   ***************************************************************************/
 
-  BLEAddress m_peerAddress = BLEAddress((uint8_t *)"\0\0\0\0\0\0");  // The BD address of the remote server.
+  BLEAddress m_peerAddress = BLEAddress((uint8_t *)"\0\0\0\0\0\0");
   uint16_t m_conn_id;
-  //  int           m_deviceType;
-  esp_gatt_if_t m_gattc_if;
-  bool m_haveServices = false;  // Have we previously obtain the set of services from the remote server.
-  bool m_isConnected = false;   // Are we currently connected.
-
+  bool m_haveServices = false;
+  bool m_isConnected = false;
   BLEClientCallbacks *m_pClientCallbacks;
   FreeRTOS::Semaphore m_semaphoreRegEvt = FreeRTOS::Semaphore("RegEvt");
   FreeRTOS::Semaphore m_semaphoreOpenEvt = FreeRTOS::Semaphore("OpenEvt");
@@ -84,20 +145,76 @@ class BLEClient {
   FreeRTOS::Semaphore m_semaphoreRssiCmplEvt = FreeRTOS::Semaphore("RssiCmplEvt");
   std::map<std::string, BLERemoteService *> m_servicesMap;
   std::map<BLERemoteService *, uint16_t> m_servicesMapByInstID;
-  void clearServices();  // Clear any existing services.
   uint16_t m_mtu = 23;
-};  // class BLEDevice
+
+  /***************************************************************************
+   *                           Bluedroid private properties                  *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  esp_gatt_if_t m_gattc_if;
+#endif
+
+  /***************************************************************************
+   *                           NimBLE private properties                     *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  int m_lastErr;
+  int32_t m_connectTimeout;
+  uint8_t m_terminateFailCount;
+  ble_gap_conn_params m_pConnParams;
+  mutable BLETaskData *m_pTaskData;
+#endif
+
+  /***************************************************************************
+   *                           Common private declarations                   *
+   ***************************************************************************/
+
+  void clearServices();
+
+  /***************************************************************************
+   *                          Bluedroid private declarations                 *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
+#endif
+
+  /***************************************************************************
+   *                           NimBLE private declarations                   *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  static void dcTimerCb(ble_npl_event *event);
+#endif
+};  // class BLEClient
 
 /**
  * @brief Callbacks associated with a %BLE client.
  */
 class BLEClientCallbacks {
 public:
+  /***************************************************************************
+   *                           Common public declarations                    *
+   ***************************************************************************/
+
   virtual ~BLEClientCallbacks(){};
-  virtual void onConnect(BLEClient *pClient) = 0;
-  virtual void onDisconnect(BLEClient *pClient) = 0;
+  virtual void onConnect(BLEClient *pClient);
+  virtual void onDisconnect(BLEClient *pClient);
+
+  /***************************************************************************
+   *                           NimBLE public declarations                    *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  virtual bool onConnParamsUpdateRequest(BLEClient *pClient, const ble_gap_upd_params *params);
+  virtual uint32_t onPassKeyRequest();
+  virtual void onAuthenticationComplete(ble_gap_conn_desc *desc);
+  virtual bool onConfirmPIN(uint32_t pin);
+#endif
 };
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
-#endif /* MAIN_BLEDEVICE_H_ */
+#endif /* MAIN_BLECLIENT_H_ */
diff --git a/libraries/BLE/src/BLEConnInfo.h b/libraries/BLE/src/BLEConnInfo.h
new file mode 100644
index 00000000000..b81ab93c28f
--- /dev/null
+++ b/libraries/BLE/src/BLEConnInfo.h
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
+ * esp-nimble-cpp, NimBLE-Arduino contributors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef BLECONNINFO_H_
+#define BLECONNINFO_H_
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
+#include <host/ble_gap.h>
+#include "BLEAddress.h"
+
+/**
+ * @brief Connection information.
+ */
+class BLEConnInfo {
+public:
+  /** @brief Gets the over-the-air address of the connected peer */
+  BLEAddress getAddress() const {
+    return BLEAddress(m_desc.peer_ota_addr);
+  }
+
+  /** @brief Gets the ID address of the connected peer */
+  BLEAddress getIdAddress() const {
+    return BLEAddress(m_desc.peer_id_addr);
+  }
+
+  /** @brief Gets the connection handle (also known as the connection id) of the connected peer */
+  uint16_t getConnHandle() const {
+    return m_desc.conn_handle;
+  }
+
+  /** @brief Gets the connection interval for this connection (in 1.25ms units) */
+  uint16_t getConnInterval() const {
+    return m_desc.conn_itvl;
+  }
+
+  /** @brief Gets the supervision timeout for this connection (in 10ms units) */
+  uint16_t getConnTimeout() const {
+    return m_desc.supervision_timeout;
+  }
+
+  /** @brief Gets the allowable latency for this connection (unit = number of intervals) */
+  uint16_t getConnLatency() const {
+    return m_desc.conn_latency;
+  }
+
+  /** @brief Gets the maximum transmission unit size for this connection (in bytes) */
+  uint16_t getMTU() const {
+    return ble_att_mtu(m_desc.conn_handle);
+  }
+
+  /** @brief Check if we are in the master role in this connection */
+  bool isMaster() const {
+    return (m_desc.role == BLE_GAP_ROLE_MASTER);
+  }
+
+  /** @brief Check if we are in the slave role in this connection */
+  bool isSlave() const {
+    return (m_desc.role == BLE_GAP_ROLE_SLAVE);
+  }
+
+  /** @brief Check if we are connected to a bonded peer */
+  bool isBonded() const {
+    return (m_desc.sec_state.bonded == 1);
+  }
+
+  /** @brief Check if the connection in encrypted */
+  bool isEncrypted() const {
+    return (m_desc.sec_state.encrypted == 1);
+  }
+
+  /** @brief Check if the the connection has been authenticated */
+  bool isAuthenticated() const {
+    return (m_desc.sec_state.authenticated == 1);
+  }
+
+  /** @brief Gets the key size used to encrypt the connection */
+  uint8_t getSecKeySize() const {
+    return m_desc.sec_state.key_size;
+  }
+
+private:
+  friend class BLEServer;
+  friend class BLEClient;
+  friend class BLECharacteristic;
+  friend class BLEDescriptor;
+
+  ble_gap_conn_desc m_desc{};
+  BLEConnInfo(){};
+  BLEConnInfo(ble_gap_conn_desc desc) {
+    m_desc = desc;
+  }
+};
+#endif
+
+#endif  // BLECONNINFO_H_
diff --git a/libraries/BLE/src/BLEDescriptor.cpp b/libraries/BLE/src/BLEDescriptor.cpp
index 69a93e57201..51c77bb9b49 100644
--- a/libraries/BLE/src/BLEDescriptor.cpp
+++ b/libraries/BLE/src/BLEDescriptor.cpp
@@ -3,25 +3,50 @@
  *
  *  Created on: Jun 22, 2017
  *      Author: kolban
+ *
+ *  Modified on: Apr 3, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
 #include <sstream>
 #include <string.h>
 #include <iomanip>
 #include <stdlib.h>
 #include "sdkconfig.h"
 #include <esp_err.h>
+#include "BLE2904.h"
 #include "BLEService.h"
 #include "BLEDescriptor.h"
 #include "GeneralUtils.h"
 #include "esp32-hal-log.h"
 
+/***************************************************************************
+ *                           Common definitions                            *
+ ***************************************************************************/
+
 #define NULL_HANDLE (0xffff)
 
+/***************************************************************************
+ *                         Common global variables                         *
+ ***************************************************************************/
+
+static BLEDescriptorCallbacks defaultCallbacks;
+
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
+
 /**
  * @brief BLEDescriptor constructor.
  */
@@ -32,13 +57,15 @@ BLEDescriptor::BLEDescriptor(const char *uuid, uint16_t len) : BLEDescriptor(BLE
  */
 BLEDescriptor::BLEDescriptor(BLEUUID uuid, uint16_t max_len) {
   m_bleUUID = uuid;
-  m_value.attr_len = 0;            // Initial length is 0.
-  m_value.attr_max_len = max_len;  // Maximum length of the data.
-  m_handle = NULL_HANDLE;          // Handle is initially unknown.
-  m_pCharacteristic = nullptr;     // No initial characteristic.
-  m_pCallback = nullptr;           // No initial callback.
-
+  m_handle = NULL_HANDLE;                           // Handle is initially unknown.
+  m_pCharacteristic = nullptr;                      // No initial characteristic.
+  m_pCallback = nullptr;                            // No initial callback.
+  m_value.attr_len = 0;                             // Initial length is 0.
+  m_value.attr_max_len = max_len;                   // Maximum length of the data.
   m_value.attr_value = (uint8_t *)malloc(max_len);  // Allocate storage for the value.
+#if CONFIG_NIMBLE_ENABLED
+  m_removed = 0;
+#endif
 }  // BLEDescriptor
 
 /**
@@ -62,6 +89,7 @@ void BLEDescriptor::executeCreate(BLECharacteristic *pCharacteristic) {
 
   m_pCharacteristic = pCharacteristic;  // Save the characteristic associated with this service.
 
+#if CONFIG_BLUEDROID_ENABLED
   esp_attr_control_t control;
   control.auto_rsp = ESP_GATT_AUTO_RSP;
   m_semaphoreCreateEvt.take("executeCreate");
@@ -73,6 +101,7 @@ void BLEDescriptor::executeCreate(BLECharacteristic *pCharacteristic) {
   }
 
   m_semaphoreCreateEvt.wait("executeCreate");
+#endif
   log_v("<< executeCreate");
 }  // executeCreate
 
@@ -107,6 +136,118 @@ uint8_t *BLEDescriptor::getValue() {
   return m_value.attr_value;
 }  // getValue
 
+/**
+ * @brief Get the characteristic this descriptor belongs to.
+ * @return A pointer to the characteristic this descriptor belongs to.
+ */
+BLECharacteristic *BLEDescriptor::getCharacteristic() {
+  return m_pCharacteristic;
+}  // getCharacteristic
+
+/**
+ * @brief Set the callback handlers for this descriptor.
+ * @param [in] pCallbacks An instance of a callback structure used to define any callbacks for the descriptor.
+ */
+void BLEDescriptor::setCallbacks(BLEDescriptorCallbacks *pCallback) {
+  log_v(">> setCallbacks: 0x%x", (uint32_t)pCallback);
+  if (pCallback != nullptr) {
+    m_pCallback = pCallback;
+  } else {
+    m_pCallback = &defaultCallbacks;
+  }
+  log_v("<< setCallbacks");
+}  // setCallbacks
+
+/**
+ * @brief Set the handle of this descriptor.
+ * Set the handle of this descriptor to be the supplied value.
+ * @param [in] handle The handle to be associated with this descriptor.
+ * @return N/A.
+ */
+void BLEDescriptor::setHandle(uint16_t handle) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  log_v(">> setHandle(0x%.2x): Setting descriptor handle to be 0x%.2x", handle, handle);
+  m_handle = handle;
+  log_v("<< setHandle()");
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  log_w("NimBLE does not support manually setting the handle of a descriptor. Ignoring request.");
+#endif
+}  // setHandle
+
+/**
+ * @brief Set the value of the descriptor.
+ * @param [in] data The data to set for the descriptor.
+ * @param [in] length The length of the data in bytes.
+ */
+void BLEDescriptor::setValue(uint8_t *data, size_t length) {
+  if (length > m_value.attr_max_len) {
+    log_e("Size %d too large, must be no bigger than %d", length, m_value.attr_max_len);
+    return;
+  }
+
+  m_semaphoreSetValue.take();
+  m_value.attr_len = length;
+  memcpy(m_value.attr_value, data, length);
+#if CONFIG_BLUEDROID_ENABLED
+  if (m_handle != NULL_HANDLE) {
+    esp_ble_gatts_set_attr_value(m_handle, length, (const uint8_t *)data);
+    log_d("Set the value in the GATTS database using handle 0x%x", m_handle);
+  }
+#endif
+  m_semaphoreSetValue.give();
+}  // setValue
+
+/**
+ * @brief Set the value of the descriptor.
+ * @param [in] value The value of the descriptor in string form.
+ */
+void BLEDescriptor::setValue(String value) {
+  setValue((uint8_t *)value.c_str(), value.length());
+}  // setValue
+
+void BLEDescriptor::setAccessPermissions(uint8_t perm) {
+  m_permissions = perm;
+}
+
+/**
+ * @brief Return a string representation of the descriptor.
+ * @return A string representation of the descriptor.
+ */
+String BLEDescriptor::toString() {
+  char hex[5];
+  snprintf(hex, sizeof(hex), "%04x", m_handle);
+  String res = "UUID: " + m_bleUUID.toString() + ", handle: 0x" + hex;
+  return res;
+}  // toString
+
+BLEDescriptorCallbacks::~BLEDescriptorCallbacks() {}
+
+/**
+ * @brief Callback function to support a read request.
+ * @param [in] pDescriptor The descriptor that is the source of the event.
+ */
+void BLEDescriptorCallbacks::onRead(BLEDescriptor *pDescriptor) {
+  log_d("BLEDescriptorCallbacks", ">> onRead: default");
+  log_d("BLEDescriptorCallbacks", "<< onRead");
+}  // onRead
+
+/**
+ * @brief Callback function to support a write request.
+ * @param [in] pDescriptor The descriptor that is the source of the event.
+ */
+void BLEDescriptorCallbacks::onWrite(BLEDescriptor *pDescriptor) {
+  log_d("BLEDescriptorCallbacks", ">> onWrite: default");
+  log_d("BLEDescriptorCallbacks", "<< onWrite");
+}  // onWrite
+
+/***************************************************************************
+ *                           Bluedroid functions                           *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+
 /**
  * @brief Handle GATT server events for the descripttor.
  * @param [in] event
@@ -185,88 +326,84 @@ void BLEDescriptor::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_i
   }  // switch event
 }  // handleGATTServerEvent
 
-/**
- * @brief Set the callback handlers for this descriptor.
- * @param [in] pCallbacks An instance of a callback structure used to define any callbacks for the descriptor.
- */
-void BLEDescriptor::setCallbacks(BLEDescriptorCallbacks *pCallback) {
-  log_v(">> setCallbacks: 0x%x", (uint32_t)pCallback);
-  m_pCallback = pCallback;
-  log_v("<< setCallbacks");
-}  // setCallbacks
+#endif
 
-/**
- * @brief Set the handle of this descriptor.
- * Set the handle of this descriptor to be the supplied value.
- * @param [in] handle The handle to be associated with this descriptor.
- * @return N/A.
- */
-void BLEDescriptor::setHandle(uint16_t handle) {
-  log_v(">> setHandle(0x%.2x): Setting descriptor handle to be 0x%.2x", handle, handle);
-  m_handle = handle;
-  log_v("<< setHandle()");
-}  // setHandle
+/***************************************************************************
+ *                           NimBLE functions                             *
+ ***************************************************************************/
 
-/**
- * @brief Set the value of the descriptor.
- * @param [in] data The data to set for the descriptor.
- * @param [in] length The length of the data in bytes.
- */
-void BLEDescriptor::setValue(uint8_t *data, size_t length) {
-  if (length > ESP_GATT_MAX_ATTR_LEN) {
-    log_e("Size %d too large, must be no bigger than %d", length, ESP_GATT_MAX_ATTR_LEN);
-    return;
-  }
-  m_value.attr_len = length;
-  memcpy(m_value.attr_value, data, length);
-  if (m_handle != NULL_HANDLE) {
-    esp_ble_gatts_set_attr_value(m_handle, length, (const uint8_t *)data);
-    log_d("Set the value in the GATTS database using handle 0x%x", m_handle);
-  }
-}  // setValue
+#if defined(CONFIG_NIMBLE_ENABLED)
 
 /**
- * @brief Set the value of the descriptor.
- * @param [in] value The value of the descriptor in string form.
+ * @brief Handle GATT server events for the descriptor.
+ * @param [in] conn_handle The connection handle.
+ * @param [in] attr_handle The attribute handle.
+ * @param [in] ctxt The GATT access context.
+ * @param [in] arg The argument.
  */
-void BLEDescriptor::setValue(String value) {
-  setValue((uint8_t *)value.c_str(), value.length());
-}  // setValue
+int BLEDescriptor::handleGATTServerEvent(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt *ctxt, void *arg) {
+  const ble_uuid_t *uuid;
+  int rc;
+  struct ble_gap_conn_desc desc;
+  BLEDescriptor *pDescriptor = (BLEDescriptor *)arg;
+
+  log_d("Descriptor %s %s event", pDescriptor->getUUID().toString().c_str(), ctxt->op == BLE_GATT_ACCESS_OP_READ_DSC ? "Read" : "Write");
+
+  uuid = ctxt->chr->uuid;
+  if (ble_uuid_cmp(uuid, &pDescriptor->getUUID().getNative()->u) == 0) {
+    switch (ctxt->op) {
+      case BLE_GATT_ACCESS_OP_READ_DSC:
+      {
+        rc = ble_gap_conn_find(conn_handle, &desc);
+        assert(rc == 0);
+
+        // If the packet header is only 8 bytes this is a follow up of a long read
+        // so we don't want to call the onRead() callback again.
+        if (ctxt->om->om_pkthdr_len > 8 || pDescriptor->m_value.attr_len <= (ble_att_mtu(desc.conn_handle) - 3)) {
+          pDescriptor->m_pCallback->onRead(pDescriptor);
+        }
 
-void BLEDescriptor::setAccessPermissions(esp_gatt_perm_t perm) {
-  m_permissions = perm;
-}
+        ble_npl_hw_enter_critical();
+        rc = os_mbuf_append(ctxt->om, pDescriptor->m_value.attr_value, pDescriptor->m_value.attr_len);
+        ble_npl_hw_exit_critical(0);
+        return rc == 0 ? 0 : BLE_ATT_ERR_INSUFFICIENT_RES;
+      }
 
-/**
- * @brief Return a string representation of the descriptor.
- * @return A string representation of the descriptor.
- */
-String BLEDescriptor::toString() {
-  char hex[5];
-  snprintf(hex, sizeof(hex), "%04x", m_handle);
-  String res = "UUID: " + m_bleUUID.toString() + ", handle: 0x" + hex;
-  return res;
-}  // toString
+      case BLE_GATT_ACCESS_OP_WRITE_DSC:
+      {
+        uint16_t att_max_len = pDescriptor->m_value.attr_max_len;
 
-BLEDescriptorCallbacks::~BLEDescriptorCallbacks() {}
+        if (ctxt->om->om_len > att_max_len) {
+          return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
+        }
 
-/**
- * @brief Callback function to support a read request.
- * @param [in] pDescriptor The descriptor that is the source of the event.
- */
-void BLEDescriptorCallbacks::onRead(BLEDescriptor *pDescriptor) {
-  log_d("BLEDescriptorCallbacks", ">> onRead: default");
-  log_d("BLEDescriptorCallbacks", "<< onRead");
-}  // onRead
+        uint8_t buf[att_max_len];
+        size_t len = ctxt->om->om_len;
+        memcpy(buf, ctxt->om->om_data, len);
+        os_mbuf *next;
+        next = SLIST_NEXT(ctxt->om, om_next);
+        while (next != NULL) {
+          if ((len + next->om_len) > att_max_len) {
+            return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
+          }
+          memcpy(&buf[len], next->om_data, next->om_len);
+          len += next->om_len;
+          next = SLIST_NEXT(next, om_next);
+        }
 
-/**
- * @brief Callback function to support a write request.
- * @param [in] pDescriptor The descriptor that is the source of the event.
- */
-void BLEDescriptorCallbacks::onWrite(BLEDescriptor *pDescriptor) {
-  log_d("BLEDescriptorCallbacks", ">> onWrite: default");
-  log_d("BLEDescriptorCallbacks", "<< onWrite");
-}  // onWrite
+        pDescriptor->setValue(buf, len);
+        pDescriptor->m_pCallback->onWrite(pDescriptor);
+        return 0;
+      }
+
+      default: break;
+    }
+  }
+
+  return BLE_ATT_ERR_UNLIKELY;
+}
+
+#endif
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEDescriptor.h b/libraries/BLE/src/BLEDescriptor.h
index e155a1f2971..d0d34b24388 100644
--- a/libraries/BLE/src/BLEDescriptor.h
+++ b/libraries/BLE/src/BLEDescriptor.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Jun 22, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLEDESCRIPTOR_H_
@@ -11,13 +15,60 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
 #include <string>
 #include "BLEUUID.h"
 #include "BLECharacteristic.h"
-#include <esp_gatts_api.h>
 #include "RTOS.h"
 
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gatts_api.h>
+#endif
+
+/***************************************************************************
+ *                           NimBLE includes                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_att.h>
+#include "BLEConnInfo.h"
+
+#define ESP_GATT_PERM_READ                BLE_ATT_F_READ
+#define ESP_GATT_PERM_WRITE               BLE_ATT_F_WRITE
+#define ESP_GATT_PERM_READ_ENCRYPTED      BLE_ATT_F_READ_ENC
+#define ESP_GATT_PERM_WRITE_ENCRYPTED     BLE_ATT_F_WRITE_ENC
+#define ESP_GATT_PERM_READ_AUTHORIZATION  BLE_ATT_F_READ_AUTHOR
+#define ESP_GATT_PERM_WRITE_AUTHORIZATION BLE_ATT_F_WRITE_AUTHOR
+#define ESP_GATT_PERM_READ_ENC_MITM       BLE_ATT_F_READ_AUTHEN
+#define ESP_GATT_PERM_WRITE_ENC_MITM      BLE_ATT_F_WRITE_AUTHEN
+
+#endif
+
+/***************************************************************************
+ *                            NimBLE types                                 *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+typedef struct {
+  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 */
+} esp_attr_value_t;
+#endif
+
+/***************************************************************************
+ *                           Forward declarations                          *
+ ***************************************************************************/
+
 class BLEService;
 class BLECharacteristic;
 class BLEDescriptorCallbacks;
@@ -27,33 +78,83 @@ class BLEDescriptorCallbacks;
  */
 class BLEDescriptor {
 public:
+  /***************************************************************************
+   *                           Common public declarations                    *
+   ***************************************************************************/
+
   BLEDescriptor(const char *uuid, uint16_t max_len = 100);
   BLEDescriptor(BLEUUID uuid, uint16_t max_len = 100);
   virtual ~BLEDescriptor();
 
-  uint16_t getHandle();  // Get the handle of the descriptor.
-  size_t getLength();    // Get the length of the value of the descriptor.
-  BLEUUID getUUID();     // Get the UUID of the descriptor.
-  uint8_t *getValue();   // Get a pointer to the value of the descriptor.
-  void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
+  uint16_t getHandle();                    // Get the handle of the descriptor.
+  size_t getLength();                      // Get the length of the value of the descriptor.
+  BLEUUID getUUID();                       // Get the UUID of the descriptor.
+  uint8_t *getValue();                     // Get a pointer to the value of the descriptor.
+  BLECharacteristic *getCharacteristic();  // Get the characteristic that this descriptor belongs to.
 
-  void setAccessPermissions(esp_gatt_perm_t perm);        // Set the permissions of the descriptor.
+  void setAccessPermissions(uint8_t perm);                // Set the permissions of the descriptor.
   void setCallbacks(BLEDescriptorCallbacks *pCallbacks);  // Set callbacks to be invoked for the descriptor.
   void setValue(uint8_t *data, size_t size);              // Set the value of the descriptor as a pointer to data.
   void setValue(String value);                            // Set the value of the descriptor as a data buffer.
 
   String toString();  // Convert the descriptor to a string representation.
 
+  /***************************************************************************
+   *                           Bluedroid public declarations                 *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
+#endif
+
+  /***************************************************************************
+   *                           NimBLE public declarations                    *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  static int handleGATTServerEvent(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt *ctxt, void *arg);
+#endif
+
 private:
   friend class BLEDescriptorMap;
   friend class BLECharacteristic;
+  friend class BLEService;
+  friend class BLE2901;
+  friend class BLE2902;
+  friend class BLE2904;
+
+  /***************************************************************************
+   *                           Common private properties                     *
+   ***************************************************************************/
+
   BLEUUID m_bleUUID;
   uint16_t m_handle;
+  esp_attr_value_t m_value;
   BLEDescriptorCallbacks *m_pCallback;
   BLECharacteristic *m_pCharacteristic;
-  esp_gatt_perm_t m_permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE;
+  FreeRTOS::Semaphore m_semaphoreSetValue = FreeRTOS::Semaphore("SetValue");
+
+  /***************************************************************************
+   *                           Bluedroid private properties                  *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
   FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt");
-  esp_attr_value_t m_value;
+  uint8_t m_permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE;
+#endif
+
+  /***************************************************************************
+   *                           NimBLE private properties                     *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  uint8_t m_permissions = HA_FLAG_PERM_RW;
+  uint8_t m_removed = 0;
+#endif
+
+  /***************************************************************************
+   *                           Common private declarations                   *
+   ***************************************************************************/
 
   void executeCreate(BLECharacteristic *pCharacteristic);
   void setHandle(uint16_t handle);
@@ -68,11 +169,15 @@ class BLEDescriptor {
  */
 class BLEDescriptorCallbacks {
 public:
+  /***************************************************************************
+   *                           Common public declarations                    *
+   ***************************************************************************/
+
   virtual ~BLEDescriptorCallbacks();
   virtual void onRead(BLEDescriptor *pDescriptor);
   virtual void onWrite(BLEDescriptor *pDescriptor);
 };
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLEDESCRIPTOR_H_ */
diff --git a/libraries/BLE/src/BLEDescriptorMap.cpp b/libraries/BLE/src/BLEDescriptorMap.cpp
index 732fb62cdcf..e0c8b3a7cc3 100644
--- a/libraries/BLE/src/BLEDescriptorMap.cpp
+++ b/libraries/BLE/src/BLEDescriptorMap.cpp
@@ -3,21 +3,50 @@
  *
  *  Created on: Jun 22, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
 #include <sstream>
 #include <iomanip>
 #include "BLECharacteristic.h"
 #include "BLEDescriptor.h"
-#include <esp_gatts_api.h>  // ESP32 BLE
 #ifdef ARDUINO_ARCH_ESP32
 #include "esp32-hal-log.h"
 #endif
 
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gatts_api.h>  // ESP32 BLE
+#endif
+
+/***************************************************************************
+ *                           NimBLE includes                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include "host/ble_gatt.h"
+#endif
+
+/***************************************************************************
+ *                           Common functions                             *
+ ***************************************************************************/
+
 /**
  * @brief Return the descriptor by UUID.
  * @param [in] UUID The UUID to look up the descriptor.
@@ -81,6 +110,24 @@ void BLEDescriptorMap::setByHandle(uint16_t handle, BLEDescriptor *pDescriptor)
   m_handleMap.insert(std::pair<uint16_t, BLEDescriptor *>(handle, pDescriptor));
 }  // setByHandle
 
+/**
+ * @brief Get the number of registered descriptors.
+ * @return The number of registered descriptors.
+ */
+int BLEDescriptorMap::getRegisteredDescriptorCount() {
+  return m_uuidMap.size();
+}
+
+/**
+ * @brief Remove a descriptor from the map.
+ * @param [in] pDescriptor The descriptor to remove.
+ * @return N/A.
+ */
+void BLEDescriptorMap::removeDescriptor(BLEDescriptor *pDescriptor) {
+  m_uuidMap.erase(pDescriptor);
+  m_handleMap.erase(pDescriptor->getHandle());
+}
+
 /**
  * @brief Return a string representation of the descriptor map.
  * @return A string representation of the descriptor map.
@@ -102,19 +149,6 @@ String BLEDescriptorMap::toString() {
   return res;
 }  // toString
 
-/**
- * @brief Pass the GATT server event onwards to each of the descriptors found in the mapping
- * @param [in] event
- * @param [in] gatts_if
- * @param [in] param
- */
-void BLEDescriptorMap::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) {
-  // Invoke the handler for every descriptor we have.
-  for (auto &myPair : m_uuidMap) {
-    myPair.first->handleGATTServerEvent(event, gatts_if, param);
-  }
-}  // handleGATTServerEvent
-
 /**
  * @brief Get the first descriptor in the map.
  * @return The first descriptor in the map.
@@ -142,5 +176,41 @@ BLEDescriptor *BLEDescriptorMap::getNext() {
   return pRet;
 }  // getNext
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+/***************************************************************************
+ *                           Bluedroid functions                           *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+
+/**
+ * @brief Pass the GATT server event onwards to each of the descriptors found in the mapping
+ * @param [in] event
+ * @param [in] gatts_if
+ * @param [in] param
+ */
+void BLEDescriptorMap::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) {
+  // Invoke the handler for every descriptor we have.
+  for (auto &myPair : m_uuidMap) {
+    myPair.first->handleGATTServerEvent(event, gatts_if, param);
+  }
+}  // handleGATTServerEvent
+
+#endif
+
+/***************************************************************************
+ *                           NimBLE functions                             *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
+void BLEDescriptorMap::handleGATTServerEvent(uint16_t conn_handle, uint16_t attr_handle, ble_gatt_access_ctxt *ctxt, void *arg) {
+  // Invoke the handler for every descriptor we have.
+  for (auto &myPair : m_uuidMap) {
+    myPair.first->handleGATTServerEvent(conn_handle, attr_handle, ctxt, arg);
+  }
+}
+
+#endif
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEDevice.cpp b/libraries/BLE/src/BLEDevice.cpp
index 186b36d6a33..014806cc32b 100644
--- a/libraries/BLE/src/BLEDevice.cpp
+++ b/libraries/BLE/src/BLEDevice.cpp
@@ -1,30 +1,35 @@
 /*
- * BLE.cpp
+ * BLEDevice.cpp
  *
  *  Created on: Mar 16, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
 #include <freertos/FreeRTOS.h>
 #include <freertos/event_groups.h>
 #include <freertos/task.h>
 #include <esp_err.h>
 #include <nvs_flash.h>
-#include <esp_bt.h>               // ESP32 BLE
-#include <esp_bt_device.h>        // ESP32 BLE
-#include <esp_bt_main.h>          // ESP32 BLE
-#include <esp_gap_ble_api.h>      // ESP32 BLE
-#include <esp_gatts_api.h>        // ESP32 BLE
-#include <esp_gattc_api.h>        // ESP32 BLE
-#include <esp_gatt_common_api.h>  // ESP32 BLE
-#include <esp_err.h>              // ESP32 ESP-IDF
-#include <map>                    // Part of C++ Standard library
-#include <sstream>                // Part of C++ Standard library
-#include <iomanip>                // Part of C++ Standard library
+#include <esp_bt.h>
+
+#include <esp_err.h>
+#include <map>
+#include <sstream>
+#include <iomanip>
 
 #include "BLEDevice.h"
 #include "BLEClient.h"
@@ -37,34 +42,102 @@
 
 #include "esp32-hal-log.h"
 
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_bt_device.h>
+#include <esp_bt_main.h>
+#include <esp_gap_ble_api.h>
+#include <esp_gatts_api.h>
+#include <esp_gattc_api.h>
+#include <esp_gatt_common_api.h>
+#endif
+
+/***************************************************************************
+ *                           NimBLE includes                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#ifdef CONFIG_BT_NIMBLE_LEGACY_VHCI_ENABLE
+#include <esp_nimble_hci.h>
+#endif
+#include <nimble/nimble_port.h>
+#include <nimble/nimble_port_freertos.h>
+#include <host/ble_hs.h>
+#include <host/ble_hs_pvcy.h>
+#include <host/ble_gap.h>
+#include "host/ble_hs_pvcy.h"
+#include "host/util/util.h"
+#include "services/gap/ble_svc_gap.h"
+#include "services/gatt/ble_svc_gatt.h"
+#endif
+
+/***************************************************************************
+ *                            Common properties                            *
+ ***************************************************************************/
+
 /**
  * Singletons for the BLEDevice.
  */
 BLEServer *BLEDevice::m_pServer = nullptr;
 BLEScan *BLEDevice::m_pScan = nullptr;
 BLEClient *BLEDevice::m_pClient = nullptr;
-bool initialized = false;
-esp_ble_sec_act_t BLEDevice::m_securityLevel = (esp_ble_sec_act_t)0;
+static bool initialized = false;
 BLESecurityCallbacks *BLEDevice::m_securityCallbacks = nullptr;
 uint16_t BLEDevice::m_localMTU = 23;  // not sure if this variable is useful
 BLEAdvertising *BLEDevice::m_bleAdvertising = nullptr;
 uint16_t BLEDevice::m_appId = 0;
 std::map<uint16_t, conn_status_t> BLEDevice::m_connectedClientsMap;
 gap_event_handler BLEDevice::m_customGapHandler = nullptr;
+
+/***************************************************************************
+ *                           Bluedroid properties                          *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+esp_ble_sec_act_t BLEDevice::m_securityLevel = (esp_ble_sec_act_t)0;
 gattc_event_handler BLEDevice::m_customGattcHandler = nullptr;
 gatts_event_handler BLEDevice::m_customGattsHandler = nullptr;
+#endif
+
+/***************************************************************************
+ *                            NimBLE properties                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+ble_gap_event_listener BLEDevice::m_listener;
+BLEDeviceCallbacks BLEDevice::defaultDeviceCallbacks{};
+BLEDeviceCallbacks *BLEDevice::m_pDeviceCallbacks = &defaultDeviceCallbacks;
+uint8_t BLEDevice::m_ownAddrType = BLE_OWN_ADDR_PUBLIC;
+bool BLEDevice::m_synced = false;
+#endif
+
+/***************************************************************************
+ *                           Common functions                             *
+ ***************************************************************************/
 
 /**
  * @brief Create a new instance of a client.
  * @return A new instance of the client.
  */
-/* STATIC */ BLEClient *BLEDevice::createClient() {
+BLEClient *BLEDevice::createClient() {
   log_v(">> createClient");
-#ifndef CONFIG_GATTC_ENABLE  // Check that BLE GATTC is enabled in make menuconfig
-  log_e("BLE GATTC is not enabled - CONFIG_GATTC_ENABLE not defined");
+#if !defined(CONFIG_GATTC_ENABLE) && !defined(CONFIG_BT_NIMBLE_ROLE_CENTRAL)
+  log_e("BLE Client not enabled. Check CONFIG_GATTC_ENABLE for BlueDroid or CONFIG_BT_NIMBLE_ROLE_CENTRAL for NimBLE");
   abort();
 #endif  // CONFIG_GATTC_ENABLE
-  m_pClient = new BLEClient();
+
+#ifdef CONFIG_NIMBLE_ENABLED
+  if (m_connectedClientsMap.size() >= CONFIG_BT_NIMBLE_MAX_CONNECTIONS) {
+    log_e("Unable to create client. Max connections reached. Cur=%d Max=%d", m_connectedClientsMap.size(), CONFIG_BT_NIMBLE_MAX_CONNECTIONS);
+    m_pClient = nullptr;
+  } else
+#endif
+  {
+    m_pClient = new BLEClient();
+  }
   log_v("<< createClient");
   return m_pClient;
 }  // createClient
@@ -73,200 +146,45 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr;
  * @brief Create a new instance of a server.
  * @return A new instance of the server.
  */
-/* STATIC */ BLEServer *BLEDevice::createServer() {
+BLEServer *BLEDevice::createServer() {
   log_v(">> createServer");
-#ifndef CONFIG_GATTS_ENABLE  // Check that BLE GATTS is enabled in make menuconfig
-  log_e("BLE GATTS is not enabled - CONFIG_GATTS_ENABLE not defined");
+#if !defined(CONFIG_GATTS_ENABLE) && !defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
+  log_e("BLE Server not enabled. Check CONFIG_GATTS_ENABLE for BlueDroid or CONFIG_BT_NIMBLE_ROLE_PERIPHERAL for NimBLE");
   abort();
 #endif  // CONFIG_GATTS_ENABLE
-  m_pServer = new BLEServer();
-  m_pServer->createApp(m_appId++);
+
+  if (m_pServer == nullptr) {
+    m_pServer = new BLEServer();
+    m_pServer->createApp(m_appId++);
+#if defined(CONFIG_NIMBLE_ENABLED)
+    ble_gatts_reset();
+    ble_svc_gap_init();
+    ble_svc_gatt_init();
+#endif
+  }
   log_v("<< createServer");
   return m_pServer;
 }  // createServer
 
-/**
- * @brief Handle GATT server events.
- *
- * @param [in] event The event that has been newly received.
- * @param [in] gatts_if The connection to the GATT interface.
- * @param [in] param Parameters for the event.
- */
-/* STATIC */ void BLEDevice::gattServerEventHandler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) {
-  log_d("gattServerEventHandler [esp_gatt_if: %d] ... %s", gatts_if, BLEUtils::gattServerEventTypeToString(event).c_str());
-
-  BLEUtils::dumpGattServerEvent(event, gatts_if, param);
-
-  switch (event) {
-    case ESP_GATTS_CONNECT_EVT:
-    {
-#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
-      if (BLEDevice::m_securityLevel) {
-        esp_ble_set_encryption(param->connect.remote_bda, BLEDevice::m_securityLevel);
-      }
-#endif  // CONFIG_BLE_SMP_ENABLE
-      break;
-    }  // ESP_GATTS_CONNECT_EVT
-
-    default:
-    {
-      break;
-    }
-  }  // switch
-
-  if (BLEDevice::m_pServer != nullptr) {
-    BLEDevice::m_pServer->handleGATTServerEvent(event, gatts_if, param);
-  }
-
-  if (m_customGattsHandler != nullptr) {
-    m_customGattsHandler(event, gatts_if, param);
-  }
-
-}  // gattServerEventHandler
-
-/**
- * @brief Handle GATT client events.
- *
- * Handler for the GATT client events.
- *
- * @param [in] event
- * @param [in] gattc_if
- * @param [in] param
- */
-/* STATIC */ void BLEDevice::gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) {
-
-  log_d("gattClientEventHandler [esp_gatt_if: %d] ... %s", gattc_if, BLEUtils::gattClientEventTypeToString(event).c_str());
-  BLEUtils::dumpGattClientEvent(event, gattc_if, param);
-
-  switch (event) {
-    case ESP_GATTC_CONNECT_EVT:
-    {
-#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
-      if (BLEDevice::m_securityLevel) {
-        esp_ble_set_encryption(param->connect.remote_bda, BLEDevice::m_securityLevel);
-      }
-#endif  // CONFIG_BLE_SMP_ENABLE
-      break;
-    }  // ESP_GATTS_CONNECT_EVT
-
-    default: break;
-  }  // switch
-  for (auto &myPair : BLEDevice::getPeerDevices(true)) {
-    conn_status_t conn_status = (conn_status_t)myPair.second;
-    if (((BLEClient *)conn_status.peer_device)->getGattcIf() == gattc_if || ((BLEClient *)conn_status.peer_device)->getGattcIf() == ESP_GATT_IF_NONE
-        || gattc_if == ESP_GATT_IF_NONE) {
-      ((BLEClient *)conn_status.peer_device)->gattClientEventHandler(event, gattc_if, param);
-    }
-  }
-
-  if (m_customGattcHandler != nullptr) {
-    m_customGattcHandler(event, gattc_if, param);
-  }
-
-}  // gattClientEventHandler
-
-/**
- * @brief Handle GAP events.
- */
-/* STATIC */ void BLEDevice::gapEventHandler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
-
-  BLEUtils::dumpGapEvent(event, param);
-
-  switch (event) {
-
-    case ESP_GAP_BLE_OOB_REQ_EVT:  /* OOB request event */ log_i("ESP_GAP_BLE_OOB_REQ_EVT"); break;
-    case ESP_GAP_BLE_LOCAL_IR_EVT: /* BLE local IR event */ log_i("ESP_GAP_BLE_LOCAL_IR_EVT"); break;
-    case ESP_GAP_BLE_LOCAL_ER_EVT: /* BLE local ER event */ log_i("ESP_GAP_BLE_LOCAL_ER_EVT"); break;
-    case ESP_GAP_BLE_NC_REQ_EVT:   /*  NUMERIC CONFIRMATION  */ log_i("ESP_GAP_BLE_NC_REQ_EVT");
-#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
-      if (BLEDevice::m_securityCallbacks != nullptr) {
-        esp_ble_confirm_reply(param->ble_security.ble_req.bd_addr, BLEDevice::m_securityCallbacks->onConfirmPIN(param->ble_security.key_notif.passkey));
-      }
-#endif  // CONFIG_BLE_SMP_ENABLE
-      break;
-    case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* passkey request event */
-      log_i("ESP_GAP_BLE_PASSKEY_REQ_EVT: ");
-      // esp_log_buffer_hex(m_remote_bda, sizeof(m_remote_bda));
-#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
-      if (BLEDevice::m_securityCallbacks != nullptr) {
-        esp_ble_passkey_reply(param->ble_security.ble_req.bd_addr, true, BLEDevice::m_securityCallbacks->onPassKeyRequest());
-      }
-#endif  // CONFIG_BLE_SMP_ENABLE
-      break;
-      /*
-			 * TODO should we add white/black list comparison?
-			 */
-    case ESP_GAP_BLE_SEC_REQ_EVT:
-      /* send the positive(true) security response to the peer device to accept the security request.
-			 If not accept the security request, should sent the security response with negative(false) accept value*/
-      log_i("ESP_GAP_BLE_SEC_REQ_EVT");
-#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
-      if (BLEDevice::m_securityCallbacks != nullptr) {
-        esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, BLEDevice::m_securityCallbacks->onSecurityRequest());
-      } else {
-        esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true);
-      }
-#endif  // CONFIG_BLE_SMP_ENABLE
-      break;
-      /*
-			  *
-			  */
-    case ESP_GAP_BLE_PASSKEY_NOTIF_EVT:  //the app will receive this evt when the IO  has Output capability and the peer device IO has Input capability.
-      //display the passkey number to the user to input it in the peer device within 30 seconds
-      log_i("ESP_GAP_BLE_PASSKEY_NOTIF_EVT");
-#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
-      log_i("passKey = %d", param->ble_security.key_notif.passkey);
-      if (BLEDevice::m_securityCallbacks != nullptr) {
-        BLEDevice::m_securityCallbacks->onPassKeyNotify(param->ble_security.key_notif.passkey);
-      }
-#endif  // CONFIG_BLE_SMP_ENABLE
-      break;
-    case ESP_GAP_BLE_KEY_EVT:
-      //shows the ble key type info share with peer device to the user.
-      log_d("ESP_GAP_BLE_KEY_EVT");
-#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
-      log_i("key type = %s", BLESecurity::esp_key_type_to_str(param->ble_security.ble_key.key_type));
-#endif  // CONFIG_BLE_SMP_ENABLE
-      break;
-    case ESP_GAP_BLE_AUTH_CMPL_EVT: log_i("ESP_GAP_BLE_AUTH_CMPL_EVT");
-#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
-      if (BLEDevice::m_securityCallbacks != nullptr) {
-        BLEDevice::m_securityCallbacks->onAuthenticationComplete(param->ble_security.auth_cmpl);
-      }
-#endif  // CONFIG_BLE_SMP_ENABLE
-      break;
-    default:
-    {
-      break;
-    }
-  }  // switch
-
-  if (BLEDevice::m_pClient != nullptr) {
-    BLEDevice::m_pClient->handleGAPEvent(event, param);
-  }
-
-  if (BLEDevice::m_pScan != nullptr) {
-    BLEDevice::getScan()->handleGAPEvent(event, param);
-  }
-
-  if (m_bleAdvertising != nullptr) {
-    BLEDevice::getAdvertising()->handleGAPEvent(event, param);
-  }
-
-  if (m_customGapHandler != nullptr) {
-    BLEDevice::m_customGapHandler(event, param);
-  }
-
-}  // gapEventHandler
-
 /**
  * @brief Get the BLE device address.
  * @return The BLE device address.
  */
-/* STATIC*/ BLEAddress BLEDevice::getAddress() {
+BLEAddress BLEDevice::getAddress() {
+#if defined(CONFIG_BLUEDROID_ENABLED)
   const uint8_t *bdAddr = esp_bt_dev_get_address();
   esp_bd_addr_t addr;
   memcpy(addr, bdAddr, sizeof(addr));
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  ble_addr_t addr;
+  int ret = ble_hs_id_copy_addr(m_ownAddrType, addr.val, NULL);
+  if (ret != 0) {
+    log_e("No BLE address found. rc=%d", ret);
+    return BLEAddress();
+  }
+#endif
   return BLEAddress(addr);
 }  // getAddress
 
@@ -275,7 +193,7 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr;
  * @return The scanning object reference.  This is a singleton object.  The caller should not
  * try and release/delete it.
  */
-/* STATIC */ BLEScan *BLEDevice::getScan() {
+BLEScan *BLEDevice::getScan() {
   //log_v(">> getScan");
   if (m_pScan == nullptr) {
     m_pScan = new BLEScan();
@@ -285,13 +203,21 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr;
   return m_pScan;
 }  // getScan
 
+/**
+ * @brief Retrieve the server object
+ * @return The server object
+ */
+BLEServer *BLEDevice::getServer() {
+  return m_pServer;
+}  // getServer
+
 /**
  * @brief Get the value of a characteristic of a service on a remote device.
  * @param [in] bdAddress
  * @param [in] serviceUUID
  * @param [in] characteristicUUID
  */
-/* STATIC */ String BLEDevice::getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID) {
+String BLEDevice::getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID) {
   log_v(
     ">> getValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(),
     characteristicUUID.toString().c_str()
@@ -308,18 +234,25 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr;
  * @brief Initialize the %BLE environment.
  * @param deviceName The device name of the device.
  */
-/* STATIC */ void BLEDevice::init(String deviceName) {
+void BLEDevice::init(String deviceName) {
   if (!initialized) {
-    initialized = true;  // Set the initialization flag to ensure we are only initialized once.
-
     esp_err_t errRc = ESP_OK;
-#ifdef ARDUINO_ARCH_ESP32
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(ARDUINO_ARCH_ESP32)
     if (!btStart()) {
       errRc = ESP_FAIL;
       return;
     }
 #else
-    errRc = ::nvs_flash_init();
+    btStarted();
+    errRc = nvs_flash_init();
+    if (errRc == ESP_ERR_NVS_NO_FREE_PAGES || errRc == ESP_ERR_NVS_NEW_VERSION_FOUND) {
+      errRc = nvs_flash_erase();
+      if (errRc == ESP_OK) {
+        errRc = nvs_flash_init();
+      }
+    }
+
     if (errRc != ESP_OK) {
       log_e("nvs_flash_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
       return;
@@ -328,6 +261,7 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr;
 #ifndef CONFIG_BT_CLASSIC_ENABLED
     esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
 #endif
+
     esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
     errRc = esp_bt_controller_init(&bt_cfg);
     if (errRc != ESP_OK) {
@@ -348,7 +282,7 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr;
       return;
     }
 #endif
-#endif
+#endif  // !ARDUINO_ARCH_ESP32
 
     esp_bluedroid_status_t bt_state = esp_bluedroid_get_status();
     if (bt_state == ESP_BLUEDROID_STATUS_UNINITIALIZED) {
@@ -403,6 +337,45 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr;
       return;
     };
 #endif  // CONFIG_BLE_SMP_ENABLE
+#endif  // CONFIG_BLUEDROID_ENABLED
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+    errRc = nimble_port_init();
+    if (errRc != ESP_OK) {
+      log_e("nimble_port_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+      return;
+    }
+
+    // Global struct ble_hs_cfg from nimble/host/ble_hs.h needs to be initialized
+    ble_hs_cfg.reset_cb = BLEDevice::onReset;
+    ble_hs_cfg.sync_cb = BLEDevice::onSync;
+    ble_hs_cfg.store_status_cb = [](struct ble_store_status_event *event, void *arg) {
+      return m_pDeviceCallbacks->onStoreStatus(event, arg);
+    };
+    ble_hs_cfg.sm_io_cap = BLE_HS_IO_NO_INPUT_OUTPUT;
+    ble_hs_cfg.sm_bonding = 0;
+    ble_hs_cfg.sm_mitm = 0;
+    ble_hs_cfg.sm_sc = 1;
+    ble_hs_cfg.sm_our_key_dist = BLE_SM_PAIR_KEY_DIST_ENC;
+    ble_hs_cfg.sm_their_key_dist = BLE_SM_PAIR_KEY_DIST_ENC;
+#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_PRIVACY)
+    ble_hs_cfg.sm_our_key_dist |= BLE_SM_PAIR_KEY_DIST_ID;
+    ble_hs_cfg.sm_their_key_dist |= BLE_SM_PAIR_KEY_DIST_ID;
+#endif
+
+    errRc = ble_svc_gap_device_name_set(deviceName.c_str());
+    if (errRc != ESP_OK) {
+      log_e("ble_svc_gap_device_name_set: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+    }
+
+    ble_store_config_init();
+    nimble_port_freertos_init(BLEDevice::host_task);
+
+    while (!m_synced) {
+      ble_npl_time_delay(1);
+    }
+#endif                   // CONFIG_NIMBLE_ENABLED
+    initialized = true;  // Set the initialization flag to ensure we are only initialized once.
   }
   vTaskDelay(200 / portTICK_PERIOD_MS);  // Delay for 200 msecs as a workaround to an apparent Arduino environment issue.
 }  // init
@@ -435,7 +408,7 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr;
  * @param [in] powerType.
  * @param [in] powerLevel.
  */
-/* STATIC */ void BLEDevice::setPower(esp_power_level_t powerLevel, esp_ble_power_type_t powerType) {
+void BLEDevice::setPower(esp_power_level_t powerLevel, esp_ble_power_type_t powerType) {
   log_v(">> setPower: %d (type: %d)", powerLevel, powerType);
   esp_err_t errRc = ::esp_ble_tx_power_set(powerType, powerLevel);
   if (errRc != ESP_OK) {
@@ -444,13 +417,45 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr;
   log_v("<< setPower");
 }  // setPower
 
+/**
+ * @brief Get the transmission power.
+ * @param [in] powerType The power level to set, can be one of:
+ * *   ESP_BLE_PWR_TYPE_CONN_HDL0  = 0,  For connection handle 0
+ * *   ESP_BLE_PWR_TYPE_CONN_HDL1  = 1,  For connection handle 1
+ * *   ESP_BLE_PWR_TYPE_CONN_HDL2  = 2,  For connection handle 2
+ * *   ESP_BLE_PWR_TYPE_CONN_HDL3  = 3,  For connection handle 3
+ * *   ESP_BLE_PWR_TYPE_CONN_HDL4  = 4,  For connection handle 4
+ * *   ESP_BLE_PWR_TYPE_CONN_HDL5  = 5,  For connection handle 5
+ * *   ESP_BLE_PWR_TYPE_CONN_HDL6  = 6,  For connection handle 6
+ * *   ESP_BLE_PWR_TYPE_CONN_HDL7  = 7,  For connection handle 7
+ * *   ESP_BLE_PWR_TYPE_CONN_HDL8  = 8,  For connection handle 8
+ * *   ESP_BLE_PWR_TYPE_ADV        = 9,  For advertising
+ * *   ESP_BLE_PWR_TYPE_SCAN       = 10, For scan
+ * *   ESP_BLE_PWR_TYPE_DEFAULT    = 11, For default, if not set other, it will use default value
+ * @return the power level currently used by the type specified.
+ */
+
+int BLEDevice::getPower(esp_ble_power_type_t powerType) {
+  switch (esp_ble_tx_power_get(powerType)) {
+    case ESP_PWR_LVL_N12: return -12;
+    case ESP_PWR_LVL_N9:  return -9;
+    case ESP_PWR_LVL_N6:  return -6;
+    case ESP_PWR_LVL_N3:  return -6;
+    case ESP_PWR_LVL_N0:  return 0;
+    case ESP_PWR_LVL_P3:  return 3;
+    case ESP_PWR_LVL_P6:  return 6;
+    case ESP_PWR_LVL_P9:  return 9;
+    default:              return -128;
+  }
+}  // getPower
+
 /**
  * @brief Set the value of a characteristic of a service on a remote device.
  * @param [in] bdAddress
  * @param [in] serviceUUID
  * @param [in] characteristicUUID
  */
-/* STATIC */ void BLEDevice::setValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, String value) {
+void BLEDevice::setValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, String value) {
   log_v(
     ">> setValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(),
     characteristicUUID.toString().c_str()
@@ -465,7 +470,7 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr;
  * @brief Return a string representation of the nature of this device.
  * @return A string representation of the nature of this device.
  */
-/* STATIC */ String BLEDevice::toString() {
+String BLEDevice::toString() {
   String res = "BD Address: " + getAddress().toString();
   return res;
 }  // toString
@@ -476,14 +481,27 @@ gatts_event_handler BLEDevice::m_customGattsHandler = nullptr;
  */
 void BLEDevice::whiteListAdd(BLEAddress address) {
   log_v(">> whiteListAdd: %s", address.toString().c_str());
+#ifdef CONFIG_BLUEDROID_ENABLED
 #ifdef ESP_IDF_VERSION_MAJOR
-  esp_err_t errRc = esp_ble_gap_update_whitelist(true, *address.getNative(), BLE_WL_ADDR_TYPE_PUBLIC);  // HACK!!! True to add an entry.
+  esp_err_t errRc = esp_ble_gap_update_whitelist(true, address.getNative(), BLE_WL_ADDR_TYPE_PUBLIC);  // HACK!!! True to add an entry.
 #else
-  esp_err_t errRc = esp_ble_gap_update_whitelist(true, *address.getNative());  // True to add an entry.
+  esp_err_t errRc = esp_ble_gap_update_whitelist(true, address.getNative());  // True to add an entry.
 #endif
   if (errRc != ESP_OK) {
     log_e("esp_ble_gap_update_whitelist: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
   }
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  if (!BLEDevice::onWhiteList(address)) {
+    m_whiteList.push_back(address);
+    int errRc = ble_gap_wl_set(reinterpret_cast<ble_addr_t *>(&m_whiteList[0]), m_whiteList.size());
+    if (errRc != 0) {
+      log_e("Failed adding to whitelist rc=%d", errRc);
+      m_whiteList.pop_back();
+    }
+  }
+#endif
   log_v("<< whiteListAdd");
 }  // whiteListAdd
 
@@ -493,28 +511,36 @@ void BLEDevice::whiteListAdd(BLEAddress address) {
  */
 void BLEDevice::whiteListRemove(BLEAddress address) {
   log_v(">> whiteListRemove: %s", address.toString().c_str());
+#ifdef CONFIG_BLUEDROID_ENABLED
 #ifdef ESP_IDF_VERSION_MAJOR
-  esp_err_t errRc = esp_ble_gap_update_whitelist(false, *address.getNative(), BLE_WL_ADDR_TYPE_PUBLIC);  // HACK!!! False to remove an entry.
+  esp_err_t errRc = esp_ble_gap_update_whitelist(false, address.getNative(), BLE_WL_ADDR_TYPE_PUBLIC);  // HACK!!! False to remove an entry.
 #else
-  esp_err_t errRc = esp_ble_gap_update_whitelist(false, *address.getNative());  // False to remove an entry.
+  esp_err_t errRc = esp_ble_gap_update_whitelist(false, address.getNative());  // False to remove an entry.
 #endif
   if (errRc != ESP_OK) {
     log_e("esp_ble_gap_update_whitelist: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
   }
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  for (auto it = m_whiteList.begin(); it < m_whiteList.end(); ++it) {
+    if (*it == address) {
+      m_whiteList.erase(it);
+      int errRc = ble_gap_wl_set(reinterpret_cast<ble_addr_t *>(&m_whiteList[0]), m_whiteList.size());
+      if (errRc != 0) {
+        m_whiteList.push_back(address);
+        log_e("Failed removing from whitelist rc=%d", errRc);
+      }
+      std::vector<BLEAddress>(m_whiteList).swap(m_whiteList);
+    }
+  }
+#endif
   log_v("<< whiteListRemove");
 }  // whiteListRemove
 
 /*
- * @brief Set encryption level that will be negotiated with peer device durng connection
- * @param [in] level Requested encryption level
- */
-void BLEDevice::setEncryptionLevel(esp_ble_sec_act_t level) {
-  BLEDevice::m_securityLevel = level;
-}
-
-/*
- * @brief Set callbacks that will be used to handle encryption negotiation events and authentication events
- * @param [in] cllbacks Pointer to BLESecurityCallbacks class callback
+ * @brief Set callbacks that will be used to handle encryption negotiation events and authentication events
+ * @param [in] callbacks Pointer to BLESecurityCallbacks class callback
  */
 void BLEDevice::setSecurityCallbacks(BLESecurityCallbacks *callbacks) {
   BLEDevice::m_securityCallbacks = callbacks;
@@ -526,11 +552,19 @@ void BLEDevice::setSecurityCallbacks(BLESecurityCallbacks *callbacks) {
  */
 esp_err_t BLEDevice::setMTU(uint16_t mtu) {
   log_v(">> setLocalMTU: %d", mtu);
+
+#ifdef CONFIG_BLUEDROID_ENABLED
   esp_err_t err = esp_ble_gatt_set_local_mtu(mtu);
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  int err = ble_att_set_preferred_mtu(mtu);
+#endif
+
   if (err == ESP_OK) {
     m_localMTU = mtu;
   } else {
-    log_e("can't set local mtu value: %d", mtu);
+    log_e("can't set local mtu value: %d, rc=%d", mtu, err);
   }
   log_v("<< setLocalMTU");
   return err;
@@ -574,10 +608,23 @@ std::map<uint16_t, conn_status_t> BLEDevice::getPeerDevices(bool _client) {
   return m_connectedClientsMap;
 }
 
+BLEClient *BLEDevice::getClientByID(uint16_t conn_id) {
+  return BLEDevice::getClientByGattIf(conn_id);
+}
+
 BLEClient *BLEDevice::getClientByGattIf(uint16_t conn_id) {
   return (BLEClient *)m_connectedClientsMap.find(conn_id)->second.peer_device;
 }
 
+BLEClient *BLEDevice::getClientByAddress(BLEAddress address) {
+  for (auto &it : m_connectedClientsMap) {
+    if (((BLEClient *)it.second.peer_device)->getPeerAddress() == address) {
+      return (BLEClient *)it.second.peer_device;
+    }
+  }
+  return nullptr;
+}
+
 void BLEDevice::updatePeerDevice(void *peer, bool _client, uint16_t conn_id) {
   log_d("update conn_id: %d, GATT role: %s", conn_id, _client ? "client" : "server");
   std::map<uint16_t, conn_status_t>::iterator it = m_connectedClientsMap.find(ESP_GATT_IF_NONE);
@@ -619,20 +666,32 @@ void BLEDevice::removePeerDevice(uint16_t conn_id, bool _client) {
  * @brief de-Initialize the %BLE environment.
  * @param release_memory release the internal BT stack memory
  */
-/* STATIC */ void BLEDevice::deinit(bool release_memory) {
+void BLEDevice::deinit(bool release_memory) {
   if (!initialized) {
     return;
   }
 
+#ifdef CONFIG_BLUEDROID_ENABLED
   esp_bluedroid_disable();
   esp_bluedroid_deinit();
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  nimble_port_stop();
+  nimble_port_deinit();
+#endif
+
   esp_bt_controller_disable();
   esp_bt_controller_deinit();
+
 #ifdef ARDUINO_ARCH_ESP32
   if (release_memory) {
-    esp_bt_controller_mem_release(ESP_BT_MODE_BTDM
-    );  // <-- require tests because we released classic BT memory and this can cause crash (most likely not, esp-idf takes care of it)
+    // Require tests because we released classic BT memory and this can cause crash (most likely not, esp-idf takes care of it)
+    esp_bt_controller_mem_release(ESP_BT_MODE_BTDM);
   } else {
+#ifdef CONFIG_NIMBLE_ENABLED
+    m_synced = false;
+#endif
     initialized = false;
   }
 #endif
@@ -640,8 +699,195 @@ void BLEDevice::removePeerDevice(uint16_t conn_id, bool _client) {
 
 void BLEDevice::setCustomGapHandler(gap_event_handler handler) {
   m_customGapHandler = handler;
+#ifdef CONFIG_NIMBLE_ENABLED
+  int rc = ble_gap_event_listener_register(&m_listener, handler, NULL);
+  if (rc == BLE_HS_EALREADY) {
+    log_i("Already listening to GAP events.");
+  } else if (rc != 0) {
+    log_e("ble_gap_event_listener_register: rc=%d %s", rc, GeneralUtils::errorToString(rc));
+  }
+#endif
 }
 
+/***************************************************************************
+ *                           Bluedroid functions                           *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+
+/**
+ * @brief Handle GATT server events.
+ *
+ * @param [in] event The event that has been newly received.
+ * @param [in] gatts_if The connection to the GATT interface.
+ * @param [in] param Parameters for the event.
+ */
+void BLEDevice::gattServerEventHandler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) {
+  log_d("gattServerEventHandler [esp_gatt_if: %d] ... %s", gatts_if, BLEUtils::gattServerEventTypeToString(event).c_str());
+
+  BLEUtils::dumpGattServerEvent(event, gatts_if, param);
+
+  switch (event) {
+    case ESP_GATTS_CONNECT_EVT:
+    {
+#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
+      if (BLEDevice::m_securityLevel) {
+        esp_ble_set_encryption(param->connect.remote_bda, BLEDevice::m_securityLevel);
+      }
+#endif  // CONFIG_BLE_SMP_ENABLE
+      break;
+    }  // ESP_GATTS_CONNECT_EVT
+
+    default:
+    {
+      break;
+    }
+  }  // switch
+
+  if (BLEDevice::m_pServer != nullptr) {
+    BLEDevice::m_pServer->handleGATTServerEvent(event, gatts_if, param);
+  }
+
+  if (m_customGattsHandler != nullptr) {
+    m_customGattsHandler(event, gatts_if, param);
+  }
+
+}  // gattServerEventHandler
+
+/**
+ * @brief Handle GATT client events.
+ *
+ * Handler for the GATT client events.
+ *
+ * @param [in] event
+ * @param [in] gattc_if
+ * @param [in] param
+ */
+void BLEDevice::gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) {
+
+  log_d("gattClientEventHandler [esp_gatt_if: %d] ... %s", gattc_if, BLEUtils::gattClientEventTypeToString(event).c_str());
+  BLEUtils::dumpGattClientEvent(event, gattc_if, param);
+
+  switch (event) {
+    case ESP_GATTC_CONNECT_EVT:
+    {
+#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
+      if (BLEDevice::m_securityLevel) {
+        esp_ble_set_encryption(param->connect.remote_bda, BLEDevice::m_securityLevel);
+      }
+#endif  // CONFIG_BLE_SMP_ENABLE
+      break;
+    }  // ESP_GATTS_CONNECT_EVT
+
+    default: break;
+  }  // switch
+  for (auto &myPair : BLEDevice::getPeerDevices(true)) {
+    conn_status_t conn_status = (conn_status_t)myPair.second;
+    if (((BLEClient *)conn_status.peer_device)->getGattcIf() == gattc_if || ((BLEClient *)conn_status.peer_device)->getGattcIf() == ESP_GATT_IF_NONE
+        || gattc_if == ESP_GATT_IF_NONE) {
+      ((BLEClient *)conn_status.peer_device)->gattClientEventHandler(event, gattc_if, param);
+    }
+  }
+
+  if (m_customGattcHandler != nullptr) {
+    m_customGattcHandler(event, gattc_if, param);
+  }
+
+}  // gattClientEventHandler
+
+/**
+ * @brief Handle GAP events.
+ */
+void BLEDevice::gapEventHandler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
+
+  BLEUtils::dumpGapEvent(event, param);
+
+  switch (event) {
+
+    case ESP_GAP_BLE_OOB_REQ_EVT:  /* OOB request event */ log_i("ESP_GAP_BLE_OOB_REQ_EVT"); break;
+    case ESP_GAP_BLE_LOCAL_IR_EVT: /* BLE local IR event */ log_i("ESP_GAP_BLE_LOCAL_IR_EVT"); break;
+    case ESP_GAP_BLE_LOCAL_ER_EVT: /* BLE local ER event */ log_i("ESP_GAP_BLE_LOCAL_ER_EVT"); break;
+    case ESP_GAP_BLE_NC_REQ_EVT:   /*  NUMERIC CONFIRMATION  */ log_i("ESP_GAP_BLE_NC_REQ_EVT");
+#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
+      if (BLEDevice::m_securityCallbacks != nullptr) {
+        esp_ble_confirm_reply(param->ble_security.ble_req.bd_addr, BLEDevice::m_securityCallbacks->onConfirmPIN(param->ble_security.key_notif.passkey));
+      }
+#endif  // CONFIG_BLE_SMP_ENABLE
+      break;
+    case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* passkey request event */
+      log_i("ESP_GAP_BLE_PASSKEY_REQ_EVT: ");
+      // esp_log_buffer_hex(m_remote_bda, sizeof(m_remote_bda));
+#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
+      if (BLEDevice::m_securityCallbacks != nullptr) {
+        esp_ble_passkey_reply(param->ble_security.ble_req.bd_addr, true, BLEDevice::m_securityCallbacks->onPassKeyRequest());
+      }
+#endif  // CONFIG_BLE_SMP_ENABLE
+      break;
+      /*
+			 * TODO should we add white/black list comparison?
+			 */
+    case ESP_GAP_BLE_SEC_REQ_EVT:
+      /* send the positive(true) security response to the peer device to accept the security request.
+			 If not accept the security request, should sent the security response with negative(false) accept value*/
+      log_i("ESP_GAP_BLE_SEC_REQ_EVT");
+#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
+      if (BLEDevice::m_securityCallbacks != nullptr) {
+        esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, BLEDevice::m_securityCallbacks->onSecurityRequest());
+      } else {
+        esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true);
+      }
+#endif  // CONFIG_BLE_SMP_ENABLE
+      break;
+      /*
+			  *
+			  */
+    case ESP_GAP_BLE_PASSKEY_NOTIF_EVT:  //the app will receive this evt when the IO  has Output capability and the peer device IO has Input capability.
+      //display the passkey number to the user to input it in the peer device within 30 seconds
+      log_i("ESP_GAP_BLE_PASSKEY_NOTIF_EVT");
+#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
+      log_i("passKey = %d", param->ble_security.key_notif.passkey);
+      if (BLEDevice::m_securityCallbacks != nullptr) {
+        BLEDevice::m_securityCallbacks->onPassKeyNotify(param->ble_security.key_notif.passkey);
+      }
+#endif  // CONFIG_BLE_SMP_ENABLE
+      break;
+    case ESP_GAP_BLE_KEY_EVT:
+      //shows the ble key type info share with peer device to the user.
+      log_d("ESP_GAP_BLE_KEY_EVT");
+#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
+      log_i("key type = %s", BLESecurity::esp_key_type_to_str(param->ble_security.ble_key.key_type));
+#endif  // CONFIG_BLE_SMP_ENABLE
+      break;
+    case ESP_GAP_BLE_AUTH_CMPL_EVT: log_i("ESP_GAP_BLE_AUTH_CMPL_EVT");
+#ifdef CONFIG_BLE_SMP_ENABLE  // Check that BLE SMP (security) is configured in make menuconfig
+      if (BLEDevice::m_securityCallbacks != nullptr) {
+        BLEDevice::m_securityCallbacks->onAuthenticationComplete(param->ble_security.auth_cmpl);
+      }
+#endif  // CONFIG_BLE_SMP_ENABLE
+      break;
+    default:
+    {
+      break;
+    }
+  }  // switch
+
+  if (BLEDevice::m_pClient != nullptr) {
+    BLEDevice::m_pClient->handleGAPEvent(event, param);
+  }
+
+  if (BLEDevice::m_pScan != nullptr) {
+    BLEDevice::getScan()->handleGAPEvent(event, param);
+  }
+
+  if (m_bleAdvertising != nullptr) {
+    BLEDevice::getAdvertising()->handleGAPEvent(event, param);
+  }
+
+  if (m_customGapHandler != nullptr) {
+    BLEDevice::m_customGapHandler(event, param);
+  }
+
+}  // gapEventHandler
 void BLEDevice::setCustomGattcHandler(gattc_event_handler handler) {
   m_customGattcHandler = handler;
 }
@@ -650,5 +896,170 @@ void BLEDevice::setCustomGattsHandler(gatts_event_handler handler) {
   m_customGattsHandler = handler;
 }
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+/*
+ * @brief Set encryption level that will be negotiated with peer device durng connection
+ * @param [in] level Requested encryption level
+ */
+void BLEDevice::setEncryptionLevel(esp_ble_sec_act_t level) {
+  BLEDevice::m_securityLevel = level;
+}
+
+#endif
+
+/***************************************************************************
+ *                            NimBLE functions                             *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
+/**
+ * @brief Checks if a peer device is whitelisted.
+ * @param [in] address The address to check for in the whitelist.
+ * @returns True if the address is in the whitelist.
+ */
+bool BLEDevice::onWhiteList(BLEAddress &address) {
+  for (auto &addr : m_whiteList) {
+    if (addr == address) {
+      return true;
+    }
+  }
+  return false;
+}
+
+void BLEDevice::host_task(void *param) {
+  log_i("NimBLE host task started");
+  nimble_port_run();  // This function will return only when nimble_port_stop() is executed
+  nimble_port_freertos_deinit();
+}
+
+void BLEDevice::onReset(int reason) {
+  if (!m_synced) {
+    return;
+  }
+
+  m_synced = false;
+
+  log_i("onReset, reason=%d, %s", reason, BLEUtils::returnCodeToString(reason));
+
+  if (initialized) {
+    if (m_pScan != nullptr) {
+      m_pScan->onHostReset();
+    }
+  }
+}
+
+void BLEDevice::onSync() {
+  log_d("onSync");
+
+  if (m_synced) {
+    log_d("onSync: already synced");
+    return;
+  }
+
+  int rc = ble_hs_util_ensure_addr(0);
+  if (rc == 0) {
+    rc = ble_hs_util_ensure_addr(1);
+  }
+
+  if (rc != 0) {
+    log_e("onSync: failed to ensure BLE address. rc=%d", rc);
+    return;
+  }
+
+  rc = ble_hs_id_copy_addr(BLE_OWN_ADDR_PUBLIC, NULL, NULL);
+  if (rc != 0) {
+    log_d("onSync: no public address available");
+    m_ownAddrType = BLE_OWN_ADDR_RANDOM;
+  }
+
+  // Yield for housekeeping tasks before returning to operations.
+  // Occasionally triggers exception without.
+  ble_npl_time_delay(1);
+
+  m_synced = true;
+
+  if (initialized) {
+    if (m_pScan != nullptr) {
+      m_pScan->onHostSync();
+    }
+    if (m_bleAdvertising != nullptr) {
+      m_bleAdvertising->onHostSync();
+    }
+  }
+}
+
+void BLEDevice::setDeviceCallbacks(BLEDeviceCallbacks *cb) {
+  if (cb == nullptr) {
+    m_pDeviceCallbacks = &defaultDeviceCallbacks;
+  } else {
+    m_pDeviceCallbacks = cb;
+  }
+}
+
+/**
+ * @brief Sets the address type to use.
+ * @param [in] type Bluetooth Device address type.
+ * The available types are defined as:
+ * * 0x00: BLE_OWN_ADDR_PUBLIC - Public address; Uses the hardware static address.
+ * * 0x01: BLE_OWN_ADDR_RANDOM - Random static address; Uses the hardware or generated random static address.
+ * * 0x02: BLE_OWN_ADDR_RPA_PUBLIC_DEFAULT - Resolvable private address, defaults to public if no RPA available.
+ * * 0x03: BLE_OWN_ADDR_RPA_RANDOM_DEFAULT - Resolvable private address, defaults to random static if no RPA available.
+ */
+bool BLEDevice::setOwnAddrType(uint8_t type) {
+  int rc = ble_hs_id_copy_addr(type & 1, NULL, NULL);  // Odd values are random
+  if (rc != 0) {
+    log_e("Unable to set address type %d, rc=%d", type, rc);
+    return false;
+  }
+
+  m_ownAddrType = type;
+
+  if (type == BLE_OWN_ADDR_RPA_PUBLIC_DEFAULT || type == BLE_OWN_ADDR_RPA_RANDOM_DEFAULT) {
+#ifdef CONFIG_IDF_TARGET_ESP32
+    // esp32 controller does not support RPA so we must use the random static for calls to the stack
+    // the host will take care of the random private address generation/setting.
+    m_ownAddrType = BLE_OWN_ADDR_RANDOM;
+    rc = ble_hs_pvcy_rpa_config(NIMBLE_HOST_ENABLE_RPA);
+#endif
+  } else {
+#ifdef CONFIG_IDF_TARGET_ESP32
+    rc = ble_hs_pvcy_rpa_config(NIMBLE_HOST_DISABLE_PRIVACY);
+#endif
+  }
+  return rc == 0;
+}  // setOwnAddrType
+
+/**
+ * @brief Set the device address to use.
+ * @param [in] addr The address to set.
+ * @return True if the address was set successfully.
+ * @details To use the address generated the address type must be set to random with `setOwnAddrType`.
+ */
+bool BLEDevice::setOwnAddr(BLEAddress &addr) {
+  return setOwnAddr(addr.getNative());
+}  // setOwnAddr
+
+/**
+ * @brief Set the device address to use.
+ * @param [in] addr The address to set.
+ * @return True if the address was set successfully.
+ * @details To use the address generated the address type must be set to random with `setOwnAddrType`.
+ */
+bool BLEDevice::setOwnAddr(uint8_t *addr) {
+  int rc = ble_hs_id_set_rnd(addr);
+  if (rc != 0) {
+    log_e("Failed to set address, rc=%d", rc);
+    return false;
+  }
+  return true;
+}  // setOwnAddr
+
+int BLEDeviceCallbacks::onStoreStatus(struct ble_store_status_event *event, void *arg) {
+  log_d("onStoreStatus: default");
+  return ble_store_util_status_rr(event, arg);
+}
+
+#endif
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEDevice.h b/libraries/BLE/src/BLEDevice.h
index 01bf143c101..66cfa2b371a 100644
--- a/libraries/BLE/src/BLEDevice.h
+++ b/libraries/BLE/src/BLEDevice.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Mar 16, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef MAIN_BLEDevice_H_
@@ -11,88 +15,252 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
-#include <esp_gap_ble_api.h>  // ESP32 BLE
-#include <esp_gattc_api.h>    // ESP32 BLE
-#include <map>                // Part of C++ STL
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
+#include <map>
 #include <string>
 #include <esp_bt.h>
-
 #include "BLEServer.h"
 #include "BLEClient.h"
 #include "BLEUtils.h"
 #include "BLEScan.h"
+#include "BLEAdvertising.h"
+#include "BLESecurity.h"
 #include "BLEAddress.h"
+#include "BLEUtils.h"
 
-/**
- * @brief BLE functions.
- */
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gap_ble_api.h>
+#include <esp_gattc_api.h>
+#include <esp_gatts_api.h>
+#endif
+
+/***************************************************************************
+ *                      NimBLE includes and definitions                    *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_gap.h>
+#define ESP_GATT_IF_NONE BLE_HS_CONN_HANDLE_NONE
+
+// NimBLE configuration compatibility macros
+#if defined(CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR) && !defined(CONFIG_BTDM_SCAN_DUPL_TYPE_DEVICE)
+#define CONFIG_BTDM_SCAN_DUPL_TYPE_DEVICE CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR
+#endif
+
+#if defined(CONFIG_SCAN_DUPLICATE_BY_ADV_DATA) && !defined(CONFIG_BTDM_SCAN_DUPL_TYPE_DATA)
+#define CONFIG_BTDM_SCAN_DUPL_TYPE_DATA CONFIG_SCAN_DUPLICATE_BY_ADV_DATA
+#endif
+
+#if defined(CONFIG_SCAN_DUPLICATE_BY_ADV_DATA_AND_DEVICE_ADDR) && !defined(CONFIG_BTDM_SCAN_DUPL_TYPE_DATA_DEVICE)
+#define CONFIG_BTDM_SCAN_DUPL_TYPE_DATA_DEVICE CONFIG_SCAN_DUPLICATE_BY_ADV_DATA_AND_DEVICE_ADDR
+#endif
+
+#if defined(CONFIG_SCAN_DUPLICATE_TYPE) && !defined(CONFIG_BTDM_SCAN_DUPL_TYPE)
+#define CONFIG_BTDM_SCAN_DUPL_TYPE CONFIG_SCAN_DUPLICATE_TYPE
+#endif
+
+#if defined(CONFIG_BT_CTRL_SCAN_DUPL_TYPE) && !defined(CONFIG_BTDM_SCAN_DUPL_TYPE)
+#define CONFIG_BTDM_SCAN_DUPL_TYPE CONFIG_BT_CTRL_SCAN_DUPL_TYPE
+#endif
+
+#if defined(CONFIG_BT_LE_SCAN_DUPL_TYPE) && !defined(CONFIG_BTDM_SCAN_DUPL_TYPE)
+#define CONFIG_BTDM_SCAN_DUPL_TYPE CONFIG_BT_LE_SCAN_DUPL_TYPE
+#endif
+
+#if defined(CONFIG_DUPLICATE_SCAN_CACHE_SIZE) && !defined(CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE)
+#define CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE CONFIG_DUPLICATE_SCAN_CACHE_SIZE
+#endif
+
+#if defined(CONFIG_BT_CTRL_SCAN_DUPL_CACHE_SIZE) && !defined(CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE)
+#define CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE CONFIG_BT_CTRL_SCAN_DUPL_CACHE_SIZE
+#endif
+
+#if defined(CONFIG_BT_LE_LL_DUP_SCAN_LIST_COUNT) && !defined(CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE)
+#define CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE CONFIG_BT_LE_LL_DUP_SCAN_LIST_COUNT
+#endif
+
+#if defined(CONFIG_NIMBLE_MAX_CONNECTIONS) && !defined(CONFIG_BT_NIMBLE_MAX_CONNECTIONS)
+#define CONFIG_BT_NIMBLE_MAX_CONNECTIONS CONFIG_NIMBLE_MAX_CONNECTIONS
+#endif
+
+#endif
+
+/***************************************************************************
+ *                           Forward declarations                          *
+ ***************************************************************************/
+
+class BLEAddress;
+class BLEDeviceCallbacks;
+class BLESecurityCallbacks;
+class BLEServer;
+class BLEScan;
+class BLEAdvertising;
+class BLEClient;
+class BLESecurity;
+
+/***************************************************************************
+ *                        Bluedroid type definitions                       *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
 typedef void (*gap_event_handler)(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
 typedef void (*gattc_event_handler)(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
 typedef void (*gatts_event_handler)(esp_gatts_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gatts_cb_param_t *param);
+#endif
+
+/***************************************************************************
+ *                    NimBLE type definitions and externals                *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+extern "C" void ble_store_config_init(void);
+typedef int (*gap_event_handler)(struct ble_gap_event *event, void *param);
+#endif
 
 class BLEDevice {
 public:
-  static BLEClient *createClient();                                                               // Create a new BLE client.
-  static BLEServer *createServer();                                                               // Create a new BLE server.
-  static BLEAddress getAddress();                                                                 // Retrieve our own local BD address.
-  static BLEScan *getScan();                                                                      // Get the scan object
-  static String getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID);  // Get the value of a characteristic of a service on a server.
-  static void init(String deviceName);                                                            // Initialize the local BLE environment.
-  static void setPower(esp_power_level_t powerLevel, esp_ble_power_type_t powerType = ESP_BLE_PWR_TYPE_DEFAULT);  // Set our power level.
-  static void setValue(
-    BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, String value
-  );                                                // Set the value of a characteristic on a service on a server.
-  static String toString();                         // Return a string representation of our device.
-  static void whiteListAdd(BLEAddress address);     // Add an entry to the BLE white list.
-  static void whiteListRemove(BLEAddress address);  // Remove an entry from the BLE white list.
-  static void setEncryptionLevel(esp_ble_sec_act_t level);
+  /***************************************************************************
+   *                        Common public properties                         *
+   ***************************************************************************/
+
+  static uint16_t m_appId;
+  static uint16_t m_localMTU;
+  static gap_event_handler m_customGapHandler;
+
+  /***************************************************************************
+   *                        Bluedroid public properties                      *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  static esp_ble_sec_act_t m_securityLevel;
+  static gattc_event_handler m_customGattcHandler;
+  static gatts_event_handler m_customGattsHandler;
+#endif
+
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
+  static BLEClient *createClient();
+  static BLEServer *createServer();
+  static BLEAddress getAddress();
+  static BLEServer *getServer();
+  static BLEScan *getScan();
+  static String getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID);
+  static void init(String deviceName);
+  static void setPower(esp_power_level_t powerLevel, esp_ble_power_type_t powerType = ESP_BLE_PWR_TYPE_DEFAULT);
+  static int getPower(esp_ble_power_type_t powerType = ESP_BLE_PWR_TYPE_DEFAULT);
+  static void setValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, String value);
+  static String toString();
+  static void whiteListAdd(BLEAddress address);
+  static void whiteListRemove(BLEAddress address);
   static void setSecurityCallbacks(BLESecurityCallbacks *pCallbacks);
   static esp_err_t setMTU(uint16_t mtu);
   static uint16_t getMTU();
-  static bool getInitialized();  // Returns the state of the device, is it initialized or not?
-  /* move advertising to BLEDevice for saving ram and flash in beacons */
+  static bool getInitialized();
   static BLEAdvertising *getAdvertising();
   static void startAdvertising();
   static void stopAdvertising();
-  static uint16_t m_appId;
-  /* multi connect */
   static std::map<uint16_t, conn_status_t> getPeerDevices(bool client);
   static void addPeerDevice(void *peer, bool is_client, uint16_t conn_id);
   static void updatePeerDevice(void *peer, bool _client, uint16_t conn_id);
   static void removePeerDevice(uint16_t conn_id, bool client);
+  static BLEClient *getClientByID(uint16_t conn_id);
+  static BLEClient *getClientByAddress(BLEAddress address);
   static BLEClient *getClientByGattIf(uint16_t conn_id);
   static void setCustomGapHandler(gap_event_handler handler);
+  static void deinit(bool release_memory = false);
+
+  /***************************************************************************
+   *                       Bluedroid public declarations                    *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  static void setEncryptionLevel(esp_ble_sec_act_t level);
   static void setCustomGattcHandler(gattc_event_handler handler);
   static void setCustomGattsHandler(gatts_event_handler handler);
-  static void deinit(bool release_memory = false);
-  static uint16_t m_localMTU;
-  static esp_ble_sec_act_t m_securityLevel;
+#endif
+
+  /***************************************************************************
+   *                       NimBLE public declarations                       *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  static void onReset(int reason);
+  static void onSync(void);
+  static void host_task(void *param);
+  static bool setOwnAddrType(uint8_t type);
+  static bool setOwnAddr(BLEAddress &addr);
+  static bool setOwnAddr(uint8_t *addr);
+  static void setDeviceCallbacks(BLEDeviceCallbacks *cb);
+  static bool onWhiteList(BLEAddress &address);
+#endif
 
 private:
+  friend class BLEClient;
+  friend class BLEScan;
+  friend class BLEServer;
+  friend class BLECharacteristic;
+  friend class BLEAdvertising;
+
+  /***************************************************************************
+   *                        Common private properties                        *
+   ***************************************************************************/
+
   static BLEServer *m_pServer;
   static BLEScan *m_pScan;
   static BLEClient *m_pClient;
   static BLESecurityCallbacks *m_securityCallbacks;
   static BLEAdvertising *m_bleAdvertising;
-  static esp_gatt_if_t getGattcIF();
   static std::map<uint16_t, conn_status_t> m_connectedClientsMap;
   static portMUX_TYPE mux;
 
-  static void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
+  /***************************************************************************
+   *                        NimBLE private properties                        *
+   ***************************************************************************/
 
-  static void gattServerEventHandler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
+#if defined(CONFIG_NIMBLE_ENABLED)
+  static uint8_t m_ownAddrType;
+  static bool m_synced;
+  static std::vector<BLEAddress> m_whiteList;
+  static BLEDeviceCallbacks defaultDeviceCallbacks;
+  static BLEDeviceCallbacks *m_pDeviceCallbacks;
+  static ble_gap_event_listener m_listener;
+#endif
 
+  /***************************************************************************
+   *                        Bluedroid private declarations                   *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  static esp_gatt_if_t getGattcIF();
+  static void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
+  static void gattServerEventHandler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
   static void gapEventHandler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
+#endif
+};  // class BLE
 
-public:
-  /* custom gap and gatt handlers for flexibility */
-  static gap_event_handler m_customGapHandler;
-  static gattc_event_handler m_customGattcHandler;
-  static gatts_event_handler m_customGattsHandler;
+/***************************************************************************
+ *                       NimBLE specific classes                           *
+ ***************************************************************************/
 
-};  // class BLE
+#if defined(CONFIG_NIMBLE_ENABLED)
+class BLEDeviceCallbacks {
+public:
+  virtual ~BLEDeviceCallbacks(){};
+  virtual int onStoreStatus(struct ble_store_status_event *event, void *arg);
+};
+#endif
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* MAIN_BLEDevice_H_ */
diff --git a/libraries/BLE/src/BLEEddystoneTLM.cpp b/libraries/BLE/src/BLEEddystoneTLM.cpp
index 1a301f09011..ca0fb41b1a2 100644
--- a/libraries/BLE/src/BLEEddystoneTLM.cpp
+++ b/libraries/BLE/src/BLEEddystoneTLM.cpp
@@ -8,12 +8,16 @@
  *  Fix time stamp (0.1 second resolution)
  *  Fixes based on EddystoneTLM frame specification https://github.com/google/eddystone/blob/master/eddystone-tlm/tlm-plain.md
  *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on pcbreflux's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
 #include <string.h>
 #include <stdio.h>
 #include "esp32-hal-log.h"
@@ -176,5 +180,5 @@ void BLEEddystoneTLM::setTime(uint32_t tmil) {
   m_eddystoneData.tmil = tmil;
 }  // setTime
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEEddystoneTLM.cppwithheadder b/libraries/BLE/src/BLEEddystoneTLM.cppwithheadder
deleted file mode 100644
index 07002dbab1f..00000000000
--- a/libraries/BLE/src/BLEEddystoneTLM.cppwithheadder
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * BLEEddystoneTLM.cpp
- *
- *  Created on: Mar 12, 2018
- *      Author: pcbreflux
- *  Edited on: Mar 20, 2020 by beegee-tokyo
- *  Fix temperature value (8.8 fixed format)
- *  Fix time stamp (0.1 second resolution)
- *  Fixes based on EddystoneTLM frame specification https://github.com/google/eddystone/blob/master/eddystone-tlm/tlm-plain.md
- *
- */
-#include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
-#include <string.h>
-#include <stdio.h>
-#include "esp32-hal-log.h"
-#include "BLEEddystoneTLM.h"
-
-static const char LOG_TAG[] = "BLEEddystoneTLM";
-
-BLEEddystoneTLM::BLEEddystoneTLM() {
-  m_eddystoneData.frameType = EDDYSTONE_TLM_FRAME_TYPE;
-  m_eddystoneData.version = 0;
-  m_eddystoneData.volt = 3300; // 3300mV = 3.3V
-  m_eddystoneData.temp = (uint16_t) ((float) 23.00)/256;
-  m_eddystoneData.advCount = 0;
-  m_eddystoneData.tmil = 0;
-  _initHeadder();
-} // BLEEddystoneTLM
-
-BLEEddystoneTLM::BLEEddystoneTLM(BLEAdvertisedDevice *advertisedDevice){
-  char* payload = (char*)advertisedDevice->getPayload();
-  for(int i = 0; i < advertisedDevice->getPayloadLength(); ++i){
-    if(payload[i] == 0x16 && advertisedDevice->getPayloadLength() >= i+2+sizeof(m_eddystoneData) && payload[i+1] == 0xAA && payload[i+2] == 0xFE && payload[i+3] == 0x20){
-      log_d("Eddystone TLM data frame starting at byte [%d]", i+3);
-      setData(std::string(payload+i+3, sizeof(m_eddystoneData)));
-      break;
-    }
-  }
-  _initHeadder();
-}
-
-String BLEEddystoneTLM::getData() {
-  return String((char*) &m_eddystoneData, sizeof(m_eddystoneData));
-} // getData
-
-BLEUUID BLEEddystoneTLM::getUUID() {
-  return beaconUUID;
-} // getUUID
-
-uint8_t BLEEddystoneTLM::getVersion() {
-  return m_eddystoneData.version;
-} // getVersion
-
-uint16_t BLEEddystoneTLM::getVolt() {
-  return ENDIAN_CHANGE_U16(m_eddystoneData.volt);
-} // getVolt
-
-float BLEEddystoneTLM::getTemp() {
-  return EDDYSTONE_TEMP_U16_TO_FLOAT(m_eddystoneData.temp);
-} // getTemp
-
-uint16_t BLEEddystoneTLM::getRawTemp() {
-  return ENDIAN_CHANGE_U16(m_eddystoneData.temp);
-} // getRawTemp
-
-uint32_t BLEEddystoneTLM::getCount() {
-  return ENDIAN_CHANGE_U32(m_eddystoneData.advCount);
-} // getCount
-
-uint32_t BLEEddystoneTLM::getTime() {
-  return (ENDIAN_CHANGE_U32(m_eddystoneData.tmil)) / 10;
-} // getTime
-
-String  BLEEddystoneTLM::getFrame(){
-  String frame(BLEHeadder);
-  frame += String((char*) &m_eddystoneData, sizeof(m_eddystoneData));
-  log_d("Compiled frame of length %d Bytes", frame.length());
-  for(int i = 0; i < frame.length(); ++i){
-    log_d("[%d]=0x%02X",i, frame[i]);
-  }
-  return frame;
-} // getServiceData
-
-String BLEEddystoneTLM::toString() {
-  String out = "";
-  uint32_t rawsec = ENDIAN_CHANGE_U32(m_eddystoneData.tmil);
-  char val[12];
-
-  out += "Version "; // + std::string(m_eddystoneData.version);
-  snprintf(val, sizeof(val), "%d", m_eddystoneData.version);
-  out += val;
-  out += "\n";
-  out += "Battery Voltage "; // + ENDIAN_CHANGE_U16(m_eddystoneData.volt);
-  snprintf(val, sizeof(val), "%d", ENDIAN_CHANGE_U16(m_eddystoneData.volt));
-  out += val;
-  out += " mV\n";
-
-  out += "Temperature ";
-  snprintf(val, sizeof(val), "%.2f", ((int16_t)ENDIAN_CHANGE_U16(m_eddystoneData.temp)) / 256.0f);
-  out += val;
-  out += " C\n";
-
-  out += "Adv. Count ";
-  snprintf(val, sizeof(val), "%d", ENDIAN_CHANGE_U32(m_eddystoneData.advCount));
-  out += val;
-  out += "\n";
-
-  out += "Time in seconds ";
-  snprintf(val, sizeof(val), "%d", rawsec/10);
-  out += val;
-  out += "\n";
-
-  out += "Time ";
-
-  snprintf(val, sizeof(val), "%04d", rawsec / 864000);
-  out += val;
-  out += ".";
-
-  snprintf(val, sizeof(val), "%02d", (rawsec / 36000) % 24);
-  out += val;
-  out += ":";
-
-  snprintf(val, sizeof(val), "%02d", (rawsec / 600) % 60);
-  out += val;
-  out += ":";
-
-  snprintf(val, sizeof(val), "%02d", (rawsec / 10) % 60);
-  out += val;
-  out += "\n";
-
-  return out;
-} // toString
-
-/**
- * Set the raw data for the beacon record.
- * Example:
- * uint8_t *payload = advertisedDevice.getPayload();
- * eddystoneTLM.setData(std::string((char*)payload+22, advertisedDevice.getPayloadLength() - 22));
- * Note: the offset 22 works for current implementation of example BLE_EddystoneTLM Beacon.ino, however
- *   the position is not static and it is programmers responsibility to align the data.
- * Data frame:
- * | Field  || Len | Type | UUID        | EddyStone TLM |
- * | Offset || 0   | 1    | 2           | 4             |
- * | Len    || 1 B | 1 B  | 2 B         | 14 B          |
- * | Data   || ??  | ??   | 0xAA | 0xFE | ???           |
- *
- * EddyStone TLM frame:
- * | Field  || Type  | Version | Batt mV     | Beacon temp | Cnt since boot | Time since boot |
- * | Offset || 0     | 1       | 2           | 4           | 6              | 10              |
- * | Len    || 1 B   | 1 B     | 2 B         | 2 B         | 4 B            | 4 B             |
- * | Data   || 0x20  | ??      | ??   | ??   | ??    | ??  |   |   |   |    |   |   |   |     |
- */
-void BLEEddystoneTLM::setData(std::string data) {
-  if (data.length() != sizeof(m_eddystoneData)) {
-    log_e("Unable to set the data ... length passed in was %d and expected %d", data.length(), sizeof(m_eddystoneData));
-    return;
-  }
-  memcpy(&m_eddystoneData, data.data(), data.length());
-} // setData
-
-void BLEEddystoneTLM::setUUID(BLEUUID l_uuid) {
-  beaconUUID = l_uuid;
-} // setUUID
-
-void BLEEddystoneTLM::setVersion(uint8_t version) {
-  m_eddystoneData.version = version;
-} // setVersion
-
-// Set voltage in ESP32 native Big endian and convert it to little endian used for BLE Frame
-void BLEEddystoneTLM::setVolt(uint16_t volt) {
-  m_eddystoneData.volt = ENDIAN_CHANGE_U16(volt);
-} // setVolt
-
-void BLEEddystoneTLM::setTemp(float temp) {
-  m_eddystoneData.temp = EDDYSTONE_TEMP_FLOAT_TO_U16(temp);
-} // setTemp
-
-void BLEEddystoneTLM::setCount(uint32_t advCount) {
-  m_eddystoneData.advCount = advCount;
-} // setCount
-
-void BLEEddystoneTLM::setTime(uint32_t tmil) {
-  m_eddystoneData.tmil = tmil;
-} // setTime
-
-void BLEEddystoneTLM::_initHeadder(){
-  BLEHeadder[0]  = 0x02; // Len
-  BLEHeadder[1]  = 0x01; // Type Flags
-  BLEHeadder[2]  = 0x06; // GENERAL_DISC_MODE 0x02 | BR_EDR_NOT_SUPPORTED 0x04
-  BLEHeadder[3]  = 0x03; // Len
-  BLEHeadder[4]  = 0x03; // Type 16-Bit UUID
-  BLEHeadder[5]  = 0xAA; // Eddystone UUID 2 -> 0xFEAA LSB
-  BLEHeadder[6]  = 0xFE; // Eddystone UUID 1 MSB
-  BLEHeadder[7]  = 0x11; // Length of TLM Beacon Data is constant 17 B (not counting the length field itself)
-  BLEHeadder[8]  = 0x16; // Type Service Data
-  BLEHeadder[9]  = 0xAA; // Eddystone UUID 2 -> 0xFEAA LSB
-  BLEHeadder[10] = 0xFE; // Eddystone UUID 1 MSB
-  BLEHeadder[11] = 0x20; // Eddystone Frame Type - TLM
-}
-
-#endif
diff --git a/libraries/BLE/src/BLEEddystoneTLM.h b/libraries/BLE/src/BLEEddystoneTLM.h
index 3981af4a4a9..17915a670da 100644
--- a/libraries/BLE/src/BLEEddystoneTLM.h
+++ b/libraries/BLE/src/BLEEddystoneTLM.h
@@ -1,8 +1,12 @@
 /*
- * BLEEddystoneTLM.cpp
+ * BLEEddystoneTLM.h
  *
  *  Created on: Mar 12, 2018
  *      Author: pcbreflux
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on pcbreflux's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef _BLEEddystoneTLM_H_
@@ -10,6 +14,9 @@
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
+#include "sdkconfig.h"
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
 #include "BLEUUID.h"
 #include <BLEAdvertisedDevice.h>
 
@@ -57,5 +64,6 @@ class BLEEddystoneTLM {
   } __attribute__((packed)) m_eddystoneData;
 };  // BLEEddystoneTLM
 
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* _BLEEddystoneTLM_H_ */
diff --git a/libraries/BLE/src/BLEEddystoneURL.cpp b/libraries/BLE/src/BLEEddystoneURL.cpp
index ddee8af0b30..495671ca49b 100644
--- a/libraries/BLE/src/BLEEddystoneURL.cpp
+++ b/libraries/BLE/src/BLEEddystoneURL.cpp
@@ -3,14 +3,20 @@
  *
  *  Created on: Mar 12, 2018
  *      Author: pcbreflux
+ *
  *  Upgraded on: Feb 20, 2023
  *      By: Tomas Pilny
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on pcbreflux's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
 #include <string.h>
 #include "esp32-hal-log.h"
 #include "BLEEddystoneURL.h"
@@ -158,7 +164,11 @@ void BLEEddystoneURL::setData(String data) {
 }  // setData
 
 void BLEEddystoneURL::setUUID(BLEUUID l_uuid) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
   uint16_t beaconUUID = l_uuid.getNative()->uuid.uuid16;
+#elif defined(CONFIG_NIMBLE_ENABLED)
+  uint16_t beaconUUID = l_uuid.getNative()->u16.value;
+#endif
   BLEHeadder[10] = beaconUUID >> 8;
   BLEHeadder[9] = beaconUUID & 0x00FF;
 }  // setUUID
diff --git a/libraries/BLE/src/BLEEddystoneURL.h b/libraries/BLE/src/BLEEddystoneURL.h
index 92668eb6855..9ed89a23694 100644
--- a/libraries/BLE/src/BLEEddystoneURL.h
+++ b/libraries/BLE/src/BLEEddystoneURL.h
@@ -3,9 +3,13 @@
  *
  *  Created on: Mar 12, 2018
  *      Author: pcbreflux
+ *
  *  Upgraded on: Feb 20, 2023
  *      By: Tomas Pilny
  *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on pcbreflux's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef _BLEEddystoneURL_H_
@@ -13,6 +17,9 @@
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
+#include "sdkconfig.h"
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
 #include "BLEUUID.h"
 #include <BLEAdvertisedDevice.h>
 #include "esp_bt.h"
@@ -57,5 +64,6 @@ class BLEEddystoneURL {
   char BLEHeadder[12];
 };  // BLEEddystoneURL
 
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* _BLEEddystoneURL_H_ */
diff --git a/libraries/BLE/src/BLEEddystoneURL.h.orig b/libraries/BLE/src/BLEEddystoneURL.h.orig
deleted file mode 100644
index 57722d0b769..00000000000
--- a/libraries/BLE/src/BLEEddystoneURL.h.orig
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * BLEEddystoneURL.cpp
- *
- *  Created on: Mar 12, 2018
- *      Author: pcbreflux
- *  Upgraded on: Feb 17, 2023
- *      By: Tomas Pilny
- *
- */
-
-#ifndef _BLEEddystoneURL_H_
-#define _BLEEddystoneURL_H_
-#include "BLEUUID.h"
-#include <BLEAdvertisedDevice.h>
-#include <Arduino.h>
-
-#define EDDYSTONE_URL_FRAME_TYPE 0x10
-
-extern String EDDYSTONE_URL_PREFIX[];
-extern String EDDYSTONE_URL_SUFFIX[];
-
-/**
- * @brief Representation of a beacon.
- * See:
- * * https://github.com/google/eddystone
- */
-class BLEEddystoneURL {
-public:
-  BLEEddystoneURL();
-  BLEEddystoneURL(BLEAdvertisedDevice *advertisedDevice);
-  std::string getData();
-  String      getFrame();
-  BLEUUID     getUUID();
-  int8_t      getPower();
-  std::string getURL();
-  String      getPrefix();
-  String      getSuffix();
-  std::string getDecodedURL();
-  void        setData(std::string data);
-  void        setUUID(BLEUUID l_uuid);
-  void        setPower(int8_t advertisedTxPower);
-  void        setURL(std::string url);
-  int         setSmartURL(String url);
-
-private:
-<<<<<<< Updated upstream
-	uint16_t beaconUUID;
-	uint8_t  lengthURL;
-	struct {
-		uint8_t frameType;
-		int8_t  advertisedTxPower;
-		uint8_t url[18];  // 18 bytes: 1 byte for URL scheme + up to 17 bytes of URL
-	} __attribute__((packed)) m_eddystoneData;
-
-=======
-  uint8_t lengthURL; // Describes length of URL part including prefix and suffix - max 18 B (excluding TX power, frame type and preceding header)
-  struct {
-    int8_t  advertisedTxPower;
-    uint8_t url[18]; // Byte [0] is for prefix. Last byte **can** contain suffix
-  } __attribute__((packed)) m_eddystoneData;
-  void _initHeadder();
-  char BLEHeadder[12];
->>>>>>> Stashed changes
-}; // BLEEddystoneURL
-
-#endif /* _BLEEddystoneURL_H_ */
diff --git a/libraries/BLE/src/BLEExceptions.cpp b/libraries/BLE/src/BLEExceptions.cpp
index 4e6c31fca22..b88ea337493 100644
--- a/libraries/BLE/src/BLEExceptions.cpp
+++ b/libraries/BLE/src/BLEExceptions.cpp
@@ -5,4 +5,9 @@
  *      Author: kolban
  */
 
+#include "soc/soc_caps.h"
+#if SOC_BLE_SUPPORTED
+
 //#include "BLEExceptions.h"
+
+#endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEHIDDevice.cpp b/libraries/BLE/src/BLEHIDDevice.cpp
index 0873aa1049f..a255879e2d8 100644
--- a/libraries/BLE/src/BLEHIDDevice.cpp
+++ b/libraries/BLE/src/BLEHIDDevice.cpp
@@ -3,15 +3,37 @@
  *
  *  Created on: Jan 03, 2018
  *      Author: chegewara
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
 #include "BLEHIDDevice.h"
 #include "BLE2904.h"
+#include "BLEDescriptor.h"
+
+/***************************************************************************
+ *                     NimBLE includes and definitions                     *
+ ***************************************************************************/
+
+#ifdef CONFIG_NIMBLE_ENABLED
+#include <host/ble_att.h>
+#endif
+
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
 
 BLEHIDDevice::BLEHIDDevice(BLEServer *server) {
   /*
@@ -45,10 +67,12 @@ BLEHIDDevice::BLEHIDDevice(BLEServer *server) {
   m_batteryLevelCharacteristic =
     m_batteryService->createCharacteristic((uint16_t)0x2a19, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
   m_batteryLevelCharacteristic->addDescriptor(batteryLevelDescriptor);
+#if CONFIG_BLUEDROID_ENABLED
   BLE2902 *batLevelIndicator = new BLE2902();
   // Battery Level Notification is ON by default, making it work always on BLE Pairing and Bonding
   batLevelIndicator->setNotifications(true);
   m_batteryLevelCharacteristic->addDescriptor(batLevelIndicator);
+#endif
 
   /*
 	 * This value is setup here because its default value in most usage cases, its very rare to use boot mode
@@ -117,16 +141,19 @@ BLECharacteristic *BLEHIDDevice::inputReport(uint8_t reportID) {
   BLECharacteristic *inputReportCharacteristic =
     m_hidService->createCharacteristic((uint16_t)0x2a4d, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
   BLEDescriptor *inputReportDescriptor = new BLEDescriptor(BLEUUID((uint16_t)0x2908));
-  BLE2902 *p2902 = new BLE2902();
   inputReportCharacteristic->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED);
   inputReportDescriptor->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED);
-  p2902->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED);
 
   uint8_t desc1_val[] = {reportID, 0x01};
   inputReportDescriptor->setValue((uint8_t *)desc1_val, 2);
-  inputReportCharacteristic->addDescriptor(p2902);
   inputReportCharacteristic->addDescriptor(inputReportDescriptor);
 
+#if CONFIG_BLUEDROID_ENABLED
+  BLE2902 *p2902 = new BLE2902();
+  p2902->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED);
+  inputReportCharacteristic->addDescriptor(p2902);
+#endif
+
   return inputReportCharacteristic;
 }
 
@@ -175,7 +202,9 @@ BLECharacteristic *BLEHIDDevice::featureReport(uint8_t reportID) {
  */
 BLECharacteristic *BLEHIDDevice::bootInput() {
   BLECharacteristic *bootInputCharacteristic = m_hidService->createCharacteristic((uint16_t)0x2a22, BLECharacteristic::PROPERTY_NOTIFY);
+#if CONFIG_BLUEDROID_ENABLED
   bootInputCharacteristic->addDescriptor(new BLE2902());
+#endif
 
   return bootInputCharacteristic;
 }
@@ -252,5 +281,5 @@ BLEService *BLEHIDDevice::batteryService() {
   return m_batteryService;
 }
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEHIDDevice.h b/libraries/BLE/src/BLEHIDDevice.h
index a92a23c21d5..9dde9452c12 100644
--- a/libraries/BLE/src/BLEHIDDevice.h
+++ b/libraries/BLE/src/BLEHIDDevice.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Jan 03, 2018
  *      Author: chegewara
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef _BLEHIDDEVICE_H_
@@ -12,7 +16,7 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
 
 #include "BLECharacteristic.h"
 #include "BLEService.h"
@@ -75,6 +79,6 @@ class BLEHIDDevice {
   BLECharacteristic *m_batteryLevelCharacteristic;  //0x2a19
 };
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* _BLEHIDDEVICE_H_ */
diff --git a/libraries/BLE/src/BLERemoteCharacteristic.cpp b/libraries/BLE/src/BLERemoteCharacteristic.cpp
index 60d5108c1fc..aec9500d6f3 100644
--- a/libraries/BLE/src/BLERemoteCharacteristic.cpp
+++ b/libraries/BLE/src/BLERemoteCharacteristic.cpp
@@ -3,46 +3,55 @@
  *
  *  Created on: Jul 8, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
-#include "BLERemoteCharacteristic.h"
-
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
-#include <esp_gattc_api.h>
 #include <esp_err.h>
 
 #include <sstream>
+#include "WString.h"
 //#include "BLEExceptions.h"
 #include "BLEUtils.h"
 #include "GeneralUtils.h"
+#include "BLERemoteCharacteristic.h"
 #include "BLERemoteDescriptor.h"
 #include "esp32-hal-log.h"
 
-/**
- * @brief Constructor.
- * @param [in] handle The BLE server side handle of this characteristic.
- * @param [in] uuid The UUID of this characteristic.
- * @param [in] charProp The properties of this characteristic.
- * @param [in] pRemoteService A reference to the remote service to which this remote characteristic pertains.
- */
-BLERemoteCharacteristic::BLERemoteCharacteristic(uint16_t handle, BLEUUID uuid, esp_gatt_char_prop_t charProp, BLERemoteService *pRemoteService) {
-  log_v(">> BLERemoteCharacteristic: handle: %d 0x%d, uuid: %s", handle, handle, uuid.toString().c_str());
-  m_handle = handle;
-  m_uuid = uuid;
-  m_charProp = charProp;
-  m_pRemoteService = pRemoteService;
-  m_notifyCallback = nullptr;
-  m_rawData = nullptr;
-  m_auth = ESP_GATT_AUTH_REQ_NONE;
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
 
-  retrieveDescriptors();  // Get the descriptors for this characteristic
-  log_v("<< BLERemoteCharacteristic");
-}  // BLERemoteCharacteristic
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gattc_api.h>
+#endif
+
+/***************************************************************************
+ *                           NimBLE includes                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <freertos/task.h>
+#include <host/ble_uuid.h>
+#include <host/ble_gatt.h>
+#include <host/ble_hs.h>
+#endif
+
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
 
 /**
  *@brief Destructor.
@@ -100,211 +109,6 @@ bool BLERemoteCharacteristic::canWriteNoResponse() {
   return (m_charProp & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) != 0;
 }  // canWriteNoResponse
 
-/*
-static bool compareSrvcId(esp_gatt_srvc_id_t id1, esp_gatt_srvc_id_t id2) {
-	if (id1.id.inst_id != id2.id.inst_id) {
-		return false;
-	}
-	if (!BLEUUID(id1.id.uuid).equals(BLEUUID(id2.id.uuid))) {
-		return false;
-	}
-	return true;
-} // compareSrvcId
-*/
-
-/*
-static bool compareGattId(esp_gatt_id_t id1, esp_gatt_id_t id2) {
-	if (id1.inst_id != id2.inst_id) {
-		return false;
-	}
-	if (!BLEUUID(id1.uuid).equals(BLEUUID(id2.uuid))) {
-		return false;
-	}
-	return true;
-} // compareCharId
-*/
-
-/**
- * @brief Handle GATT Client events.
- * When an event arrives for a GATT client we give this characteristic the opportunity to
- * take a look at it to see if there is interest in it.
- * @param [in] event The type of event.
- * @param [in] gattc_if The interface on which the event was received.
- * @param [in] evtParam Payload data for the event.
- * @returns N/A
- */
-void BLERemoteCharacteristic::gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *evtParam) {
-  switch (event) {
-    // ESP_GATTC_NOTIFY_EVT
-    //
-    // notify
-    // - uint16_t           conn_id    - The connection identifier of the server.
-    // - esp_bd_addr_t      remote_bda - The device address of the BLE server.
-    // - uint16_t           handle     - The handle of the characteristic for which the event is being received.
-    // - uint16_t           value_len  - The length of the received data.
-    // - uint8_t*           value      - The received data.
-    // - bool               is_notify  - True if this is a notify, false if it is an indicate.
-    //
-    // We have received a notification event which means that the server wishes us to know about a notification
-    // piece of data.  What we must now do is find the characteristic with the associated handle and then
-    // invoke its notification callback (if it has one).
-    case ESP_GATTC_NOTIFY_EVT:
-    {
-      if (evtParam->notify.handle != getHandle()) {
-        break;
-      }
-      if (m_notifyCallback != nullptr) {
-        log_d("Invoking callback for notification on characteristic %s", toString().c_str());
-        m_notifyCallback(this, evtParam->notify.value, evtParam->notify.value_len, evtParam->notify.is_notify);
-      }  // End we have a callback function ...
-      break;
-    }  // ESP_GATTC_NOTIFY_EVT
-
-    // ESP_GATTC_READ_CHAR_EVT
-    // This event indicates that the server has responded to the read request.
-    //
-    // read:
-    // - esp_gatt_status_t  status
-    // - uint16_t           conn_id
-    // - uint16_t           handle
-    // - uint8_t*           value
-    // - uint16_t           value_len
-    case ESP_GATTC_READ_CHAR_EVT:
-    {
-      // If this event is not for us, then nothing further to do.
-      if (evtParam->read.handle != getHandle()) {
-        break;
-      }
-
-      // At this point, we have determined that the event is for us, so now we save the value
-      // and unlock the semaphore to ensure that the requester of the data can continue.
-      if (evtParam->read.status == ESP_GATT_OK) {
-        m_value = String((char *)evtParam->read.value, evtParam->read.value_len);
-        if (m_rawData != nullptr) {
-          free(m_rawData);
-        }
-        m_rawData = (uint8_t *)calloc(evtParam->read.value_len, sizeof(uint8_t));
-        memcpy(m_rawData, evtParam->read.value, evtParam->read.value_len);
-      } else {
-        m_value = "";
-      }
-
-      m_semaphoreReadCharEvt.give();
-      break;
-    }  // ESP_GATTC_READ_CHAR_EVT
-
-    // ESP_GATTC_REG_FOR_NOTIFY_EVT
-    //
-    // reg_for_notify:
-    // - esp_gatt_status_t status
-    // - uint16_t          handle
-    case ESP_GATTC_REG_FOR_NOTIFY_EVT:
-    {
-      // If the request is not for this BLERemoteCharacteristic then move on to the next.
-      if (evtParam->reg_for_notify.handle != getHandle()) {
-        break;
-      }
-
-      // We have processed the notify registration and can unlock the semaphore.
-      m_semaphoreRegForNotifyEvt.give();
-      break;
-    }  // ESP_GATTC_REG_FOR_NOTIFY_EVT
-
-    // ESP_GATTC_UNREG_FOR_NOTIFY_EVT
-    //
-    // unreg_for_notify:
-    // - esp_gatt_status_t status
-    // - uint16_t          handle
-    case ESP_GATTC_UNREG_FOR_NOTIFY_EVT:
-    {
-      if (evtParam->unreg_for_notify.handle != getHandle()) {
-        break;
-      }
-      // We have processed the notify un-registration and can unlock the semaphore.
-      m_semaphoreRegForNotifyEvt.give();
-      break;
-    }  // ESP_GATTC_UNREG_FOR_NOTIFY_EVT:
-
-    // ESP_GATTC_WRITE_CHAR_EVT
-    //
-    // write:
-    // - esp_gatt_status_t status
-    // - uint16_t          conn_id
-    // - uint16_t          handle
-    case ESP_GATTC_WRITE_CHAR_EVT:
-    {
-      // Determine if this event is for us and, if not, pass onwards.
-      if (evtParam->write.handle != getHandle()) {
-        break;
-      }
-
-      // There is nothing further we need to do here.  This is merely an indication
-      // that the write has completed and we can unlock the caller.
-      m_semaphoreWriteCharEvt.give();
-      break;
-    }  // ESP_GATTC_WRITE_CHAR_EVT
-
-    case ESP_GATTC_READ_DESCR_EVT:
-    case ESP_GATTC_WRITE_DESCR_EVT:
-      for (auto &myPair : m_descriptorMap) {
-        myPair.second->gattClientEventHandler(event, gattc_if, evtParam);
-      }
-      break;
-
-    case ESP_GATTC_DISCONNECT_EVT:
-      // Cleanup semaphores to avoid deadlocks.
-      m_semaphoreReadCharEvt.give(1);
-      m_semaphoreWriteCharEvt.give(1);
-      break;
-
-    default: break;
-  }  // End switch
-};  // gattClientEventHandler
-
-/**
- * @brief Populate the descriptors (if any) for this characteristic.
- */
-void BLERemoteCharacteristic::retrieveDescriptors() {
-  log_v(">> retrieveDescriptors() for characteristic: %s", getUUID().toString().c_str());
-
-  removeDescriptors();  // Remove any existing descriptors.
-
-  // Loop over each of the descriptors within the service associated with this characteristic.
-  // For each descriptor we find, create a BLERemoteDescriptor instance.
-  uint16_t offset = 0;
-  esp_gattc_descr_elem_t result;
-  while (true) {
-    uint16_t count = 10;
-    esp_gatt_status_t status = ::esp_ble_gattc_get_all_descr(
-      getRemoteService()->getClient()->getGattcIf(), getRemoteService()->getClient()->getConnId(), getHandle(), &result, &count, offset
-    );
-
-    if (status == ESP_GATT_INVALID_OFFSET) {  // We have reached the end of the entries.
-      break;
-    }
-
-    if (status != ESP_GATT_OK) {
-      log_e("esp_ble_gattc_get_all_descr: %s", BLEUtils::gattStatusToString(status).c_str());
-      break;
-    }
-
-    if (count == 0) {
-      break;
-    }
-
-    log_d("Found a descriptor: Handle: %d, UUID: %s", result.handle, BLEUUID(result.uuid).toString().c_str());
-
-    // We now have a new characteristic ... let us add that to our set of known characteristics
-    BLERemoteDescriptor *pNewRemoteDescriptor = new BLERemoteDescriptor(result.handle, BLEUUID(result.uuid), this);
-
-    m_descriptorMap.insert(std::pair<std::string, BLERemoteDescriptor *>(pNewRemoteDescriptor->getUUID().toString().c_str(), pNewRemoteDescriptor));
-
-    offset++;
-  }  // while true
-  //m_haveCharacteristics = true; // Remember that we have received the characteristics.
-  log_v("<< retrieveDescriptors(): Found %d descriptors.", offset);
-}  // getDescriptors
-
 /**
  * @brief Retrieve the map of descriptors keyed by UUID.
  */
@@ -404,44 +208,6 @@ float BLERemoteCharacteristic::readFloat() {
   return 0.0;
 }  // readFloat
 
-/**
- * @brief Read the value of the remote characteristic.
- * @return The value of the remote characteristic.
- */
-String BLERemoteCharacteristic::readValue() {
-  log_v(">> readValue(): uuid: %s, handle: %d 0x%.2x", getUUID().toString().c_str(), getHandle(), getHandle());
-
-  // Check to see that we are connected.
-  if (!getRemoteService()->getClient()->isConnected()) {
-    log_e("Disconnected");
-    return String();
-  }
-
-  m_semaphoreReadCharEvt.take("readValue");
-
-  // Ask the BLE subsystem to retrieve the value for the remote hosted characteristic.
-  // This is an asynchronous request which means that we must block waiting for the response
-  // to become available.
-  esp_err_t errRc = ::esp_ble_gattc_read_char(
-    m_pRemoteService->getClient()->getGattcIf(),
-    m_pRemoteService->getClient()->getConnId(),  // The connection ID to the BLE server
-    getHandle(),                                 // The handle of this characteristic
-    m_auth
-  );  // Security
-
-  if (errRc != ESP_OK) {
-    log_e("esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-    return "";
-  }
-
-  // Block waiting for the event that indicates that the read has completed.  When it has, the String found
-  // in m_value will contain our data.
-  m_semaphoreReadCharEvt.wait("readValue");
-
-  log_v("<< readValue(): length: %d", m_value.length());
-  return m_value;
-}  // readValue
-
 /**
  * @brief Register for notifications.
  * @param [in] notifyCallback A callback to be invoked for a notification.  If NULL is provided then we are
@@ -451,13 +217,14 @@ String BLERemoteCharacteristic::readValue() {
 void BLERemoteCharacteristic::registerForNotify(notify_callback notifyCallback, bool notifications, bool descriptorRequiresRegistration) {
   log_v(">> registerForNotify(): %s", toString().c_str());
 
+#if defined(CONFIG_BLUEDROID_ENABLED)
   m_notifyCallback = notifyCallback;  // Save the notification callback.
 
   m_semaphoreRegForNotifyEvt.take("registerForNotify");
 
   if (notifyCallback != nullptr) {  // If we have a callback function, then this is a registration.
     esp_err_t errRc = ::esp_ble_gattc_register_for_notify(
-      m_pRemoteService->getClient()->getGattcIf(), *m_pRemoteService->getClient()->getPeerAddress().getNative(), getHandle()
+      m_pRemoteService->getClient()->getGattcIf(), m_pRemoteService->getClient()->getPeerAddress().getNative(), getHandle()
     );
 
     if (errRc != ESP_OK) {
@@ -475,7 +242,7 @@ void BLERemoteCharacteristic::registerForNotify(notify_callback notifyCallback,
   }  // End Register
   else {  // If we weren't passed a callback function, then this is an unregistration.
     esp_err_t errRc = ::esp_ble_gattc_unregister_for_notify(
-      m_pRemoteService->getClient()->getGattcIf(), *m_pRemoteService->getClient()->getPeerAddress().getNative(), getHandle()
+      m_pRemoteService->getClient()->getGattcIf(), m_pRemoteService->getClient()->getPeerAddress().getNative(), getHandle()
     );
 
     if (errRc != ESP_OK) {
@@ -491,8 +258,22 @@ void BLERemoteCharacteristic::registerForNotify(notify_callback notifyCallback,
 
   m_semaphoreRegForNotifyEvt.wait("registerForNotify");
 
-  log_v("<< registerForNotify()");
-}  // registerForNotify
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  bool success;
+  if (notifyCallback != nullptr) {
+    success = subscribe(notifications, notifyCallback, descriptorRequiresRegistration);
+  } else {
+    success = unsubscribe(descriptorRequiresRegistration);
+  }
+
+  if (!success) {
+    log_e("Failed to subscribe/unsubscribe for notify");
+  }
+#endif
+  log_v("<< registerForNotify()");
+}  // registerForNotify
 
 /**
  * @brief Delete the descriptors in the descriptor map.
@@ -532,8 +313,8 @@ String BLERemoteCharacteristic::toString() {
  * @param [in] response Do we expect a response?
  * @return N/A.
  */
-void BLERemoteCharacteristic::writeValue(String newValue, bool response) {
-  writeValue((uint8_t *)newValue.c_str(), newValue.length(), response);
+bool BLERemoteCharacteristic::writeValue(String newValue, bool response) {
+  return writeValue((uint8_t *)newValue.c_str(), newValue.length(), response);
 }  // writeValue
 
 /**
@@ -544,58 +325,678 @@ void BLERemoteCharacteristic::writeValue(String newValue, bool response) {
  * @param [in] response Whether we require a response from the write.
  * @return N/A.
  */
-void BLERemoteCharacteristic::writeValue(uint8_t newValue, bool response) {
-  writeValue(&newValue, 1, response);
+bool BLERemoteCharacteristic::writeValue(uint8_t newValue, bool response) {
+  return writeValue(&newValue, 1, response);
 }  // writeValue
 
+/**
+ * @brief Read raw data from remote characteristic as hex bytes
+ * @return return pointer data read
+ */
+uint8_t *BLERemoteCharacteristic::readRawData() {
+  return m_rawData;
+}
+
+/**
+ * @brief Set authentication request type for characteristic
+ * @param [in] auth Authentication request type.
+ */
+void BLERemoteCharacteristic::setAuth(uint8_t auth) {
+  m_auth = auth;
+}
+
+/***************************************************************************
+ *                           Bluedroid functions                           *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+
+/**
+ * @brief Constructor.
+ * @param [in] handle The BLE server side handle of this characteristic.
+ * @param [in] uuid The UUID of this characteristic.
+ * @param [in] charProp The properties of this characteristic.
+ * @param [in] pRemoteService A reference to the remote service to which this remote characteristic pertains.
+ */
+BLERemoteCharacteristic::BLERemoteCharacteristic(uint16_t handle, BLEUUID uuid, esp_gatt_char_prop_t charProp, BLERemoteService *pRemoteService) {
+  log_v(">> BLERemoteCharacteristic: handle: %d 0x%d, uuid: %s", handle, handle, uuid.toString().c_str());
+  m_handle = handle;
+  m_uuid = uuid;
+  m_charProp = charProp;
+  m_pRemoteService = pRemoteService;
+  m_notifyCallback = nullptr;
+  m_rawData = nullptr;
+  m_auth = ESP_GATT_AUTH_REQ_NONE;
+
+  retrieveDescriptors();  // Get the descriptors for this characteristic
+  log_v("<< BLERemoteCharacteristic");
+}  // BLERemoteCharacteristic
+
+/**
+ * @brief Handle GATT Client events.
+ * When an event arrives for a GATT client we give this characteristic the opportunity to
+ * take a look at it to see if there is interest in it.
+ * @param [in] event The type of event.
+ * @param [in] gattc_if The interface on which the event was received.
+ * @param [in] evtParam Payload data for the event.
+ * @returns N/A
+ */
+void BLERemoteCharacteristic::gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *evtParam) {
+  switch (event) {
+    // ESP_GATTC_NOTIFY_EVT
+    //
+    // notify
+    // - uint16_t           conn_id    - The connection identifier of the server.
+    // - esp_bd_addr_t      remote_bda - The device address of the BLE server.
+    // - uint16_t           handle     - The handle of the characteristic for which the event is being received.
+    // - uint16_t           value_len  - The length of the received data.
+    // - uint8_t*           value      - The received data.
+    // - bool               is_notify  - True if this is a notify, false if it is an indicate.
+    //
+    // We have received a notification event which means that the server wishes us to know about a notification
+    // piece of data.  What we must now do is find the characteristic with the associated handle and then
+    // invoke its notification callback (if it has one).
+    case ESP_GATTC_NOTIFY_EVT:
+    {
+      if (evtParam->notify.handle != getHandle()) {
+        break;
+      }
+      if (m_notifyCallback != nullptr) {
+        log_d("Invoking callback for notification on characteristic %s", toString().c_str());
+        m_notifyCallback(this, evtParam->notify.value, evtParam->notify.value_len, evtParam->notify.is_notify);
+      }  // End we have a callback function ...
+      break;
+    }  // ESP_GATTC_NOTIFY_EVT
+
+    // ESP_GATTC_READ_CHAR_EVT
+    // This event indicates that the server has responded to the read request.
+    //
+    // read:
+    // - esp_gatt_status_t  status
+    // - uint16_t           conn_id
+    // - uint16_t           handle
+    // - uint8_t*           value
+    // - uint16_t           value_len
+    case ESP_GATTC_READ_CHAR_EVT:
+    {
+      // If this event is not for us, then nothing further to do.
+      if (evtParam->read.handle != getHandle()) {
+        break;
+      }
+
+      // At this point, we have determined that the event is for us, so now we save the value
+      // and unlock the semaphore to ensure that the requester of the data can continue.
+      if (evtParam->read.status == ESP_GATT_OK) {
+        m_value = String((char *)evtParam->read.value, evtParam->read.value_len);
+        if (m_rawData != nullptr) {
+          free(m_rawData);
+        }
+        m_rawData = (uint8_t *)calloc(evtParam->read.value_len, sizeof(uint8_t));
+        memcpy(m_rawData, evtParam->read.value, evtParam->read.value_len);
+      } else {
+        m_value = "";
+      }
+
+      m_semaphoreReadCharEvt.give();
+      break;
+    }  // ESP_GATTC_READ_CHAR_EVT
+
+    // ESP_GATTC_REG_FOR_NOTIFY_EVT
+    //
+    // reg_for_notify:
+    // - esp_gatt_status_t status
+    // - uint16_t          handle
+    case ESP_GATTC_REG_FOR_NOTIFY_EVT:
+    {
+      // If the request is not for this BLERemoteCharacteristic then move on to the next.
+      if (evtParam->reg_for_notify.handle != getHandle()) {
+        break;
+      }
+
+      // We have processed the notify registration and can unlock the semaphore.
+      m_semaphoreRegForNotifyEvt.give();
+      break;
+    }  // ESP_GATTC_REG_FOR_NOTIFY_EVT
+
+    // ESP_GATTC_UNREG_FOR_NOTIFY_EVT
+    //
+    // unreg_for_notify:
+    // - esp_gatt_status_t status
+    // - uint16_t          handle
+    case ESP_GATTC_UNREG_FOR_NOTIFY_EVT:
+    {
+      if (evtParam->unreg_for_notify.handle != getHandle()) {
+        break;
+      }
+      // We have processed the notify un-registration and can unlock the semaphore.
+      m_semaphoreRegForNotifyEvt.give();
+      break;
+    }  // ESP_GATTC_UNREG_FOR_NOTIFY_EVT:
+
+    // ESP_GATTC_WRITE_CHAR_EVT
+    //
+    // write:
+    // - esp_gatt_status_t status
+    // - uint16_t          conn_id
+    // - uint16_t          handle
+    case ESP_GATTC_WRITE_CHAR_EVT:
+    {
+      // Determine if this event is for us and, if not, pass onwards.
+      if (evtParam->write.handle != getHandle()) {
+        break;
+      }
+
+      // There is nothing further we need to do here.  This is merely an indication
+      // that the write has completed and we can unlock the caller.
+      m_semaphoreWriteCharEvt.give();
+      break;
+    }  // ESP_GATTC_WRITE_CHAR_EVT
+
+    case ESP_GATTC_READ_DESCR_EVT:
+    case ESP_GATTC_WRITE_DESCR_EVT:
+      for (auto &myPair : m_descriptorMap) {
+        myPair.second->gattClientEventHandler(event, gattc_if, evtParam);
+      }
+      break;
+
+    case ESP_GATTC_DISCONNECT_EVT:
+      // Cleanup semaphores to avoid deadlocks.
+      m_semaphoreReadCharEvt.give(1);
+      m_semaphoreWriteCharEvt.give(1);
+      break;
+
+    default: break;
+  }  // End switch
+};  // gattClientEventHandler
+
+/**
+ * @brief Populate the descriptors (if any) for this characteristic.
+ */
+void BLERemoteCharacteristic::retrieveDescriptors() {
+  log_v(">> retrieveDescriptors() for characteristic: %s", getUUID().toString().c_str());
+
+  removeDescriptors();  // Remove any existing descriptors.
+
+  // Loop over each of the descriptors within the service associated with this characteristic.
+  // For each descriptor we find, create a BLERemoteDescriptor instance.
+  uint16_t offset = 0;
+  esp_gattc_descr_elem_t result;
+  while (true) {
+    uint16_t count = 10;
+    esp_gatt_status_t status = ::esp_ble_gattc_get_all_descr(
+      getRemoteService()->getClient()->getGattcIf(), getRemoteService()->getClient()->getConnId(), getHandle(), &result, &count, offset
+    );
+
+    if (status == ESP_GATT_INVALID_OFFSET) {  // We have reached the end of the entries.
+      break;
+    }
+
+    if (status != ESP_GATT_OK) {
+      log_e("esp_ble_gattc_get_all_descr: %s", BLEUtils::gattStatusToString(status).c_str());
+      break;
+    }
+
+    if (count == 0) {
+      break;
+    }
+
+    log_d("Found a descriptor: Handle: %d, UUID: %s", result.handle, BLEUUID(result.uuid).toString().c_str());
+
+    // We now have a new characteristic ... let us add that to our set of known characteristics
+    BLERemoteDescriptor *pNewRemoteDescriptor = new BLERemoteDescriptor(result.handle, BLEUUID(result.uuid), this);
+
+    m_descriptorMap.insert(std::pair<std::string, BLERemoteDescriptor *>(pNewRemoteDescriptor->getUUID().toString().c_str(), pNewRemoteDescriptor));
+
+    offset++;
+  }  // while true
+  //m_haveCharacteristics = true; // Remember that we have received the characteristics.
+  log_v("<< retrieveDescriptors(): Found %d descriptors.", offset);
+}  // getDescriptors
+
+/**
+ * @brief Read the value of the remote characteristic.
+ * @return The value of the remote characteristic.
+ */
+String BLERemoteCharacteristic::readValue() {
+  log_v(">> readValue(): uuid: %s, handle: %d 0x%.2x", getUUID().toString().c_str(), getHandle(), getHandle());
+
+  // Check to see that we are connected.
+  if (!getRemoteService()->getClient()->isConnected()) {
+    log_e("Disconnected");
+    return String();
+  }
+
+  m_semaphoreReadCharEvt.take("readValue");
+
+  // Ask the BLE subsystem to retrieve the value for the remote hosted characteristic.
+  // This is an asynchronous request which means that we must block waiting for the response
+  // to become available.
+  esp_err_t errRc = ::esp_ble_gattc_read_char(
+    m_pRemoteService->getClient()->getGattcIf(),
+    m_pRemoteService->getClient()->getConnId(),  // The connection ID to the BLE server
+    getHandle(),                                 // The handle of this characteristic
+    (esp_gatt_auth_req_t)m_auth
+  );  // Security
+
+  if (errRc != ESP_OK) {
+    log_e("esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+    return "";
+  }
+
+  // Block waiting for the event that indicates that the read has completed.  When it has, the String found
+  // in m_value will contain our data.
+  m_semaphoreReadCharEvt.wait("readValue");
+
+  log_v("<< readValue(): length: %d", m_value.length());
+  return m_value;
+}  // readValue
+
 /**
  * @brief Write the new value for the characteristic from a data buffer.
  * @param [in] data A pointer to a data buffer.
  * @param [in] length The length of the data in the data buffer.
  * @param [in] response Whether we require a response from the write.
+ * @return True if successful
  */
-void BLERemoteCharacteristic::writeValue(uint8_t *data, size_t length, bool response) {
+bool BLERemoteCharacteristic::writeValue(uint8_t *data, size_t length, bool response) {
   // writeValue(String((char*)data, length), response);
   log_v(">> writeValue(), length: %d", length);
 
   // Check to see that we are connected.
   if (!getRemoteService()->getClient()->isConnected()) {
     log_e("Disconnected");
-    return;
+    return false;
   }
 
   m_semaphoreWriteCharEvt.take("writeValue");
   // Invoke the ESP-IDF API to perform the write.
   esp_err_t errRc = ::esp_ble_gattc_write_char(
     m_pRemoteService->getClient()->getGattcIf(), m_pRemoteService->getClient()->getConnId(), getHandle(), length, data,
-    response ? ESP_GATT_WRITE_TYPE_RSP : ESP_GATT_WRITE_TYPE_NO_RSP, m_auth
+    response ? ESP_GATT_WRITE_TYPE_RSP : ESP_GATT_WRITE_TYPE_NO_RSP, (esp_gatt_auth_req_t)m_auth
   );
 
   if (errRc != ESP_OK) {
     log_e("esp_ble_gattc_write_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-    return;
+    return false;
   }
 
   m_semaphoreWriteCharEvt.wait("writeValue");
 
   log_v("<< writeValue");
+  return true;
 }  // writeValue
 
+#endif
+
+/***************************************************************************
+ *                           NimBLE functions                              *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
 /**
- * @brief Read raw data from remote characteristic as hex bytes
- * @return return pointer data read
+ * @brief Constructor.
+ * @param [in] reference to the service this characteristic belongs to.
+ * @param [in] ble_gatt_chr struct defined as:
+ *  struct ble_gatt_chr {
+ *      uint16_t def_handle;
+ *      uint16_t val_handle;
+ *      uint8_t properties;
+ *      ble_uuid_any_t uuid;
+ *  };
  */
-uint8_t *BLERemoteCharacteristic::readRawData() {
-  return m_rawData;
+BLERemoteCharacteristic::BLERemoteCharacteristic(BLERemoteService *pRemoteService, const struct ble_gatt_chr *chr) {
+  log_v(">> BLERemoteCharacteristic()");
+  switch (chr->uuid.u.type) {
+    case BLE_UUID_TYPE_16:  m_uuid = BLEUUID(chr->uuid.u16.value); break;
+    case BLE_UUID_TYPE_32:  m_uuid = BLEUUID(chr->uuid.u32.value); break;
+    case BLE_UUID_TYPE_128: m_uuid = BLEUUID(const_cast<ble_uuid128_t *>(&chr->uuid.u128)); break;
+    default:                break;
+  }
+
+  m_handle = chr->val_handle;
+  m_defHandle = chr->def_handle;
+  m_endHandle = 0;
+  m_charProp = chr->properties;
+  m_pRemoteService = pRemoteService;
+  m_notifyCallback = nullptr;
+  m_rawData = nullptr;
+  m_auth = 0;
+
+  retrieveDescriptors();  // Get the descriptors for this characteristic
+
+  log_v("<< BLERemoteCharacteristic(): %s", m_uuid.toString().c_str());
+}  // BLERemoteCharacteristic
+
+/**
+ * @brief Callback used by the API when a descriptor is discovered or search complete.
+ */
+int BLERemoteCharacteristic::descriptorDiscCB(
+  uint16_t conn_handle, const struct ble_gatt_error *error, uint16_t chr_val_handle, const struct ble_gatt_dsc *dsc, void *arg
+) {
+  int rc = error->status;
+  log_d("Descriptor Discovered >> status: %d handle: %d", rc, (rc == 0) ? dsc->handle : -1);
+
+  desc_filter_t *filter = (desc_filter_t *)arg;
+  const BLEUUID *uuid_filter = filter->uuid;
+  BLETaskData *pTaskData = (BLETaskData *)filter->task_data;
+  BLERemoteCharacteristic *characteristic = (BLERemoteCharacteristic *)pTaskData->m_pInstance;
+
+  if (characteristic->getRemoteService()->getClient()->getConnId() != conn_handle) {
+    return 0;
+  }
+
+  if (rc == 0 && characteristic->getHandle() == chr_val_handle && (!uuid_filter || ble_uuid_cmp(&uuid_filter->getNative()->u, &dsc->uuid.u) == 0)) {
+    BLERemoteDescriptor *pNewRemoteDescriptor = new BLERemoteDescriptor(characteristic, dsc);
+    characteristic->m_descriptorMap.insert(
+      std::pair<std::string, BLERemoteDescriptor *>(pNewRemoteDescriptor->getUUID().toString().c_str(), pNewRemoteDescriptor)
+    );
+    rc = !!uuid_filter * BLE_HS_EDONE;
+  }
+
+  if (rc != 0) {
+    BLEUtils::taskRelease(*pTaskData, rc);
+    log_d("<< Descriptor Discovery");
+  }
+
+  return rc;
 }
 
 /**
- * @brief Set authentication request type for characteristic
- * @param [in] auth Authentication request type.
+ * @brief Callback for characteristic read operation.
+ * @return success == 0 or error code.
  */
-void BLERemoteCharacteristic::setAuth(esp_gatt_auth_req_t auth) {
-  m_auth = auth;
+int BLERemoteCharacteristic::onReadCB(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg) {
+  BLETaskData *pTaskData = static_cast<BLETaskData *>(arg);
+  BLERemoteCharacteristic *characteristic = static_cast<BLERemoteCharacteristic *>(pTaskData->m_pInstance);
+
+  if (error->status == BLE_HS_ENOTCONN) {
+    log_e("<< Characteristic Read; Not connected");
+    BLEUtils::taskRelease(*pTaskData, error->status);
+    return error->status;
+  }
+
+  if (characteristic->getRemoteService()->getClient()->getConnId() != conn_handle) {
+    return 0;
+  }
+
+  int rc = error->status;
+  log_i("Read complete; status=%d conn_handle=%d", rc, conn_handle);
+
+  String *strBuf = (String *)pTaskData->m_pBuf;
+
+  if (rc == 0) {
+    if (attr) {
+      uint32_t data_len = OS_MBUF_PKTLEN(attr->om);
+      if (((*strBuf).length() + data_len) > BLE_ATT_ATTR_MAX_LEN) {
+        rc = BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
+      } else {
+        log_i("Got %d bytes", data_len);
+        (*strBuf) += String((char *)attr->om->om_data, data_len);
+        return 0;
+      }
+    }
+  }
+
+  BLEUtils::taskRelease(*pTaskData, rc);
+  return rc;
 }
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+/**
+ * @brief Callback for characteristic write operation.
+ * @return success == 0 or error code.
+ */
+int BLERemoteCharacteristic::onWriteCB(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg) {
+  BLETaskData *pTaskData = static_cast<BLETaskData *>(arg);
+  BLERemoteCharacteristic *characteristic = static_cast<BLERemoteCharacteristic *>(pTaskData->m_pInstance);
+
+  if (error->status == BLE_HS_ENOTCONN) {
+    log_e("<< Characteristic Write; Not connected");
+    BLEUtils::taskRelease(*pTaskData, error->status);
+    return error->status;
+  }
+
+  if (characteristic->getRemoteService()->getClient()->getConnId() != conn_handle) {
+    return 0;
+  }
+
+  log_i("Write complete; status=%d conn_handle=%d", error->status, conn_handle);
+  BLEUtils::taskRelease(*pTaskData, error->status);
+  return 0;
+}
+
+/**
+ * @brief Populate the descriptors (if any) for this characteristic.
+ * @param [in] the end handle of the characteristic, or the service, whichever comes first.
+ */
+bool BLERemoteCharacteristic::retrieveDescriptors(const BLEUUID *uuid_filter) {
+  log_d(">> retrieveDescriptors() for characteristic: %s", getUUID().toString().c_str());
+
+  // If this is the last handle then there are no descriptors
+  if (m_handle == getRemoteService()->getEndHandle()) {
+    log_d("<< retrieveDescriptors(): No descriptors found");
+    return true;
+  }
+
+  BLETaskData taskData(const_cast<BLERemoteCharacteristic *>(this));
+  desc_filter_t filter = {uuid_filter, &taskData};
+  int rc = 0;
+
+  rc = ble_gattc_disc_all_dscs(getRemoteService()->getClient()->getConnId(), m_handle, m_endHandle, BLERemoteCharacteristic::descriptorDiscCB, &filter);
+
+  if (rc != 0) {
+    log_e("ble_gattc_disc_all_dscs: rc=%d %s", rc, BLEUtils::returnCodeToString(rc));
+    return false;
+  }
+
+  [[maybe_unused]]
+  size_t prevDscCount = m_descriptorMap.size();
+  BLEUtils::taskWait(taskData, BLE_NPL_TIME_FOREVER);
+  rc = ((BLETaskData *)filter.task_data)->m_flags;
+
+  if (rc != BLE_HS_EDONE) {
+    log_e("<< retrieveDescriptors(): failed: rc=%d %s", rc, BLEUtils::returnCodeToString(rc));
+    return false;
+  }
+
+  log_d("<< retrieveDescriptors(): Found %d descriptors.", m_descriptorMap.size() - prevDscCount);
+  return true;
+}  // retrieveDescriptors
+
+/**
+ * @brief Read the value of the remote characteristic.
+ * @return The value of the remote characteristic.
+ */
+String BLERemoteCharacteristic::readValue() {
+  log_d(">> readValue(): uuid: %s, handle: %d 0x%.2x", getUUID().toString().c_str(), getHandle(), getHandle());
+
+  BLEClient *pClient = getRemoteService()->getClient();
+  String value{};
+
+  if (!pClient->isConnected()) {
+    log_e("Disconnected");
+    return value;
+  }
+
+  int rc = 0;
+  int retryCount = 1;
+  BLETaskData taskData(const_cast<BLERemoteCharacteristic *>(this), 0, &value);
+
+  do {
+    rc = ble_gattc_read_long(pClient->getConnId(), m_handle, 0, BLERemoteCharacteristic::onReadCB, &taskData);
+    if (rc != 0) {
+      goto exit;
+    }
+
+    BLEUtils::taskWait(taskData, BLE_NPL_TIME_FOREVER);
+    rc = taskData.m_flags;
+
+    switch (rc) {
+      case 0:
+      case BLE_HS_EDONE: rc = 0; break;
+      // Characteristic is not long-readable, return with what we have.
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_ATTR_NOT_LONG):
+        log_i("Attribute not long");
+        rc = ble_gattc_read(pClient->getConnId(), m_handle, BLERemoteCharacteristic::onReadCB, &taskData);
+        if (rc != 0) {
+          goto exit;
+        }
+        retryCount++;
+        break;
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHEN):
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHOR):
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_ENC):
+        if (retryCount && pClient->secureConnection()) {
+          break;
+        }
+      /* Else falls through. */
+      default: goto exit;
+    }
+  } while (rc != 0 && retryCount--);
+
+  m_semaphoreReadCharEvt.take("readValue");
+  m_value = value;
+  m_rawData = (uint8_t *)calloc(value.length(), sizeof(uint8_t));
+  for (size_t i = 0; i < value.length(); i++) {
+    m_rawData[i] = value[i];
+  }
+  m_semaphoreReadCharEvt.give();
+
+exit:
+  if (rc != 0) {
+    log_e("<< readValue failed rc=%d, %s", rc, BLEUtils::returnCodeToString(rc));
+  } else {
+    log_d("<< readValue length: %d rc=%d", value.length(), rc);
+  }
+
+  return value;
+}  // readValue
+
+/**
+ * @brief Write the new value for the characteristic from a data buffer.
+ * @param [in] data A pointer to a data buffer.
+ * @param [in] length The length of the data in the data buffer.
+ * @param [in] response Whether we require a response from the write.
+ * @return false if not connected or cant perform write for some reason.
+ */
+bool BLERemoteCharacteristic::writeValue(uint8_t *data, size_t length, bool response) {
+  log_d(">> writeValue(), length: %d", length);
+
+  BLEClient *pClient = getRemoteService()->getClient();
+
+  if (!pClient->isConnected()) {
+    log_e("Disconnected");
+    return false;
+  }
+
+  int rc = 0;
+  int retryCount = 1;
+  uint16_t mtu = ble_att_mtu(pClient->getConnId()) - 3;
+  BLETaskData taskData(const_cast<BLERemoteCharacteristic *>(this));
+
+  // Check if the data length is longer than we can write in one connection event.
+  // If so we must do a long write which requires a response.
+  if (length <= mtu && !response) {
+    rc = ble_gattc_write_no_rsp_flat(pClient->getConnId(), m_handle, data, length);
+    goto exit;
+  }
+
+  do {
+    if (length > mtu) {
+      log_i("long write %d bytes", length);
+      os_mbuf *om = ble_hs_mbuf_from_flat(data, length);
+      rc = ble_gattc_write_long(pClient->getConnId(), m_handle, 0, om, BLERemoteCharacteristic::onWriteCB, &taskData);
+    } else {
+      rc = ble_gattc_write_flat(pClient->getConnId(), m_handle, data, length, BLERemoteCharacteristic::onWriteCB, &taskData);
+    }
+    if (rc != 0) {
+      goto exit;
+    }
+
+    BLEUtils::taskWait(taskData, BLE_NPL_TIME_FOREVER);
+    rc = taskData.m_flags;
+
+    switch (rc) {
+      case 0:
+      case BLE_HS_EDONE: rc = 0; break;
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_ATTR_NOT_LONG):
+        log_e("Long write not supported by peer; Truncating length to %d", mtu);
+        retryCount++;
+        length = mtu;
+        break;
+
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHEN):
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHOR):
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_ENC):
+        if (retryCount && pClient->secureConnection()) {
+          break;
+        }
+        /* Else falls through. */
+      default: goto exit;
+    }
+  } while (rc != 0 && retryCount--);
+
+exit:
+  if (rc != 0) {
+    log_e("<< writeValue failed rc=%d, %s", rc, BLEUtils::returnCodeToString(rc));
+  } else {
+    log_d("<< writeValue success. length: %d rc=%d", length, rc);
+  }
+
+  return (rc == 0);
+}  // writeValue
+
+/**
+ * @brief Subscribe or unsubscribe for notifications or indications.
+ * @param [in] val 0x00 to unsubscribe, 0x01 for notifications, 0x02 for indications.
+ * @param [in] notifyCallback A callback to be invoked for a notification.
+ * @param [in] response If write response required set this to true.
+ * If NULL is provided then no callback is performed.
+ * @return false if writing to the descriptor failed.
+ */
+bool BLERemoteCharacteristic::setNotify(uint16_t val, notify_callback notifyCallback, bool response) {
+  log_v(">> setNotify(): %s, %02x", toString().c_str(), val);
+
+  m_notifyCallback = notifyCallback;
+
+  BLERemoteDescriptor *desc = getDescriptor(BLEUUID((uint16_t)0x2902));
+  if (desc == nullptr) {
+    log_w("<< setNotify(): Callback set, CCCD not found");
+    return true;
+  }
+
+  log_d("<< setNotify()");
+
+  response = true;  // Always write with response as per Bluetooth core specification.
+  return desc->writeValue((uint8_t *)&val, 2, response);
+}  // setNotify
+
+/**
+ * @brief Subscribe for notifications or indications.
+ * @param [in] notifications If true, subscribe for notifications, false subscribe for indications.
+ * @param [in] notifyCallback A callback to be invoked for a notification.
+ * @param [in] response If true, require a write response from the descriptor write operation.
+ * If NULL is provided then no callback is performed.
+ * @return false if writing to the descriptor failed.
+ */
+bool BLERemoteCharacteristic::subscribe(bool notifications, notify_callback notifyCallback, bool response) {
+  if (notifications) {
+    return setNotify(0x01, notifyCallback, response);
+  } else {
+    return setNotify(0x02, notifyCallback, response);
+  }
+}  // subscribe
+
+/**
+ * @brief Unsubscribe for notifications or indications.
+ * @param [in] response bool if true, require a write response from the descriptor write operation.
+ * @return false if writing to the descriptor failed.
+ */
+bool BLERemoteCharacteristic::unsubscribe(bool response) {
+  return setNotify(0x00, nullptr, response);
+}  // unsubscribe
+
+#endif
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLERemoteCharacteristic.h b/libraries/BLE/src/BLERemoteCharacteristic.h
index dc63a3bc1a6..81ad7b2f4f5 100644
--- a/libraries/BLE/src/BLERemoteCharacteristic.h
+++ b/libraries/BLE/src/BLERemoteCharacteristic.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Jul 8, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLEREMOTECHARACTERISTIC_H_
@@ -11,27 +15,80 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
-#include <functional>
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
 
-#include <esp_gattc_api.h>
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
+#include <functional>
 #include "BLERemoteService.h"
 #include "BLERemoteDescriptor.h"
 #include "BLEUUID.h"
 #include "RTOS.h"
+#include "BLEUtils.h"
+
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gattc_api.h>
+#endif
+
+/***************************************************************************
+ *                     NimBLE includes and definitions                     *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_sm.h>
+#include <host/ble_gatt.h>
+#include <host/ble_att.h>
+
+#define ESP_GATT_MAX_ATTR_LEN            BLE_ATT_ATTR_MAX_LEN
+#define ESP_GATT_CHAR_PROP_BIT_READ      BLE_GATT_CHR_PROP_READ
+#define ESP_GATT_CHAR_PROP_BIT_WRITE     BLE_GATT_CHR_PROP_WRITE
+#define ESP_GATT_CHAR_PROP_BIT_WRITE_NR  BLE_GATT_CHR_PROP_WRITE_NO_RSP
+#define ESP_GATT_CHAR_PROP_BIT_BROADCAST BLE_GATT_CHR_PROP_BROADCAST
+#define ESP_GATT_CHAR_PROP_BIT_NOTIFY    BLE_GATT_CHR_PROP_NOTIFY
+#define ESP_GATT_CHAR_PROP_BIT_INDICATE  BLE_GATT_CHR_PROP_INDICATE
+
+#endif
+
+/***************************************************************************
+ *                             Common types                                *
+ ***************************************************************************/
+
+typedef std::function<void(BLERemoteCharacteristic *pBLERemoteCharacteristic, uint8_t *pData, size_t length, bool isNotify)> notify_callback;
+
+/***************************************************************************
+ *                             NimBLE types                                *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+typedef struct {
+  const BLEUUID *uuid;
+  void *task_data;
+} desc_filter_t;
+#endif
+
+/***************************************************************************
+ *                           Forward declarations                          *
+ ***************************************************************************/
 
 class BLERemoteService;
 class BLERemoteDescriptor;
-typedef std::function<void(BLERemoteCharacteristic *pBLERemoteCharacteristic, uint8_t *pData, size_t length, bool isNotify)> notify_callback;
+
 /**
  * @brief A model of a remote %BLE characteristic.
  */
 class BLERemoteCharacteristic {
 public:
-  ~BLERemoteCharacteristic();
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
 
-  // Public member functions
+  ~BLERemoteCharacteristic();
   bool canBroadcast();
   bool canIndicate();
   bool canNotify();
@@ -49,29 +106,34 @@ class BLERemoteCharacteristic {
   uint32_t readUInt32();
   float readFloat();
   void registerForNotify(notify_callback _callback, bool notifications = true, bool descriptorRequiresRegistration = true);
-  void writeValue(uint8_t *data, size_t length, bool response = false);
-  void writeValue(String newValue, bool response = false);
-  void writeValue(uint8_t newValue, bool response = false);
+  bool writeValue(uint8_t *data, size_t length, bool response = false);
+  bool writeValue(String newValue, bool response = false);
+  bool writeValue(uint8_t newValue, bool response = false);
   String toString();
   uint8_t *readRawData();
-  void setAuth(esp_gatt_auth_req_t auth);
+  void setAuth(uint8_t auth);
+
+  /***************************************************************************
+   *                       NimBLE public declarations                        *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  bool subscribe(bool notifications = true, notify_callback notifyCallback = nullptr, bool response = true);
+  bool unsubscribe(bool response = true);
+#endif
 
 private:
-  BLERemoteCharacteristic(uint16_t handle, BLEUUID uuid, esp_gatt_char_prop_t charProp, BLERemoteService *pRemoteService);
   friend class BLEClient;
   friend class BLERemoteService;
   friend class BLERemoteDescriptor;
 
-  // Private member functions
-  void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *evtParam);
-
-  void removeDescriptors();
-  void retrieveDescriptors();
+  /***************************************************************************
+   *                       Common private properties                        *
+   ***************************************************************************/
 
-  // Private properties
   BLEUUID m_uuid;
-  esp_gatt_char_prop_t m_charProp;
-  esp_gatt_auth_req_t m_auth;
+  uint8_t m_charProp;
+  uint8_t m_auth;
   uint16_t m_handle;
   BLERemoteService *m_pRemoteService;
   FreeRTOS::Semaphore m_semaphoreReadCharEvt = FreeRTOS::Semaphore("ReadCharEvt");
@@ -83,8 +145,46 @@ class BLERemoteCharacteristic {
 
   // We maintain a map of descriptors owned by this characteristic keyed by a string representation of the UUID.
   std::map<std::string, BLERemoteDescriptor *> m_descriptorMap;
+
+  /***************************************************************************
+   *                       NimBLE private properties                        *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  uint16_t m_defHandle;
+  uint16_t m_endHandle;
+#endif
+
+  /***************************************************************************
+   *                       Common private declarations                       *
+   ***************************************************************************/
+
+  void removeDescriptors();
+
+  /***************************************************************************
+   *                       Bluedroid private declarations                    *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  BLERemoteCharacteristic(uint16_t handle, BLEUUID uuid, uint8_t charProp, BLERemoteService *pRemoteService);
+  void retrieveDescriptors();
+  void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *evtParam);
+#endif
+
+  /***************************************************************************
+   *                       NimBLE private declarations                       *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  BLERemoteCharacteristic(BLERemoteService *pRemoteservice, const struct ble_gatt_chr *chr);
+  bool setNotify(uint16_t val, notify_callback notifyCallback = nullptr, bool response = true);
+  bool retrieveDescriptors(const BLEUUID *uuid_filter = nullptr);
+  static int onReadCB(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg);
+  static int onWriteCB(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg);
+  static int descriptorDiscCB(uint16_t conn_handle, const struct ble_gatt_error *error, uint16_t chr_val_handle, const struct ble_gatt_dsc *dsc, void *arg);
+#endif
 };  // BLERemoteCharacteristic
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLEREMOTECHARACTERISTIC_H_ */
diff --git a/libraries/BLE/src/BLERemoteDescriptor.cpp b/libraries/BLE/src/BLERemoteDescriptor.cpp
index b6d654cf9ec..a142fe11880 100644
--- a/libraries/BLE/src/BLERemoteDescriptor.cpp
+++ b/libraries/BLE/src/BLERemoteDescriptor.cpp
@@ -3,23 +3,48 @@
  *
  *  Created on: Jul 8, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
+
+#include "WString.h"
 #include <sstream>
 #include "BLERemoteDescriptor.h"
 #include "GeneralUtils.h"
 #include "esp32-hal-log.h"
 
-BLERemoteDescriptor::BLERemoteDescriptor(uint16_t handle, BLEUUID uuid, BLERemoteCharacteristic *pRemoteCharacteristic) {
+/***************************************************************************
+ *                           NimBLE includes                               *
+ ***************************************************************************/
 
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <freertos/task.h>
+#include <host/ble_gatt.h>
+#include <host/ble_att.h>
+#include <host/ble_hs.h>
+#endif
+
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
+
+BLERemoteDescriptor::BLERemoteDescriptor(uint16_t handle, BLEUUID uuid, BLERemoteCharacteristic *pRemoteCharacteristic) {
   m_handle = handle;
   m_uuid = uuid;
   m_pRemoteCharacteristic = pRemoteCharacteristic;
-  m_auth = ESP_GATT_AUTH_REQ_NONE;
+  m_auth = 0;
 }
 
 /**
@@ -46,6 +71,75 @@ BLEUUID BLERemoteDescriptor::getUUID() {
   return m_uuid;
 }  // getUUID
 
+uint8_t BLERemoteDescriptor::readUInt8() {
+  String value = readValue();
+  if (value.length() >= 1) {
+    return (uint8_t)value[0];
+  }
+  return 0;
+}  // readUInt8
+
+uint16_t BLERemoteDescriptor::readUInt16() {
+  String value = readValue();
+  if (value.length() >= 2) {
+    return *(uint16_t *)value.c_str();
+  }
+  return 0;
+}  // readUInt16
+
+uint32_t BLERemoteDescriptor::readUInt32() {
+  String value = readValue();
+  if (value.length() >= 4) {
+    return *(uint32_t *)value.c_str();
+  }
+  return 0;
+}  // readUInt32
+
+/**
+ * @brief Return a string representation of this BLE Remote Descriptor.
+ * @return A string representation of this BLE Remote Descriptor.
+ */
+String BLERemoteDescriptor::toString() {
+  char val[6];
+  snprintf(val, sizeof(val), "%d", getHandle());
+  String res = "handle: ";
+  res += val;
+  res += ", uuid: " + getUUID().toString();
+  return res;
+}  // toString
+
+/**
+ * @brief Write data represented as a string to the BLE Remote Descriptor.
+ * @param [in] newValue The data to send to the remote descriptor.
+ * @param [in] response True if we expect a response.
+ */
+bool BLERemoteDescriptor::writeValue(String newValue, bool response) {
+  return writeValue((uint8_t *)newValue.c_str(), newValue.length(), response);
+}  // writeValue
+
+/**
+ * @brief Write a byte value to the Descriptor.
+ * @param [in] The single byte to write.
+ * @param [in] True if we expect a response.
+ */
+bool BLERemoteDescriptor::writeValue(uint8_t newValue, bool response) {
+  return writeValue(&newValue, 1, response);
+}  // writeValue
+
+/**
+ * @brief Set authentication request type for characteristic
+ * @param [in] auth Authentication request type.
+ */
+void BLERemoteDescriptor::setAuth(uint8_t auth) {
+  m_auth = auth;
+}
+
+/***************************************************************************
+ *                           Bluedroid functions                           *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+
 void BLERemoteDescriptor::gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *evtParam) {
   switch (event) {
     // ESP_GATTC_READ_DESCR_EVT
@@ -99,7 +193,7 @@ String BLERemoteDescriptor::readValue() {
     m_pRemoteCharacteristic->getRemoteService()->getClient()->getGattcIf(),
     m_pRemoteCharacteristic->getRemoteService()->getClient()->getConnId(),  // The connection ID to the BLE server
     getHandle(),                                                            // The handle of this characteristic
-    m_auth
+    (esp_gatt_auth_req_t)m_auth
   );  // Security
 
   if (errRc != ESP_OK) {
@@ -115,55 +209,19 @@ String BLERemoteDescriptor::readValue() {
   return m_value;
 }  // readValue
 
-uint8_t BLERemoteDescriptor::readUInt8() {
-  String value = readValue();
-  if (value.length() >= 1) {
-    return (uint8_t)value[0];
-  }
-  return 0;
-}  // readUInt8
-
-uint16_t BLERemoteDescriptor::readUInt16() {
-  String value = readValue();
-  if (value.length() >= 2) {
-    return *(uint16_t *)value.c_str();
-  }
-  return 0;
-}  // readUInt16
-
-uint32_t BLERemoteDescriptor::readUInt32() {
-  String value = readValue();
-  if (value.length() >= 4) {
-    return *(uint32_t *)value.c_str();
-  }
-  return 0;
-}  // readUInt32
-
-/**
- * @brief Return a string representation of this BLE Remote Descriptor.
- * @return A string representation of this BLE Remote Descriptor.
- */
-String BLERemoteDescriptor::toString() {
-  char val[6];
-  snprintf(val, sizeof(val), "%d", getHandle());
-  String res = "handle: ";
-  res += val;
-  res += ", uuid: " + getUUID().toString();
-  return res;
-}  // toString
-
 /**
  * @brief Write data to the BLE Remote Descriptor.
  * @param [in] data The data to send to the remote descriptor.
  * @param [in] length The length of the data to send.
  * @param [in] response True if we expect a response.
+ * @return True if successful
  */
-void BLERemoteDescriptor::writeValue(uint8_t *data, size_t length, bool response) {
+bool BLERemoteDescriptor::writeValue(uint8_t *data, size_t length, bool response) {
   log_v(">> writeValue: %s", toString().c_str());
   // Check to see that we are connected.
   if (!getRemoteCharacteristic()->getRemoteService()->getClient()->isConnected()) {
     log_e("Disconnected");
-    return;
+    return false;
   }
 
   m_semaphoreWriteDescrEvt.take("writeValue");
@@ -172,7 +230,7 @@ void BLERemoteDescriptor::writeValue(uint8_t *data, size_t length, bool response
     m_pRemoteCharacteristic->getRemoteService()->getClient()->getGattcIf(), m_pRemoteCharacteristic->getRemoteService()->getClient()->getConnId(), getHandle(),
     length,  // Data length
     data,    // Data
-    response ? ESP_GATT_WRITE_TYPE_RSP : ESP_GATT_WRITE_TYPE_NO_RSP, m_auth
+    response ? ESP_GATT_WRITE_TYPE_RSP : ESP_GATT_WRITE_TYPE_NO_RSP, (esp_gatt_auth_req_t)m_auth
   );
   if (errRc != ESP_OK) {
     log_e("esp_ble_gattc_write_char_descr: %d", errRc);
@@ -180,33 +238,246 @@ void BLERemoteDescriptor::writeValue(uint8_t *data, size_t length, bool response
 
   m_semaphoreWriteDescrEvt.wait("writeValue");
   log_v("<< writeValue");
+  return (errRc == ESP_OK);
 }  // writeValue
 
+#endif
+
+/***************************************************************************
+ *                           NimBLE functions                             *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
 /**
- * @brief Write data represented as a string to the BLE Remote Descriptor.
- * @param [in] newValue The data to send to the remote descriptor.
- * @param [in] response True if we expect a response.
+ * @brief Remote descriptor constructor.
+ * @param [in] pRemoteCharacteristic A pointer to the Characteristic that this belongs to.
+ * @param [in] dsc A pointer to the struct that contains the descriptor information.
  */
-void BLERemoteDescriptor::writeValue(String newValue, bool response) {
-  writeValue((uint8_t *)newValue.c_str(), newValue.length(), response);
-}  // writeValue
+BLERemoteDescriptor::BLERemoteDescriptor(BLERemoteCharacteristic *pRemoteCharacteristic, const struct ble_gatt_dsc *dsc) {
+  log_d(">> BLERemoteDescriptor()");
+  switch (dsc->uuid.u.type) {
+    case BLE_UUID_TYPE_16:  m_uuid = BLEUUID(dsc->uuid.u16.value); break;
+    case BLE_UUID_TYPE_32:  m_uuid = BLEUUID(dsc->uuid.u32.value); break;
+    case BLE_UUID_TYPE_128: m_uuid = BLEUUID(const_cast<ble_uuid128_t *>(&dsc->uuid.u128)); break;
+    default:                break;
+  }
+
+  m_handle = dsc->handle;
+  m_pRemoteCharacteristic = pRemoteCharacteristic;
+  m_auth = 0;
+
+  log_d("<< BLERemoteDescriptor(): %s", m_uuid.toString().c_str());
+}
 
 /**
- * @brief Write a byte value to the Descriptor.
- * @param [in] The single byte to write.
- * @param [in] True if we expect a response.
+ * @brief Read the value of the remote descriptor.
+ * @return The value of the remote descriptor.
  */
-void BLERemoteDescriptor::writeValue(uint8_t newValue, bool response) {
-  writeValue(&newValue, 1, response);
-}  // writeValue
+String BLERemoteDescriptor::readValue() {
+  log_d(">> Descriptor readValue: %s", toString().c_str());
+
+  BLEClient *pClient = getRemoteCharacteristic()->getRemoteService()->getClient();
+  String value{};
+
+  if (!pClient->isConnected()) {
+    log_e("Disconnected");
+    return value;
+  }
+
+  int rc = 0;
+  int retryCount = 1;
+  BLETaskData taskData(const_cast<BLERemoteDescriptor *>(this), 0, &value);
+
+  do {
+    rc = ble_gattc_read_long(pClient->getConnId(), m_handle, 0, BLERemoteDescriptor::onReadCB, &taskData);
+    if (rc != 0) {
+      goto exit;
+    }
+
+    BLEUtils::taskWait(taskData, BLE_NPL_TIME_FOREVER);
+    rc = taskData.m_flags;
+
+    switch (rc) {
+      case 0:
+      case BLE_HS_EDONE: rc = 0; break;
+      // Descriptor is not long-readable, return with what we have.
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_ATTR_NOT_LONG):
+        log_i("Attribute not long");
+        rc = ble_gattc_read(pClient->getConnId(), m_handle, BLERemoteDescriptor::onReadCB, &taskData);
+        if (rc != 0) {
+          goto exit;
+        }
+        retryCount++;
+        break;
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHEN):
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHOR):
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_ENC):
+        if (retryCount && pClient->secureConnection()) {
+          break;
+        }
+      /* Else falls through. */
+      default: goto exit;
+    }
+  } while (rc != 0 && retryCount--);
+
+  m_semaphoreReadDescrEvt.take("readValue");
+  m_value = value;
+  m_semaphoreReadDescrEvt.give();
+
+exit:
+  if (rc != 0) {
+    log_e("<< readValue failed rc=%d, %s", rc, BLEUtils::returnCodeToString(rc));
+  } else {
+    log_d("<< Descriptor readValue(): length: %d rc=%d", value.length(), rc);
+  }
+
+  return value;
+}  // readValue
 
 /**
- * @brief Set authentication request type for characteristic
- * @param [in] auth Authentication request type.
+ * @brief Callback for Descriptor read operation.
+ * @return success == 0 or error code.
  */
-void BLERemoteDescriptor::setAuth(esp_gatt_auth_req_t auth) {
-  m_auth = auth;
+int BLERemoteDescriptor::onReadCB(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg) {
+  BLETaskData *pTaskData = static_cast<BLETaskData *>(arg);
+  BLERemoteDescriptor *desc = static_cast<BLERemoteDescriptor *>(pTaskData->m_pInstance);
+  uint16_t conn_id = desc->getRemoteCharacteristic()->getRemoteService()->getClient()->getConnId();
+
+  if (error->status == BLE_HS_ENOTCONN) {
+    log_e("<< Descriptor Read; Not connected");
+    BLEUtils::taskRelease(*pTaskData, error->status);
+    return error->status;
+  }
+
+  if (conn_id != conn_handle) {
+    return 0;
+  }
+
+  log_d("Read complete; status=%d conn_handle=%d", error->status, conn_handle);
+
+  String *strBuf = static_cast<String *>(pTaskData->m_pBuf);
+  int rc = error->status;
+
+  if (rc == 0) {
+    if (attr) {
+      uint32_t data_len = OS_MBUF_PKTLEN(attr->om);
+      if (((*strBuf).length() + data_len) > BLE_ATT_ATTR_MAX_LEN) {
+        rc = BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
+      } else {
+        log_d("Got %d bytes", data_len);
+        (*strBuf) += String((char *)attr->om->om_data, data_len);
+        return 0;
+      }
+    }
+  }
+
+  BLEUtils::taskRelease(*pTaskData, rc);
+  return rc;
+}
+
+/**
+ * @brief Callback for descriptor write operation.
+ * @return success == 0 or error code.
+ */
+int BLERemoteDescriptor::onWriteCB(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg) {
+  BLETaskData *pTaskData = static_cast<BLETaskData *>(arg);
+  BLERemoteDescriptor *descriptor = static_cast<BLERemoteDescriptor *>(pTaskData->m_pInstance);
+  int rc = error->status;
+
+  if (rc == BLE_HS_ENOTCONN) {
+    log_e("<< Descriptor Write; Not connected");
+    BLEUtils::taskRelease(*pTaskData, rc);
+    return rc;
+  }
+
+  if (descriptor->getRemoteCharacteristic()->getRemoteService()->getClient()->getConnId() != conn_handle) {
+    return 0;
+  }
+
+  log_i("Write complete; status=%d conn_handle=%d", rc, conn_handle);
+
+  BLEUtils::taskRelease(*pTaskData, rc);
+  return 0;
 }
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+/**
+ * @brief Write data to the BLE Remote Descriptor.
+ * @param [in] data The data to send to the remote descriptor.
+ * @param [in] length The length of the data to send.
+ * @param [in] response True if we expect a write response.
+ * @return True if successful
+ */
+bool BLERemoteDescriptor::writeValue(uint8_t *data, size_t length, bool response) {
+  log_d(">> Descriptor writeValue: %s", toString().c_str());
+
+  BLEClient *pClient = getRemoteCharacteristic()->getRemoteService()->getClient();
+
+  // Check to see that we are connected.
+  if (!pClient->isConnected()) {
+    log_e("Disconnected");
+    return false;
+  }
+
+  int rc = 0;
+  int retryCount = 1;
+  uint16_t mtu = ble_att_mtu(pClient->getConnId()) - 3;
+  BLETaskData taskData(const_cast<BLERemoteDescriptor *>(this));
+
+  // Check if the data length is longer than we can write in 1 connection event.
+  // If so we must do a long write which requires a response.
+  if (length <= mtu && !response) {
+    rc = ble_gattc_write_no_rsp_flat(pClient->getConnId(), m_handle, data, length);
+    goto exit;
+  }
+
+  do {
+    if (length > mtu) {
+      log_i("long write %d bytes", length);
+      os_mbuf *om = ble_hs_mbuf_from_flat(data, length);
+      rc = ble_gattc_write_long(pClient->getConnId(), m_handle, 0, om, BLERemoteDescriptor::onWriteCB, &taskData);
+    } else {
+      rc = ble_gattc_write_flat(pClient->getConnId(), m_handle, data, length, BLERemoteDescriptor::onWriteCB, &taskData);
+    }
+
+    if (rc != 0) {
+      goto exit;
+    }
+
+    BLEUtils::taskWait(taskData, BLE_NPL_TIME_FOREVER);
+    rc = taskData.m_flags;
+
+    switch (rc) {
+      case 0:
+      case BLE_HS_EDONE: rc = 0; break;
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_ATTR_NOT_LONG):
+        log_e("Long write not supported by peer; Truncating length to %d", mtu);
+        retryCount++;
+        length = mtu;
+        break;
+
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHEN):
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHOR):
+      case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_ENC):
+        if (retryCount && pClient->secureConnection()) {
+          break;
+        }
+      /* Else falls through. */
+      default: goto exit;
+    }
+  } while (rc != 0 && retryCount--);
+
+exit:
+  if (rc != 0) {
+    log_e("<< writeValue failed rc=%d, %s", rc, BLEUtils::returnCodeToString(rc));
+  } else {
+    log_d("<< writeValue success. length: %d rc=%d", length, rc);
+  }
+
+  return (rc == 0);
+}  // writeValue
+
+#endif
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLERemoteDescriptor.h b/libraries/BLE/src/BLERemoteDescriptor.h
index 94b11f1490a..afe113df551 100644
--- a/libraries/BLE/src/BLERemoteDescriptor.h
+++ b/libraries/BLE/src/BLERemoteDescriptor.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Jul 8, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLEREMOTEDESCRIPTOR_H_
@@ -11,21 +15,41 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
-#include <string>
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
 
-#include <esp_gattc_api.h>
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
+#include <string>
 #include "BLERemoteCharacteristic.h"
 #include "BLEUUID.h"
 #include "RTOS.h"
+#include "BLEUtils.h"
+
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gattc_api.h>
+#endif
+
+/***************************************************************************
+ *                           Forward declarations                          *
+ ***************************************************************************/
 
 class BLERemoteCharacteristic;
+
 /**
  * @brief A model of remote %BLE descriptor.
  */
 class BLERemoteDescriptor {
 public:
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   uint16_t getHandle();
   BLERemoteCharacteristic *getRemoteCharacteristic();
   BLEUUID getUUID();
@@ -34,24 +58,50 @@ class BLERemoteDescriptor {
   uint16_t readUInt16(void);
   uint32_t readUInt32(void);
   String toString(void);
-  void writeValue(uint8_t *data, size_t length, bool response = false);
-  void writeValue(String newValue, bool response = false);
-  void writeValue(uint8_t newValue, bool response = false);
-  void setAuth(esp_gatt_auth_req_t auth);
+  bool writeValue(uint8_t *data, size_t length, bool response = false);
+  bool writeValue(String newValue, bool response = false);
+  bool writeValue(uint8_t newValue, bool response = false);
+  void setAuth(uint8_t auth);
+
+  /***************************************************************************
+   *                       Bluedroid public declarations                     *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
   void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *evtParam);
+#endif
 
 private:
   friend class BLERemoteCharacteristic;
-  BLERemoteDescriptor(uint16_t handle, BLEUUID uuid, BLERemoteCharacteristic *pRemoteCharacteristic);
-  uint16_t m_handle;                                 // Server handle of this descriptor.
-  BLEUUID m_uuid;                                    // UUID of this descriptor.
-  String m_value;                                    // Last received value of the descriptor.
+
+  /***************************************************************************
+   *                        Common private properties                        *
+   ***************************************************************************/
+  uint16_t m_handle;  // Server handle of this descriptor.
+  BLEUUID m_uuid;     // UUID of this descriptor.
+  String m_value;     // Last received value of the descriptor.
+  uint8_t m_auth;
   BLERemoteCharacteristic *m_pRemoteCharacteristic;  // Reference to the Remote characteristic of which this descriptor is associated.
   FreeRTOS::Semaphore m_semaphoreReadDescrEvt = FreeRTOS::Semaphore("ReadDescrEvt");
   FreeRTOS::Semaphore m_semaphoreWriteDescrEvt = FreeRTOS::Semaphore("WriteDescrEvt");
-  esp_gatt_auth_req_t m_auth;
+
+  /***************************************************************************
+   *                       Common private declarations                       *
+   ***************************************************************************/
+
+  BLERemoteDescriptor(uint16_t handle, BLEUUID uuid, BLERemoteCharacteristic *pRemoteCharacteristic);
+
+  /***************************************************************************
+   *                       NimBLE private declarations                       *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  BLERemoteDescriptor(BLERemoteCharacteristic *pRemoteCharacteristic, const struct ble_gatt_dsc *dsc);
+  static int onWriteCB(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg);
+  static int onReadCB(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg);
+#endif
 };
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLEREMOTEDESCRIPTOR_H_ */
diff --git a/libraries/BLE/src/BLERemoteService.cpp b/libraries/BLE/src/BLERemoteService.cpp
index e4cc31dbb33..7baf6908d40 100644
--- a/libraries/BLE/src/BLERemoteService.cpp
+++ b/libraries/BLE/src/BLERemoteService.cpp
@@ -3,12 +3,21 @@
  *
  *  Created on: Jul 8, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
 #include <sstream>
 #include "BLERemoteService.h"
@@ -17,97 +26,14 @@
 #include <esp_err.h>
 #include "esp32-hal-log.h"
 
-#pragma GCC diagnostic warning "-Wunused-but-set-parameter"
-
-BLERemoteService::BLERemoteService(esp_gatt_id_t srvcId, BLEClient *pClient, uint16_t startHandle, uint16_t endHandle) {
-
-  log_v(">> BLERemoteService()");
-  m_srvcId = srvcId;
-  m_pClient = pClient;
-  m_uuid = BLEUUID(m_srvcId);
-  m_haveCharacteristics = false;
-  m_startHandle = startHandle;
-  m_endHandle = endHandle;
-
-  log_v("<< BLERemoteService()");
-}
+/***************************************************************************
+ *                           Common functions                             *
+ ***************************************************************************/
 
 BLERemoteService::~BLERemoteService() {
   removeCharacteristics();
 }
 
-/*
-static bool compareSrvcId(esp_gatt_srvc_id_t id1, esp_gatt_srvc_id_t id2) {
-  if (id1.id.inst_id != id2.id.inst_id) {
-    return false;
-  }
-  if (!BLEUUID(id1.id.uuid).equals(BLEUUID(id2.id.uuid))) {
-    return false;
-  }
-  return true;
-} // compareSrvcId
-*/
-
-/**
- * @brief Handle GATT Client events
- */
-void BLERemoteService::gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *evtParam) {
-  switch (event) {
-      //
-      // ESP_GATTC_GET_CHAR_EVT
-      //
-      // get_char:
-      // - esp_gatt_status_t    status
-      // - uin1t6_t             conn_id
-      // - esp_gatt_srvc_id_t   srvc_id
-      // - esp_gatt_id_t        char_id
-      // - esp_gatt_char_prop_t char_prop
-      //
-      /*
-    case ESP_GATTC_GET_CHAR_EVT: {
-      // Is this event for this service?  If yes, then the local srvc_id and the event srvc_id will be
-      // the same.
-      if (compareSrvcId(m_srvcId, evtParam->get_char.srvc_id) == false) {
-        break;
-      }
-
-      // If the status is NOT OK then we have a problem and continue.
-      if (evtParam->get_char.status != ESP_GATT_OK) {
-        m_semaphoreGetCharEvt.give();
-        break;
-      }
-
-      // This is an indication that we now have the characteristic details for a characteristic owned
-      // by this service so remember it.
-      m_characteristicMap.insert(std::pair<std::string, BLERemoteCharacteristic*>(
-          BLEUUID(evtParam->get_char.char_id.uuid).toString().c_str(),
-          new BLERemoteCharacteristic(evtParam->get_char.char_id, evtParam->get_char.char_prop, this)  ));
-
-
-      // Now that we have received a characteristic, lets ask for the next one.
-      esp_err_t errRc = ::esp_ble_gattc_get_characteristic(
-          m_pClient->getGattcIf(),
-          m_pClient->getConnId(),
-          &m_srvcId,
-          &evtParam->get_char.char_id);
-      if (errRc != ESP_OK) {
-        log_e("esp_ble_gattc_get_characteristic: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-        break;
-      }
-
-      //m_semaphoreGetCharEvt.give();
-      break;
-    } // ESP_GATTC_GET_CHAR_EVT
-*/
-    default: break;
-  }  // switch
-
-  // Send the event to each of the characteristics owned by this service.
-  for (auto &myPair : m_characteristicMapByHandle) {
-    myPair.second->gattClientEventHandler(event, gattc_if, evtParam);
-  }
-}  // gattClientEventHandler
-
 /**
  * @brief Get the remote characteristic object for the characteristic UUID.
  * @param [in] uuid Remote characteristic uuid.
@@ -144,52 +70,6 @@ BLERemoteCharacteristic *BLERemoteService::getCharacteristic(BLEUUID uuid) {
   return nullptr;
 }  // getCharacteristic
 
-/**
- * @brief Retrieve all the characteristics for this service.
- * This function will not return until we have all the characteristics.
- * @return N/A
- */
-void BLERemoteService::retrieveCharacteristics() {
-  log_v(">> getCharacteristics() for service: %s", getUUID().toString().c_str());
-
-  removeCharacteristics();  // Forget any previous characteristics.
-
-  uint16_t offset = 0;
-  esp_gattc_char_elem_t result;
-  while (true) {
-    uint16_t count = 1;  // only room for 1 result allocated, so go one by one
-    esp_gatt_status_t status =
-      ::esp_ble_gattc_get_all_char(getClient()->getGattcIf(), getClient()->getConnId(), m_startHandle, m_endHandle, &result, &count, offset);
-
-    if (status == ESP_GATT_INVALID_OFFSET) {  // We have reached the end of the entries.
-      break;
-    }
-
-    if (status != ESP_GATT_OK) {  // If we got an error, end.
-      log_e("esp_ble_gattc_get_all_char: %s", BLEUtils::gattStatusToString(status).c_str());
-      break;
-    }
-
-    if (count == 0) {  // If we failed to get any new records, end.
-      break;
-    }
-
-    log_d("Found a characteristic: Handle: %d, UUID: %s", result.char_handle, BLEUUID(result.uuid).toString().c_str());
-
-    // We now have a new characteristic ... let us add that to our set of known characteristics
-    BLERemoteCharacteristic *pNewRemoteCharacteristic = new BLERemoteCharacteristic(result.char_handle, BLEUUID(result.uuid), result.properties, this);
-
-    m_characteristicMap.insert(
-      std::pair<std::string, BLERemoteCharacteristic *>(pNewRemoteCharacteristic->getUUID().toString().c_str(), pNewRemoteCharacteristic)
-    );
-    m_characteristicMapByHandle.insert(std::pair<uint16_t, BLERemoteCharacteristic *>(result.char_handle, pNewRemoteCharacteristic));
-    offset++;  // Increment our count of number of descriptors found.
-  }  // Loop forever (until we break inside the loop).
-
-  m_haveCharacteristics = true;  // Remember that we have received the characteristics.
-  log_v("<< getCharacteristics()");
-}  // getCharacteristics
-
 /**
  * @brief Retrieve a map of all the characteristics of this service.
  * @return A map of all the characteristics of this service.
@@ -248,10 +128,6 @@ uint16_t BLERemoteService::getEndHandle() {
   return m_endHandle;
 }  // getEndHandle
 
-esp_gatt_id_t *BLERemoteService::getSrvcId() {
-  return &m_srvcId;
-}  // getSrvcId
-
 uint16_t BLERemoteService::getStartHandle() {
   return m_startHandle;
 }  // getStartHandle
@@ -330,5 +206,222 @@ String BLERemoteService::toString() {
   return res;
 }  // toString
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+/***************************************************************************
+ *                           Bluedroid functions                           *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+
+BLERemoteService::BLERemoteService(esp_gatt_id_t srvcId, BLEClient *pClient, uint16_t startHandle, uint16_t endHandle) {
+  log_v(">> BLERemoteService()");
+  m_srvcId = srvcId;
+  m_pClient = pClient;
+  m_uuid = BLEUUID(m_srvcId);
+  m_haveCharacteristics = false;
+  m_startHandle = startHandle;
+  m_endHandle = endHandle;
+
+  log_v("<< BLERemoteService()");
+}
+
+esp_gatt_id_t *BLERemoteService::getSrvcId() {
+  return &m_srvcId;
+}  // getSrvcId
+
+/**
+ * @brief Retrieve all the characteristics for this service.
+ * This function will not return until we have all the characteristics.
+ * @return N/A
+ */
+void BLERemoteService::retrieveCharacteristics() {
+  log_v(">> getCharacteristics() for service: %s", getUUID().toString().c_str());
+
+  removeCharacteristics();  // Forget any previous characteristics.
+
+  uint16_t offset = 0;
+  esp_gattc_char_elem_t result;
+  while (true) {
+    uint16_t count = 1;  // only room for 1 result allocated, so go one by one
+    esp_gatt_status_t status =
+      ::esp_ble_gattc_get_all_char(getClient()->getGattcIf(), getClient()->getConnId(), m_startHandle, m_endHandle, &result, &count, offset);
+
+    if (status == ESP_GATT_INVALID_OFFSET) {  // We have reached the end of the entries.
+      break;
+    }
+
+    if (status != ESP_GATT_OK) {  // If we got an error, end.
+      log_e("esp_ble_gattc_get_all_char: %s", BLEUtils::gattStatusToString(status).c_str());
+      break;
+    }
+
+    if (count == 0) {  // If we failed to get any new records, end.
+      break;
+    }
+
+    log_d("Found a characteristic: Handle: %d, UUID: %s", result.char_handle, BLEUUID(result.uuid).toString().c_str());
+
+    // We now have a new characteristic ... let us add that to our set of known characteristics
+    BLERemoteCharacteristic *pNewRemoteCharacteristic = new BLERemoteCharacteristic(result.char_handle, BLEUUID(result.uuid), result.properties, this);
+
+    m_characteristicMap.insert(
+      std::pair<std::string, BLERemoteCharacteristic *>(pNewRemoteCharacteristic->getUUID().toString().c_str(), pNewRemoteCharacteristic)
+    );
+    m_characteristicMapByHandle.insert(std::pair<uint16_t, BLERemoteCharacteristic *>(result.char_handle, pNewRemoteCharacteristic));
+    offset++;  // Increment our count of number of descriptors found.
+  }  // Loop forever (until we break inside the loop).
+
+  m_haveCharacteristics = true;  // Remember that we have received the characteristics.
+  log_v("<< getCharacteristics()");
+}  // getCharacteristics
+
+/**
+ * @brief Handle GATT Client events
+ */
+void BLERemoteService::gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *evtParam) {
+  switch (event) {
+      //
+      // ESP_GATTC_GET_CHAR_EVT
+      //
+      // get_char:
+      // - esp_gatt_status_t    status
+      // - uin1t6_t             conn_id
+      // - esp_gatt_srvc_id_t   srvc_id
+      // - esp_gatt_id_t        char_id
+      // - esp_gatt_char_prop_t char_prop
+      //
+      /*
+    case ESP_GATTC_GET_CHAR_EVT: {
+      // Is this event for this service?  If yes, then the local srvc_id and the event srvc_id will be
+      // the same.
+      if (compareSrvcId(m_srvcId, evtParam->get_char.srvc_id) == false) {
+        break;
+      }
+
+      // If the status is NOT OK then we have a problem and continue.
+      if (evtParam->get_char.status != ESP_GATT_OK) {
+        m_semaphoreGetCharEvt.give();
+        break;
+      }
+
+      // This is an indication that we now have the characteristic details for a characteristic owned
+      // by this service so remember it.
+      m_characteristicMap.insert(std::pair<std::string, BLERemoteCharacteristic*>(
+          BLEUUID(evtParam->get_char.char_id.uuid).toString().c_str(),
+          new BLERemoteCharacteristic(evtParam->get_char.char_id, evtParam->get_char.char_prop, this)  ));
+
+
+      // Now that we have received a characteristic, lets ask for the next one.
+      esp_err_t errRc = ::esp_ble_gattc_get_characteristic(
+          m_pClient->getGattcIf(),
+          m_pClient->getConnId(),
+          &m_srvcId,
+          &evtParam->get_char.char_id);
+      if (errRc != ESP_OK) {
+        log_e("esp_ble_gattc_get_characteristic: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+        break;
+      }
+
+      //m_semaphoreGetCharEvt.give();
+      break;
+    } // ESP_GATTC_GET_CHAR_EVT
+*/
+    default: break;
+  }  // switch
+
+  // Send the event to each of the characteristics owned by this service.
+  for (auto &myPair : m_characteristicMapByHandle) {
+    myPair.second->gattClientEventHandler(event, gattc_if, evtParam);
+  }
+}  // gattClientEventHandler
+
+#endif
+
+/***************************************************************************
+ *                           NimBLE functions                             *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
+BLERemoteService::BLERemoteService(BLEClient *pClient, const struct ble_gatt_svc *service) {
+  log_v(">> BLERemoteService()");
+  m_pClient = pClient;
+  switch (service->uuid.u.type) {
+    case BLE_UUID_TYPE_16:  m_uuid = BLEUUID(service->uuid.u16.value); break;
+    case BLE_UUID_TYPE_32:  m_uuid = BLEUUID(service->uuid.u32.value); break;
+    case BLE_UUID_TYPE_128: m_uuid = BLEUUID(const_cast<ble_uuid128_t *>(&service->uuid.u128)); break;
+    default:                break;
+  }
+  m_startHandle = service->start_handle;
+  m_endHandle = service->end_handle;
+  m_haveCharacteristics = false;
+  log_v("<< BLERemoteService(): %s", m_uuid.toString().c_str());
+}
+
+/**
+ * @brief Retrieve all the characteristics for this service.
+ * This function will not return until we have all the characteristics.
+ */
+void BLERemoteService::retrieveCharacteristics() {
+  log_v(">> retrieveCharacteristics() for service: %s", getUUID().toString().c_str());
+
+  int rc = 0;
+  BLETaskData taskData(const_cast<BLERemoteService *>(this));
+
+  rc = ble_gattc_disc_all_chrs(m_pClient->getConnId(), m_startHandle, m_endHandle, BLERemoteService::characteristicDiscCB, &taskData);
+
+  if (rc != 0) {
+    log_e("ble_gattc_disc_all_chrs: rc=%d %s", rc, BLEUtils::returnCodeToString(rc));
+    return;
+  }
+
+  BLEUtils::taskWait(taskData, BLE_NPL_TIME_FOREVER);
+  rc = taskData.m_flags;
+  if (rc == 0 || rc == BLE_HS_EDONE) {
+    log_d("<< retrieveCharacteristics()");
+    return;
+  }
+
+  log_e("<< retrieveCharacteristics() rc=%d %s", rc, BLEUtils::returnCodeToString(rc));
+}  // retrieveCharacteristics
+
+/**
+ * @brief Callback for characteristic discovery.
+ * @return success == 0 or error code.
+ */
+int BLERemoteService::characteristicDiscCB(uint16_t conn_handle, const struct ble_gatt_error *error, const struct ble_gatt_chr *chr, void *arg) {
+  log_d("Characteristic Discovered >> status: %d handle: %d", error->status, (error->status == 0) ? chr->val_handle : -1);
+
+  BLETaskData *pTaskData = (BLETaskData *)arg;
+  BLERemoteService *service = (BLERemoteService *)pTaskData->m_pInstance;
+
+  if (error->status == BLE_HS_ENOTCONN) {
+    log_e("<< Characteristic Discovery; Not connected");
+    BLEUtils::taskRelease(*pTaskData, error->status);
+    return error->status;
+  }
+
+  // Make sure the discovery is for this device
+  if (service->getClient()->getConnId() != conn_handle) {
+    return 0;
+  }
+
+  if (error->status == 0) {
+    // Found a service - add it to the vector
+    BLERemoteCharacteristic *pRemoteCharacteristic = new BLERemoteCharacteristic(service, chr);
+    service->m_characteristicMap.insert(
+      std::pair<std::string, BLERemoteCharacteristic *>(pRemoteCharacteristic->getUUID().toString().c_str(), pRemoteCharacteristic)
+    );
+    service->m_characteristicMapByHandle.insert(std::pair<uint16_t, BLERemoteCharacteristic *>(chr->val_handle, pRemoteCharacteristic));
+    return 0;
+  }
+
+  BLEUtils::taskRelease(*pTaskData, error->status);
+  service->m_haveCharacteristics = true;
+  log_d("<< Characteristic Discovered");
+  return error->status;
+}
+
+#endif
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLERemoteService.h b/libraries/BLE/src/BLERemoteService.h
index 49845a0a1e8..c93d91f6852 100644
--- a/libraries/BLE/src/BLERemoteService.h
+++ b/libraries/BLE/src/BLERemoteService.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Jul 8, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLEREMOTESERVICE_H_
@@ -11,7 +15,11 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
 #include <map>
 
@@ -19,6 +27,19 @@
 #include "BLERemoteCharacteristic.h"
 #include "BLEUUID.h"
 #include "RTOS.h"
+#include "BLEUtils.h"
+
+/***************************************************************************
+ *                           NimBLE includes                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_gatt.h>
+#endif
+
+/***************************************************************************
+ *                         Forward declarations                            *
+ ***************************************************************************/
 
 class BLEClient;
 class BLERemoteCharacteristic;
@@ -28,15 +49,18 @@ class BLERemoteCharacteristic;
  */
 class BLERemoteService {
 public:
-  virtual ~BLERemoteService();
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
 
-  // Public methods
+  virtual ~BLERemoteService();
   BLERemoteCharacteristic *getCharacteristic(const char *uuid);  // Get the specified characteristic reference.
   BLERemoteCharacteristic *getCharacteristic(BLEUUID uuid);      // Get the specified characteristic reference.
   BLERemoteCharacteristic *getCharacteristic(uint16_t uuid);     // Get the specified characteristic reference.
   std::map<std::string, BLERemoteCharacteristic *> *getCharacteristics();
   std::map<uint16_t, BLERemoteCharacteristic *> *getCharacteristicsByHandle();  // Get the characteristics map.
   void getCharacteristics(std::map<uint16_t, BLERemoteCharacteristic *> **pCharacteristicMap);
+  void retrieveCharacteristics();
 
   BLEClient *getClient(void);                               // Get a reference to the client associated with this service.
   uint16_t getHandle();                                     // Get the handle of this service.
@@ -46,24 +70,12 @@ class BLERemoteService {
   String toString(void);
 
 private:
-  // Private constructor ... never meant to be created by a user application.
-  BLERemoteService(esp_gatt_id_t srvcId, BLEClient *pClient, uint16_t startHandle, uint16_t endHandle);
-
-  // Friends
   friend class BLEClient;
   friend class BLERemoteCharacteristic;
 
-  // Private methods
-  void retrieveCharacteristics(void);  // Retrieve the characteristics from the BLE Server.
-  esp_gatt_id_t *getSrvcId(void);
-  uint16_t getStartHandle();  // Get the start handle for this service.
-  uint16_t getEndHandle();    // Get the end handle for this service.
-
-  void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *evtParam);
-
-  void removeCharacteristics();
-
-  // Properties
+  /***************************************************************************
+   *                       Common private properties                         *
+   ***************************************************************************/
 
   // We maintain a map of characteristics owned by this service keyed by a string representation of the UUID.
   std::map<std::string, BLERemoteCharacteristic *> m_characteristicMap;
@@ -74,12 +86,47 @@ class BLERemoteService {
   bool m_haveCharacteristics;  // Have we previously obtained the characteristics.
   BLEClient *m_pClient;
   FreeRTOS::Semaphore m_semaphoreGetCharEvt = FreeRTOS::Semaphore("GetCharEvt");
-  esp_gatt_id_t m_srvcId;
   BLEUUID m_uuid;          // The UUID of this service.
   uint16_t m_startHandle;  // The starting handle of this service.
   uint16_t m_endHandle;    // The ending handle of this service.
+
+  /***************************************************************************
+   *                       Bluedroid private properties                      *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  esp_gatt_id_t m_srvcId;
+#endif
+
+  /***************************************************************************
+   *                       Common private declarations                       *
+   ***************************************************************************/
+
+  uint16_t getStartHandle();  // Get the start handle for this service.
+  uint16_t getEndHandle();    // Get the end handle for this service.
+  void removeCharacteristics();
+
+  /***************************************************************************
+   *                       Bluedroid private declarations                    *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  // Private constructor ... never meant to be created by a user application.
+  BLERemoteService(esp_gatt_id_t srvcId, BLEClient *pClient, uint16_t startHandle, uint16_t endHandle);
+  esp_gatt_id_t *getSrvcId();
+  void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *evtParam);
+#endif
+
+  /***************************************************************************
+   *                       NimBLE private declarations                       *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  BLERemoteService(BLEClient *pClient, const struct ble_gatt_svc *service);
+  static int characteristicDiscCB(uint16_t conn_handle, const struct ble_gatt_error *error, const struct ble_gatt_chr *chr, void *arg);
+#endif
 };  // BLERemoteService
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLEREMOTESERVICE_H_ */
diff --git a/libraries/BLE/src/BLEScan.cpp b/libraries/BLE/src/BLEScan.cpp
index 0a99b46c61d..6d18bb2d751 100644
--- a/libraries/BLE/src/BLEScan.cpp
+++ b/libraries/BLE/src/BLEScan.cpp
@@ -6,12 +6,21 @@
  *
  * 	Update: April, 2021
  * 		add BLE5 support
+ *
+ * 	Modified on: Feb 18, 2025
+ * 		Author: lucasssvaz (based on kolban's and h2zero's work)
+ * 		Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                           Common includes                               *
+ ***************************************************************************/
 
 #include <esp_err.h>
 
@@ -23,12 +32,17 @@
 #include "GeneralUtils.h"
 #include "esp32-hal-log.h"
 
+/***************************************************************************
+ *                           Common functions                              *
+ ***************************************************************************/
+
 /**
- * Constructor
+ * @brief Constructor
  */
 BLEScan::BLEScan() {
   memset(&m_scan_params, 0, sizeof(m_scan_params));  // Initialize all params
-  m_scan_params.scan_type = BLE_SCAN_TYPE_PASSIVE;   // Default is a passive scan.
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  m_scan_params.scan_type = BLE_SCAN_TYPE_PASSIVE;  // Default is a passive scan.
   m_scan_params.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
   m_scan_params.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
   m_scan_params.scan_duplicate = BLE_SCAN_DUPLICATE_DISABLE;
@@ -38,15 +52,246 @@ BLEScan::BLEScan() {
   m_shouldParse = true;
   setInterval(100);
   setWindow(100);
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  m_scan_params.filter_policy = BLE_HCI_SCAN_FILT_NO_WL;
+  m_scan_params.passive = 1;            // If set, don’t send scan requests to advertisers (i.e., don’t request additional advertising data).
+  m_scan_params.limited = 0;            // If set, only discover devices in limited discoverable mode.
+  m_scan_params.filter_duplicates = 1;  // If set, the controller ignores all but the first advertisement from each device.
+  m_pAdvertisedDeviceCallbacks = nullptr;
+  m_ignoreResults = false;
+  m_pTaskData = nullptr;
+  m_duration = BLE_HS_FOREVER;  // make sure this is non-zero in the event of a host reset
+  m_maxResults = 0xFF;
+  m_stopped = true;
+  m_wantDuplicates = false;
+  m_shouldParse = true;
+  // This is defined as the time interval from when the Controller started its last LE scan until it begins the subsequent LE scan. (units=0.625 msec)
+  setInterval(100);
+  // The duration of the LE scan. LE_Scan_Window shall be less than or equal to LE_Scan_Interval (units=0.625 msec)
+  setWindow(100);
+#endif
 }  // BLEScan
 
+/**
+ * @brief Scan destructor, release any allocated resources.
+ */
+BLEScan::~BLEScan() {
+  clearResults();
+}
+
+/**
+ * @brief Should we perform an active or passive scan?
+ * The default is a passive scan.  An active scan means that we will wish a scan response.
+ * @param [in] active If true, we perform an active scan otherwise a passive scan.
+ * @return N/A.
+ */
+void BLEScan::setActiveScan(bool active) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  if (active) {
+    m_scan_params.scan_type = BLE_SCAN_TYPE_ACTIVE;
+  } else {
+    m_scan_params.scan_type = BLE_SCAN_TYPE_PASSIVE;
+  }
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  m_scan_params.passive = !active;
+#endif
+}  // setActiveScan
+
+/**
+ * @brief Set the call backs to be invoked.
+ * @param [in] pAdvertisedDeviceCallbacks Call backs to be invoked.
+ * @param [in] wantDuplicates  True if we wish to be called back with duplicates.  Default is false.
+ * @param [in] shouldParse  True if we wish to parse advertised package or raw payload.  Default is true.
+ */
+void BLEScan::setAdvertisedDeviceCallbacks(BLEAdvertisedDeviceCallbacks *pAdvertisedDeviceCallbacks, bool wantDuplicates, bool shouldParse) {
+  m_wantDuplicates = wantDuplicates;
+#if defined(CONFIG_NIMBLE_ENABLED)
+  setDuplicateFilter(!wantDuplicates);
+#endif
+  m_pAdvertisedDeviceCallbacks = pAdvertisedDeviceCallbacks;
+  m_shouldParse = shouldParse;
+}  // setAdvertisedDeviceCallbacks
+
+/**
+ * @brief Set the interval to scan.
+ * @param [in] The interval in msecs.
+ */
+void BLEScan::setInterval(uint16_t intervalMSecs) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  m_scan_params.scan_interval = intervalMSecs / 0.625;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  m_scan_params.itvl = intervalMSecs / 0.625;
+#endif
+}  // setInterval
+
+/**
+ * @brief Set the window to actively scan.
+ * @param [in] windowMSecs How long to actively scan.
+ */
+void BLEScan::setWindow(uint16_t windowMSecs) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  m_scan_params.scan_window = windowMSecs / 0.625;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  m_scan_params.window = windowMSecs / 0.625;
+#endif
+}  // setWindow
+
+// delete peer device from cache after disconnecting, it is required in case we are connecting to devices with not public address
+void BLEScan::erase(BLEAddress address) {
+  log_i("erase device: %s", address.toString().c_str());
+  BLEAdvertisedDevice *advertisedDevice = m_scanResults.m_vectorAdvertisedDevices.find(address.toString().c_str())->second;
+  m_scanResults.m_vectorAdvertisedDevices.erase(address.toString().c_str());
+  delete advertisedDevice;
+}
+
+/**
+ * @brief Dump the scan results to the log.
+ */
+void BLEScanResults::dump() {
+  log_v(">> Dump scan results:");
+  for (int i = 0; i < getCount(); i++) {
+    log_d("- %s", getDevice(i).toString().c_str());
+  }
+}  // dump
+
+/**
+ * @brief Return the count of devices found in the last scan.
+ * @return The number of devices found in the last scan.
+ */
+int BLEScanResults::getCount() {
+  return m_vectorAdvertisedDevices.size();
+}  // getCount
+
+/**
+ * @brief Return the specified device at the given index.
+ * The index should be between 0 and getCount()-1.
+ * @param [in] i The index of the device.
+ * @return The device at the specified index.
+ */
+BLEAdvertisedDevice BLEScanResults::getDevice(uint32_t i) {
+  uint32_t x = 0;
+  BLEAdvertisedDevice dev = *m_vectorAdvertisedDevices.begin()->second;
+  for (auto it = m_vectorAdvertisedDevices.begin(); it != m_vectorAdvertisedDevices.end(); it++) {
+    dev = *it->second;
+    if (x == i) {
+      break;
+    }
+    x++;
+  }
+  return dev;
+}
+
+BLEScanResults *BLEScan::getResults() {
+  return &m_scanResults;
+}
+
+void BLEScan::clearResults() {
+  for (auto _dev : m_scanResults.m_vectorAdvertisedDevices) {
+    delete _dev.second;
+  }
+  m_scanResults.m_vectorAdvertisedDevices.clear();
+}
+
+/***************************************************************************
+ *                         Bluedroid functions                             *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+
+#if defined(SOC_BLE_50_SUPPORTED)
+
+void BLEScan::setExtendedScanCallback(BLEExtAdvertisingCallbacks *cb) {
+  m_pExtendedScanCb = cb;
+}
+
+/**
+* @brief           This function is used to enable scanning.
+*
+* @param[in]       duration : Scan duration
+* @param[in]       period  : Time interval from when the Controller started its last Scan Duration until it begins the subsequent Scan Duration.
+*
+* @return            - ESP_OK : success
+*                    - other  : failed
+*
+*/
+esp_err_t BLEScan::startExtScan(uint32_t duration, uint16_t period) {
+  esp_err_t rc = esp_ble_gap_start_ext_scan(duration, period);
+  if (rc) {
+    log_e("extended scan start failed: %d", rc);
+  }
+  return rc;
+}
+
+esp_err_t BLEScan::stopExtScan() {
+  esp_err_t rc = esp_ble_gap_stop_ext_scan();
+  if (rc) {
+    log_e("extended scan stop failed: %d", rc);
+  }
+  return rc;
+}
+
+void BLEScan::setPeriodicScanCallback(BLEPeriodicScanCallbacks *cb) {
+  m_pPeriodicScanCb = cb;
+}
+
+/**
+* @brief           This function is used to set the extended scan parameters to be used on the advertising channels.
+*
+*
+* @return            - ESP_OK : success
+*                    - other  : failed
+*
+*/
+esp_err_t BLEScan::setExtScanParams() {
+  esp_ble_ext_scan_params_t ext_scan_params = {
+    .own_addr_type = BLE_ADDR_TYPE_PUBLIC,
+    .filter_policy = BLE_SCAN_FILTER_ALLOW_ALL,
+    .scan_duplicate = BLE_SCAN_DUPLICATE_DISABLE,
+    .cfg_mask = ESP_BLE_GAP_EXT_SCAN_CFG_UNCODE_MASK | ESP_BLE_GAP_EXT_SCAN_CFG_CODE_MASK,
+    .uncoded_cfg = {BLE_SCAN_TYPE_ACTIVE, 40, 40},
+    .coded_cfg = {BLE_SCAN_TYPE_ACTIVE, 40, 40},
+  };
+
+  esp_err_t rc = esp_ble_gap_set_ext_scan_params(&ext_scan_params);
+  if (rc) {
+    log_e("set extend scan params error, error code = %x", rc);
+  }
+  return rc;
+}
+
+/**
+* @brief           This function is used to set the extended scan parameters to be used on the advertising channels.
+*
+* @param[in]       params : scan parameters
+*
+* @return            - ESP_OK : success
+*                    - other  : failed
+*
+*/
+esp_err_t BLEScan::setExtScanParams(esp_ble_ext_scan_params_t *ext_scan_params) {
+  esp_err_t rc = esp_ble_gap_set_ext_scan_params(ext_scan_params);
+  if (rc) {
+    log_e("set extend scan params error, error code = %x", rc);
+  }
+  return rc;
+}
+
+#endif  // SOC_BLE_50_SUPPORTED
+
 /**
  * @brief Handle GAP events related to scans.
  * @param [in] event The event type for this event.
  * @param [in] param Parameter data for this event.
  */
 void BLEScan::handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
-
   switch (event) {
 
     // ---------------------------
@@ -118,6 +363,7 @@ void BLEScan::handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_
           advertisedDevice->setAddress(advertisedAddress);
           advertisedDevice->setRSSI(param->scan_rst.rssi);
           advertisedDevice->setAdFlag(param->scan_rst.flag);
+          advertisedDevice->setAdvType(param->scan_rst.ble_evt_type);
           if (m_shouldParse) {
             advertisedDevice->parseAdvertisement((uint8_t *)param->scan_rst.ble_adv, param->scan_rst.adv_data_len + param->scan_rst.scan_rsp_len);
           } else {
@@ -245,126 +491,6 @@ void BLEScan::handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_
   }  // End switch
 }  // gapEventHandler
 
-/**
- * @brief Should we perform an active or passive scan?
- * The default is a passive scan.  An active scan means that we will wish a scan response.
- * @param [in] active If true, we perform an active scan otherwise a passive scan.
- * @return N/A.
- */
-void BLEScan::setActiveScan(bool active) {
-  if (active) {
-    m_scan_params.scan_type = BLE_SCAN_TYPE_ACTIVE;
-  } else {
-    m_scan_params.scan_type = BLE_SCAN_TYPE_PASSIVE;
-  }
-}  // setActiveScan
-
-/**
- * @brief Set the call backs to be invoked.
- * @param [in] pAdvertisedDeviceCallbacks Call backs to be invoked.
- * @param [in] wantDuplicates  True if we wish to be called back with duplicates.  Default is false.
- * @param [in] shouldParse  True if we wish to parse advertised package or raw payload.  Default is true.
- */
-void BLEScan::setAdvertisedDeviceCallbacks(BLEAdvertisedDeviceCallbacks *pAdvertisedDeviceCallbacks, bool wantDuplicates, bool shouldParse) {
-  m_wantDuplicates = wantDuplicates;
-  m_pAdvertisedDeviceCallbacks = pAdvertisedDeviceCallbacks;
-  m_shouldParse = shouldParse;
-}  // setAdvertisedDeviceCallbacks
-
-#ifdef SOC_BLE_50_SUPPORTED
-
-void BLEScan::setExtendedScanCallback(BLEExtAdvertisingCallbacks *cb) {
-  m_pExtendedScanCb = cb;
-}
-
-/**
-* @brief           This function is used to set the extended scan parameters to be used on the advertising channels.
-*
-*
-* @return            - ESP_OK : success
-*                    - other  : failed
-*
-*/
-esp_err_t BLEScan::setExtScanParams() {
-  esp_ble_ext_scan_params_t ext_scan_params = {
-    .own_addr_type = BLE_ADDR_TYPE_PUBLIC,
-    .filter_policy = BLE_SCAN_FILTER_ALLOW_ALL,
-    .scan_duplicate = BLE_SCAN_DUPLICATE_DISABLE,
-    .cfg_mask = ESP_BLE_GAP_EXT_SCAN_CFG_UNCODE_MASK | ESP_BLE_GAP_EXT_SCAN_CFG_CODE_MASK,
-    .uncoded_cfg = {BLE_SCAN_TYPE_ACTIVE, 40, 40},
-    .coded_cfg = {BLE_SCAN_TYPE_ACTIVE, 40, 40},
-  };
-
-  esp_err_t rc = esp_ble_gap_set_ext_scan_params(&ext_scan_params);
-  if (rc) {
-    log_e("set extend scan params error, error code = %x", rc);
-  }
-  return rc;
-}
-
-/**
-* @brief           This function is used to set the extended scan parameters to be used on the advertising channels.
-*
-* @param[in]       params : scan parameters
-*
-* @return            - ESP_OK : success
-*                    - other  : failed
-*
-*/
-esp_err_t BLEScan::setExtScanParams(esp_ble_ext_scan_params_t *ext_scan_params) {
-  esp_err_t rc = esp_ble_gap_set_ext_scan_params(ext_scan_params);
-  if (rc) {
-    log_e("set extend scan params error, error code = %x", rc);
-  }
-  return rc;
-}
-
-/**
-* @brief           This function is used to enable scanning.
-*
-* @param[in]       duration : Scan duration
-* @param[in]       period  : Time interval from when the Controller started its last Scan Duration until it begins the subsequent Scan Duration.
-*
-* @return            - ESP_OK : success
-*                    - other  : failed
-*
-*/
-esp_err_t BLEScan::startExtScan(uint32_t duration, uint16_t period) {
-  esp_err_t rc = esp_ble_gap_start_ext_scan(duration, period);
-  if (rc) {
-    log_e("extended scan start failed: %d", rc);
-  }
-  return rc;
-}
-
-esp_err_t BLEScan::stopExtScan() {
-  esp_err_t rc;
-  rc = esp_ble_gap_stop_ext_scan();
-
-  return rc;
-}
-
-void BLEScan::setPeriodicScanCallback(BLEPeriodicScanCallbacks *cb) {
-  m_pPeriodicScanCb = cb;
-}
-
-#endif  // SOC_BLE_50_SUPPORTED
-/**
- * @brief Set the interval to scan.
- * @param [in] The interval in msecs.
- */
-void BLEScan::setInterval(uint16_t intervalMSecs) {
-  m_scan_params.scan_interval = intervalMSecs / 0.625;
-}  // setInterval
-
-/**
- * @brief Set the window to actively scan.
- * @param [in] windowMSecs How long to actively scan.
- */
-void BLEScan::setWindow(uint16_t windowMSecs) {
-  m_scan_params.scan_window = windowMSecs / 0.625;
-}  // setWindow
-
 /**
  * @brief Start scanning.
  * @param [in] duration The duration in seconds for which to scan.
@@ -425,7 +551,7 @@ BLEScanResults *BLEScan::start(uint32_t duration, bool is_continue) {
  * @brief Stop an in progress scan.
  * @return N/A.
  */
-void BLEScan::stop() {
+bool BLEScan::stop() {
   log_v(">> stop()");
 
   esp_err_t errRc = ::esp_ble_gap_stop_scanning();
@@ -435,67 +561,303 @@ void BLEScan::stop() {
 
   if (errRc != ESP_OK) {
     log_e("esp_ble_gap_stop_scanning: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc));
-    return;
+    return false;
   }
 
   log_v("<< stop()");
+  return true;
 }  // stop
 
-// delete peer device from cache after disconnecting, it is required in case we are connecting to devices with not public address
-void BLEScan::erase(BLEAddress address) {
-  log_i("erase device: %s", address.toString().c_str());
-  BLEAdvertisedDevice *advertisedDevice = m_scanResults.m_vectorAdvertisedDevices.find(address.toString().c_str())->second;
-  m_scanResults.m_vectorAdvertisedDevices.erase(address.toString().c_str());
-  delete advertisedDevice;
+#endif  // CONFIG_BLUEDROID_ENABLED
+
+/***************************************************************************
+ *                         NimBLE functions                                *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
+/**
+ * @brief Set whether or not the BLE controller should only report results
+ * from devices it has not already seen.
+ * @param [in] enabled If true, scanned devices will only be reported once.
+ * @details The controller has a limited buffer and will start reporting
+ * duplicate devices once the limit is reached.
+ */
+void BLEScan::setDuplicateFilter(bool enabled) {
+  m_scan_params.filter_duplicates = enabled;
+}  // setDuplicateFilter
+
+/**
+ * @brief Get the status of the scanner.
+ * @return true if scanning or scan starting.
+ */
+bool BLEScan::isScanning() {
+  return ble_gap_disc_active();
 }
 
 /**
- * @brief Dump the scan results to the log.
+ * @brief Handle GAP events related to scans.
+ * @param [in] event The event type for this event.
+ * @param [in] param Parameter data for this event.
  */
-void BLEScanResults::dump() {
-  log_v(">> Dump scan results:");
-  for (int i = 0; i < getCount(); i++) {
-    log_d("- %s", getDevice(i).toString().c_str());
+int BLEScan::handleGAPEvent(ble_gap_event *event, void *arg) {
+  BLEScan *pScan = (BLEScan *)arg;
+
+  switch (event->type) {
+    case BLE_GAP_EVENT_DISC:
+    {
+      if (pScan->m_ignoreResults) {
+        log_i("Scan op in progress - ignoring results");
+        return 0;
+      }
+
+      const auto &disc = event->disc;
+      const auto event_type = disc.event_type;
+      const bool isLegacyAdv = true;
+      BLEAddress advertisedAddress(disc.addr);
+
+      BLEClient *client = BLEDevice::getClientByAddress(advertisedAddress);
+      if (client != nullptr && client->isConnected()) {
+        log_i("Client %s connected - ignoring event", advertisedAddress.toString().c_str());
+        return 0;
+      }
+
+      BLEAdvertisedDevice *advertisedDevice = nullptr;
+
+      // If we've seen this device before get a pointer to it from the vector
+      for (auto &it : pScan->m_scanResults.m_vectorAdvertisedDevices) {
+        if (it.second->getAddress() == advertisedAddress) {
+          advertisedDevice = it.second;
+          break;
+        }
+      }
+
+      // If we haven't seen this device before; create a new instance and insert it in the vector.
+      // Otherwise just update the relevant parameters of the already known device.
+      if (advertisedDevice == nullptr) {
+        // Check if we have reach the scan results limit, ignore this one if so.
+        // We still need to store each device when maxResults is 0 to be able to append the scan results
+        if (pScan->m_maxResults > 0 && pScan->m_maxResults < 0xFF && (pScan->m_scanResults.m_vectorAdvertisedDevices.size() >= pScan->m_maxResults)) {
+          return 0;
+        }
+
+        if (isLegacyAdv && event_type == BLE_HCI_ADV_RPT_EVTYPE_SCAN_RSP) {
+          log_i("Scan response without advertisement: %s", advertisedAddress.toString().c_str());
+        }
+
+        advertisedDevice = new BLEAdvertisedDevice();
+        advertisedDevice->setAddress(advertisedAddress);
+        advertisedDevice->setAddressType(event->disc.addr.type);
+        advertisedDevice->setAdvType(event_type);
+        pScan->m_scanResults.m_vectorAdvertisedDevices.insert(
+          std::pair<std::string, BLEAdvertisedDevice *>(advertisedAddress.toString().c_str(), advertisedDevice)
+        );
+        log_i("New advertiser: %s", advertisedAddress.toString().c_str());
+      } else if (advertisedDevice != nullptr) {
+        log_i("Updated advertiser: %s", advertisedAddress.toString().c_str());
+      } else {
+        // Scan response from unknown device
+        return 0;
+      }
+
+      advertisedDevice->setRSSI(event->disc.rssi);
+
+      if (pScan->m_shouldParse) {
+        advertisedDevice->parseAdvertisement((uint8_t *)event->disc.data, event->disc.length_data);
+      } else {
+        advertisedDevice->setPayload((uint8_t *)event->disc.data, event->disc.length_data, event_type == BLE_HCI_ADV_RPT_EVTYPE_SCAN_RSP);
+      }
+
+      advertisedDevice->setScan(pScan);
+
+      if (pScan->m_pAdvertisedDeviceCallbacks) {
+        // If not active scanning or scan response is not available
+        // report the result to the callback now.
+        if (pScan->m_scan_params.passive || !isLegacyAdv || !advertisedDevice->isScannable()) {
+          advertisedDevice->m_callbackSent = true;
+          pScan->m_pAdvertisedDeviceCallbacks->onResult(*advertisedDevice);
+
+          // Otherwise, wait for the scan response so we can report the complete data.
+        } else if (isLegacyAdv && event_type == BLE_HCI_ADV_RPT_EVTYPE_SCAN_RSP) {
+          advertisedDevice->m_callbackSent = true;
+          pScan->m_pAdvertisedDeviceCallbacks->onResult(*advertisedDevice);
+        }
+      }
+
+      // If not storing results and we have invoked the callback, delete the device.
+      if (pScan->m_maxResults == 0 && advertisedDevice->m_callbackSent) {
+        pScan->erase(advertisedAddress);
+      }
+
+      return 0;
+    }
+
+    case BLE_GAP_EVENT_DISC_COMPLETE:
+    {
+      log_d("discovery complete; reason=%d", event->disc_complete.reason);
+
+      // If a device advertised with scan response available and it was not received
+      // the callback would not have been invoked, so do it here.
+      if (pScan->m_pAdvertisedDeviceCallbacks) {
+        for (auto &it : pScan->m_scanResults.m_vectorAdvertisedDevices) {
+          if (!it.second->m_callbackSent) {
+            pScan->m_pAdvertisedDeviceCallbacks->onResult(*(it.second));
+          }
+        }
+      }
+
+      if (pScan->m_maxResults == 0) {
+        pScan->clearResults();
+      }
+
+      if (pScan->m_scanCompleteCB != nullptr) {
+        pScan->m_scanCompleteCB(pScan->m_scanResults);
+      }
+
+      if (pScan->m_pTaskData != nullptr) {
+        BLEUtils::taskRelease(*pScan->m_pTaskData, event->disc_complete.reason);
+      }
+
+      return 0;
+    }
+
+    default: return 0;
   }
-}  // dump
+}  // gapEventHandler
 
 /**
- * @brief Return the count of devices found in the last scan.
- * @return The number of devices found in the last scan.
+ * @brief Start scanning.
+ * @param [in] duration The duration in seconds for which to scan.
+ * @param [in] scanCompleteCB A function to be called when scanning has completed.
+ * @param [in] is_continue Set to true to save previous scan results, false to clear them.
+ * @return True if scan started or false if there was an error.
  */
-int BLEScanResults::getCount() {
-  return m_vectorAdvertisedDevices.size();
-}  // getCount
+bool BLEScan::start(uint32_t duration, void (*scanCompleteCB)(BLEScanResults), bool is_continue) {
+  log_d(">> start(duration=%d)", duration);
+
+  if (!is_continue) {
+    clearResults();
+  }
+
+  // Save the callback to be invoked when the scan completes.
+  m_scanCompleteCB = scanCompleteCB;
+  // Save the duration in the case that the host is reset so we can reuse it.
+  m_duration = duration;
+
+  // If 0 duration specified then we assume a continuous scan is desired.
+  if (duration == 0) {
+    duration = BLE_HS_FOREVER;
+  } else {
+    // convert duration to milliseconds
+    duration = duration * 1000;
+  }
+
+  // Set the flag to ignore the results while we are deleting the vector
+  if (!is_continue) {
+    m_ignoreResults = true;
+  }
+
+  int rc = ble_gap_disc(BLEDevice::m_ownAddrType, duration, &m_scan_params, BLEScan::handleGAPEvent, this);
+
+  switch (rc) {
+    case 0:
+    case BLE_HS_EALREADY: break;
+
+    case BLE_HS_EBUSY: log_e("Unable to scan - connection in progress."); break;
+
+    case BLE_HS_ETIMEOUT_HCI:
+    case BLE_HS_EOS:
+    case BLE_HS_ECONTROLLER:
+    case BLE_HS_ENOTSYNCED:   log_e("Unable to scan - Host Reset"); break;
+
+    default: log_e("Error initiating GAP discovery procedure; rc=%d, %s", rc, BLEUtils::returnCodeToString(rc)); break;
+  }
+
+  m_ignoreResults = false;
+  log_d("<< start()");
+
+  if (rc != 0 && rc != BLE_HS_EALREADY) {
+    return false;
+  }
+  return true;
+}  // start
 
 /**
- * @brief Return the specified device at the given index.
- * The index should be between 0 and getCount()-1.
- * @param [in] i The index of the device.
- * @return The device at the specified index.
+ * @brief Start scanning and block until scanning has been completed.
+ * @param [in] duration The duration in seconds for which to scan.
+ * @param [in] is_continue Set to true to save previous scan results, false to clear them.
+ * @return The BLEScanResults.
  */
-BLEAdvertisedDevice BLEScanResults::getDevice(uint32_t i) {
-  uint32_t x = 0;
-  BLEAdvertisedDevice dev = *m_vectorAdvertisedDevices.begin()->second;
-  for (auto it = m_vectorAdvertisedDevices.begin(); it != m_vectorAdvertisedDevices.end(); it++) {
-    dev = *it->second;
-    if (x == i) {
-      break;
-    }
-    x++;
+BLEScanResults *BLEScan::start(uint32_t duration, bool is_continue) {
+  if (duration == 0) {
+    log_w("Blocking scan called with duration = forever");
   }
-  return dev;
-}
 
-BLEScanResults *BLEScan::getResults() {
+  if (m_pTaskData != nullptr) {
+    log_e("Scan already in progress");
+    return &m_scanResults;
+  }
+
+  BLETaskData taskData(this);
+  m_pTaskData = &taskData;
+
+  if (start(duration, nullptr, is_continue)) {
+    BLEUtils::taskWait(taskData, BLE_NPL_TIME_FOREVER);
+  }
+
+  m_pTaskData = nullptr;
   return &m_scanResults;
+}  // start
+
+/**
+ * @brief Stop an in progress scan.
+ * @return True if successful.
+ */
+bool BLEScan::stop() {
+  log_d(">> stop()");
+
+  int rc = ble_gap_disc_cancel();
+  if (rc != 0 && rc != BLE_HS_EALREADY) {
+    log_e("Failed to cancel scan; rc=%d", rc);
+    return false;
+  }
+
+  if (m_maxResults == 0) {
+    clearResults();
+  }
+
+  if (rc != BLE_HS_EALREADY && m_scanCompleteCB != nullptr) {
+    m_scanCompleteCB(m_scanResults);
+  }
+
+  if (m_pTaskData != nullptr) {
+    BLEUtils::taskRelease(*m_pTaskData);
+  }
+
+  log_d("<< stop()");
+  return true;
+}  // stop
+
+/**
+ * @brief Called when host reset, we set a flag to stop scanning until synced.
+ */
+void BLEScan::onHostReset() {
+  m_ignoreResults = true;
 }
 
-void BLEScan::clearResults() {
-  for (auto _dev : m_scanResults.m_vectorAdvertisedDevices) {
-    delete _dev.second;
+/**
+ * @brief If the host reset and re-synced this is called.
+ * If the application was scanning indefinitely with a callback, restart it.
+ */
+void BLEScan::onHostSync() {
+  m_ignoreResults = false;
+
+  if (m_duration == 0 && m_pAdvertisedDeviceCallbacks != nullptr) {
+    start(m_duration, m_scanCompleteCB);
   }
-  m_scanResults.m_vectorAdvertisedDevices.clear();
 }
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif  // CONFIG_NIMBLE_ENABLED
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEScan.h b/libraries/BLE/src/BLEScan.h
index 080e3b803b2..842b7144f06 100644
--- a/libraries/BLE/src/BLEScan.h
+++ b/libraries/BLE/src/BLEScan.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Jul 1, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLESCAN_H_
@@ -11,22 +15,51 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
-#include <esp_gap_ble_api.h>
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                         Common includes                                 *
+ ***************************************************************************/
 
-// #include <vector>
 #include <string>
 #include "BLEAdvertisedDevice.h"
 #include "BLEClient.h"
+#include "BLEUtils.h"
 #include "RTOS.h"
 
+/***************************************************************************
+ *                         Bluedroid includes                              *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gap_ble_api.h>
+#endif
+
+/***************************************************************************
+ *                           NimBLE includes                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_gap.h>
+#endif
+
+/***************************************************************************
+ *                         Forward declarations                            *
+ ***************************************************************************/
+
 class BLEAdvertisedDevice;
 class BLEAdvertisedDeviceCallbacks;
 class BLEExtAdvertisingCallbacks;
 class BLEClient;
 class BLEScan;
 class BLEPeriodicScanCallbacks;
+struct BLETaskData;
 
+/***************************************************************************
+ *                       Bluedroid type definitions                        *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
 struct esp_ble_periodic_adv_sync_estab_param_t {
   uint8_t status;                    /*!< periodic advertising sync status */
   uint16_t sync_handle;              /*!< periodic advertising sync handle */
@@ -37,6 +70,7 @@ struct esp_ble_periodic_adv_sync_estab_param_t {
   uint16_t period_adv_interval;      /*!< periodic advertising interval */
   uint8_t adv_clk_accuracy;          /*!< periodic advertising clock accuracy */
 };
+#endif
 
 /**
  * @brief The result of having performed a scan.
@@ -47,12 +81,21 @@ struct esp_ble_periodic_adv_sync_estab_param_t {
  */
 class BLEScanResults {
 public:
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   void dump();
   int getCount();
   BLEAdvertisedDevice getDevice(uint32_t i);
 
 private:
   friend BLEScan;
+
+  /***************************************************************************
+   *                       Common private properties                         *
+   ***************************************************************************/
+
   std::map<std::string, BLEAdvertisedDevice *> m_vectorAdvertisedDevices;
 };
 
@@ -63,37 +106,52 @@ class BLEScanResults {
  */
 class BLEScan {
 public:
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
+  ~BLEScan();
   void setActiveScan(bool active);
   void setAdvertisedDeviceCallbacks(BLEAdvertisedDeviceCallbacks *pAdvertisedDeviceCallbacks, bool wantDuplicates = false, bool shouldParse = true);
   void setInterval(uint16_t intervalMSecs);
   void setWindow(uint16_t windowMSecs);
   bool start(uint32_t duration, void (*scanCompleteCB)(BLEScanResults), bool is_continue = false);
   BLEScanResults *start(uint32_t duration, bool is_continue = false);
-  void stop();
+  bool stop();
   void erase(BLEAddress address);
   BLEScanResults *getResults();
   void clearResults();
 
-#ifdef SOC_BLE_50_SUPPORTED
+  /***************************************************************************
+   *                       Bluedroid public declarations                     *
+   ***************************************************************************/
+
+#if defined(SOC_BLE_50_SUPPORTED) && defined(CONFIG_BLUEDROID_ENABLED)
   void setExtendedScanCallback(BLEExtAdvertisingCallbacks *cb);
   void setPeriodicScanCallback(BLEPeriodicScanCallbacks *cb);
-
   esp_err_t stopExtScan();
   esp_err_t setExtScanParams();
-  esp_err_t setExtScanParams(esp_ble_ext_scan_params_t *ext_scan_params);
   esp_err_t startExtScan(uint32_t duration, uint16_t period);
-
-private:
-  BLEExtAdvertisingCallbacks *m_pExtendedScanCb = nullptr;
-  BLEPeriodicScanCallbacks *m_pPeriodicScanCb = nullptr;
+  esp_err_t setExtScanParams(esp_ble_ext_scan_params_t *ext_scan_params);
 #endif  // SOC_BLE_50_SUPPORTED
 
+  /***************************************************************************
+   *                       NimBLE public declarations                        *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  void setDuplicateFilter(bool enabled);
+  bool isScanning();
+  void clearDuplicateCache();
+#endif
+
 private:
-  BLEScan();  // One doesn't create a new instance instead one asks the BLEDevice for the singleton.
   friend class BLEDevice;
-  void handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
 
-  esp_ble_scan_params_t m_scan_params;
+  /***************************************************************************
+   *                       Common private properties                         *
+   ***************************************************************************/
+
   BLEAdvertisedDeviceCallbacks *m_pAdvertisedDeviceCallbacks = nullptr;
   bool m_stopped = true;
   bool m_shouldParse = true;
@@ -101,21 +159,79 @@ class BLEScan {
   BLEScanResults m_scanResults;
   bool m_wantDuplicates;
   void (*m_scanCompleteCB)(BLEScanResults scanResults);
+
+  /***************************************************************************
+   *                       Bluedroid private properties                       *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  esp_ble_scan_params_t m_scan_params;
+#if defined(SOC_BLE_50_SUPPORTED)
+  BLEExtAdvertisingCallbacks *m_pExtendedScanCb = nullptr;
+  BLEPeriodicScanCallbacks *m_pPeriodicScanCb = nullptr;
+#endif  // SOC_BLE_50_SUPPORTED
+#endif
+
+  /***************************************************************************
+   *                       NimBLE private properties                         *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  uint32_t m_duration;
+  ble_gap_disc_params m_scan_params;
+  bool m_ignoreResults;
+  BLETaskData *m_pTaskData;
+  uint8_t m_maxResults;
+#endif
+
+  /***************************************************************************
+   *                       Common private definitions                        *
+   ***************************************************************************/
+
+  BLEScan();  // One doesn't create a new instance instead one asks the BLEDevice for the singleton.
+
+  /***************************************************************************
+   *                       Bluedroid private definitions                     *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  void handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param);
+#endif
+
+  /***************************************************************************
+   *                       NimBLE private definitions                        *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  void onHostReset();
+  void onHostSync();
+  static int handleGAPEvent(ble_gap_event *event, void *arg);
+#endif
 };  // BLEScan
 
 class BLEPeriodicScanCallbacks {
 public:
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   virtual ~BLEPeriodicScanCallbacks() {}
+  virtual void onLostSync(uint16_t sync_handle) {}
 
+  /***************************************************************************
+   *                       Bluedroid public declarations                     *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
   virtual void onCreateSync(esp_bt_status_t status) {}
   virtual void onCancelSync(esp_bt_status_t status) {}
   virtual void onTerminateSync(esp_bt_status_t status) {}
-  virtual void onLostSync(uint16_t sync_handle) {}
   virtual void onSync(esp_ble_periodic_adv_sync_estab_param_t) {}
   virtual void onReport(esp_ble_gap_periodic_adv_report_t params) {}
   virtual void onStop(esp_bt_status_t status) {}
+#endif
 };
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLESCAN_H_ */
diff --git a/libraries/BLE/src/BLESecurity.cpp b/libraries/BLE/src/BLESecurity.cpp
index 34fc3e69e9e..978026a3809 100644
--- a/libraries/BLE/src/BLESecurity.cpp
+++ b/libraries/BLE/src/BLESecurity.cpp
@@ -3,77 +3,114 @@
  *
  *  Created on: Dec 17, 2017
  *      Author: chegewara
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on chegewara's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
-#include "BLESecurity.h"
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                         Common includes                                 *
+ ***************************************************************************/
+
+#include "BLESecurity.h"
+#include "BLEUtils.h"
+#include "esp32-hal-log.h"
+
+/***************************************************************************
+ *                         NimBLE includes                                 *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_hs.h>
+#endif
+
+/***************************************************************************
+ *                         Common properties                               *
+ ***************************************************************************/
+
+uint32_t BLESecurity::m_passkey = BLE_SM_DEFAULT_PASSKEY;
+
+/***************************************************************************
+ *                          Common functions                               *
+ ***************************************************************************/
 
 BLESecurity::BLESecurity() {}
 
 BLESecurity::~BLESecurity() {}
-/*
- * @brief Set requested authentication mode
- */
-void BLESecurity::setAuthenticationMode(esp_ble_auth_req_t auth_req) {
+
+void BLESecurity::setAuthenticationMode(uint8_t auth_req) {
   m_authReq = auth_req;
-  esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &m_authReq, sizeof(uint8_t));  // <--- setup requested authentication mode
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &m_authReq, sizeof(uint8_t));
+#elif defined(CONFIG_NIMBLE_ENABLED)
+  BLESecurity::setAuthenticationMode(
+    (auth_req & BLE_SM_PAIR_AUTHREQ_BOND) != 0, (auth_req & BLE_SM_PAIR_AUTHREQ_MITM) != 0, (auth_req & BLE_SM_PAIR_AUTHREQ_SC) != 0
+  );
+#endif
 }
 
-/**
- * @brief 	Set our device IO capability to let end user perform authorization
- * 			either by displaying or entering generated 6-digits pin code
- */
-void BLESecurity::setCapability(esp_ble_io_cap_t iocap) {
+void BLESecurity::setCapability(uint8_t iocap) {
   m_iocap = iocap;
+#if defined(CONFIG_BLUEDROID_ENABLED)
   esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t));
-}  // setCapability
+#elif defined(CONFIG_NIMBLE_ENABLED)
+  ble_hs_cfg.sm_io_cap = iocap;
+#endif
+}
 
-/**
- * @brief Init encryption key by server
- * @param key_size is value between 7 and 16
- */
 void BLESecurity::setInitEncryptionKey(uint8_t init_key) {
   m_initKey = init_key;
+#if defined(CONFIG_BLUEDROID_ENABLED)
   esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &m_initKey, sizeof(uint8_t));
-}  // setInitEncryptionKey
+#elif defined(CONFIG_NIMBLE_ENABLED)
+  ble_hs_cfg.sm_our_key_dist = init_key;
+#endif
+}
 
-/**
- * @brief Init encryption key by client
- * @param key_size is value between 7 and 16
- */
 void BLESecurity::setRespEncryptionKey(uint8_t resp_key) {
   m_respKey = resp_key;
+#if defined(CONFIG_BLUEDROID_ENABLED)
   esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &m_respKey, sizeof(uint8_t));
-}  // setRespEncryptionKey
+#elif defined(CONFIG_NIMBLE_ENABLED)
+  ble_hs_cfg.sm_their_key_dist = resp_key;
+#endif
+}
 
-/**
- *
- *
- */
 void BLESecurity::setKeySize(uint8_t key_size) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
   m_keySize = key_size;
   esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &m_keySize, sizeof(uint8_t));
-}  //setKeySize
+#endif
+}
 
-/**
- * Setup for static PIN connection, call it first and then call setAuthenticationMode eventually to change it
- */
 void BLESecurity::setStaticPIN(uint32_t pin) {
-  uint32_t passkey = pin;
-  esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &passkey, sizeof(uint32_t));
+  m_passkey = pin;
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &m_passkey, sizeof(uint32_t));
   setCapability(ESP_IO_CAP_OUT);
   setKeySize();
   setAuthenticationMode(ESP_LE_AUTH_REQ_SC_ONLY);
   setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);
+#elif defined(CONFIG_NIMBLE_ENABLED)
+  setCapability(BLE_HS_IO_DISPLAY_ONLY);
+  setKeySize();
+  setAuthenticationMode(false, false, true);  // No bonding, no MITM, secure connection only
+  setInitEncryptionKey(BLE_HS_KEY_DIST_ENC_KEY | BLE_HS_KEY_DIST_ID_KEY);
+#endif
 }
 
-/**
- * @brief Debug function to display what keys are exchanged by peers
- */
+/***************************************************************************
+ *                          Bluedroid functions                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
 char *BLESecurity::esp_key_type_to_str(esp_ble_key_type_t key_type) {
   char *key_str = nullptr;
   switch (key_type) {
@@ -89,7 +126,34 @@ char *BLESecurity::esp_key_type_to_str(esp_ble_key_type_t key_type) {
     default:               key_str = (char *)"INVALID BLE KEY TYPE"; break;
   }
   return key_str;
-}  // esp_key_type_to_str
+}
+#endif
+
+/***************************************************************************
+ *                          NimBLE functions                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+void BLESecurity::setAuthenticationMode(bool bonding, bool mitm, bool sc) {
+  m_authReq = bonding ? BLE_SM_PAIR_AUTHREQ_BOND : 0;
+  m_authReq |= mitm ? BLE_SM_PAIR_AUTHREQ_MITM : 0;
+  m_authReq |= sc ? BLE_SM_PAIR_AUTHREQ_SC : 0;
+  ble_hs_cfg.sm_bonding = bonding;
+  ble_hs_cfg.sm_mitm = mitm;
+  ble_hs_cfg.sm_sc = sc;
+}
+
+bool BLESecurity::startSecurity(uint16_t connHandle, int *rcPtr) {
+  int rc = ble_gap_security_initiate(connHandle);
+  if (rc != 0) {
+    log_e("ble_gap_security_initiate: rc=%d %s", rc, BLEUtils::returnCodeToString(rc));
+  }
+  if (rcPtr) {
+    *rcPtr = rc;
+  }
+  return rc == 0 || rc == BLE_HS_EALREADY;
+}
+#endif
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLESecurity.h b/libraries/BLE/src/BLESecurity.h
index 2e3a44b42d1..574110e6118 100644
--- a/libraries/BLE/src/BLESecurity.h
+++ b/libraries/BLE/src/BLESecurity.h
@@ -3,74 +3,148 @@
  *
  *  Created on: Dec 17, 2017
  *      Author: chegewara
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on chegewara's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLESECURITY_H_
 #define COMPONENTS_CPP_UTILS_BLESECURITY_H_
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                            Common includes                              *
+ ***************************************************************************/
+
+#include "WString.h"
 
+/***************************************************************************
+ *                           Bluedroid includes                            *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
 #include <esp_gap_ble_api.h>
+#endif
+
+/***************************************************************************
+ *                             NimBLE includes                             *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_gap.h>
+#endif
 
+/***************************************************************************
+ *                            Common definitions                           *
+ ***************************************************************************/
+
+#define BLE_SM_DEFAULT_PASSKEY 123456
+
+/***************************************************************************
+ *                          Forward declarations                           *
+ ***************************************************************************/
+
+class BLEServer;
+class BLEClient;
+
+/**
+ * @brief Security management class
+ */
 class BLESecurity {
 public:
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   BLESecurity();
   virtual ~BLESecurity();
-  void setAuthenticationMode(esp_ble_auth_req_t auth_req);
-  void setCapability(esp_ble_io_cap_t iocap);
-  void setInitEncryptionKey(uint8_t init_key);
-  void setRespEncryptionKey(uint8_t resp_key);
-  void setKeySize(uint8_t key_size = 16);
-  void setStaticPIN(uint32_t pin);
+  static void setAuthenticationMode(uint8_t auth_req);
+  static void setCapability(uint8_t iocap);
+  static void setInitEncryptionKey(uint8_t init_key);
+  static void setRespEncryptionKey(uint8_t resp_key);
+  static void setKeySize(uint8_t key_size = 16);
+  static void setStaticPIN(uint32_t pin);
+
+  /***************************************************************************
+   *                       Bluedroid public declarations                     *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
   static char *esp_key_type_to_str(esp_ble_key_type_t key_type);
+#endif
+
+  /***************************************************************************
+   *                       NimBLE public declarations                        *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  static void setAuthenticationMode(bool bonding, bool mitm, bool sc);
+  static bool startSecurity(uint16_t connHandle, int *rcPtr = nullptr);
+#endif
 
 private:
-  esp_ble_auth_req_t m_authReq;
-  esp_ble_io_cap_t m_iocap;
-  uint8_t m_initKey;
-  uint8_t m_respKey;
-  uint8_t m_keySize;
+  friend class BLEServer;
+  friend class BLEClient;
+
+  /***************************************************************************
+   *                       Common private properties                         *
+   ***************************************************************************/
+
+  static uint8_t m_iocap;
+  static uint8_t m_authReq;
+  static uint8_t m_initKey;
+  static uint8_t m_respKey;
+  static uint32_t m_passkey;
+
+  /***************************************************************************
+   *                       Bluedroid private properties                       *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  static uint8_t m_keySize;
+#endif
 
 };  // BLESecurity
 
-/*
+/**
  * @brief Callbacks to handle GAP events related to authorization
  */
 class BLESecurityCallbacks {
 public:
-  virtual ~BLESecurityCallbacks(){};
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
 
-  /**
-	 * @brief Its request from peer device to input authentication pin code displayed on peer device.
-	 * It requires that our device is capable to input 6-digits code by end user
-	 * @return Return 6-digits integer value from input device
-	 */
+  virtual ~BLESecurityCallbacks(){};
   virtual uint32_t onPassKeyRequest() = 0;
-
-  /**
-	 * @brief Provide us 6-digits code to perform authentication.
-	 * It requires that our device is capable to display this code to end user
-	 * @param
-	 */
   virtual void onPassKeyNotify(uint32_t pass_key) = 0;
+  virtual bool onSecurityRequest() = 0;
+  virtual bool onConfirmPIN(uint32_t pin) = 0;
 
-  /**
-	 * @brief Here we can make decision if we want to let negotiate authorization with peer device or not
-	 * return Return true if we accept this peer device request
-	 */
+  /***************************************************************************
+   *                       Bluedroid public declarations                     *
+   ***************************************************************************/
 
-  virtual bool onSecurityRequest() = 0;
-  /**
-	 * Provide us information when authentication process is completed
-	 */
+#if defined(CONFIG_BLUEDROID_ENABLED)
   virtual void onAuthenticationComplete(esp_ble_auth_cmpl_t) = 0;
+#endif
+
+  /***************************************************************************
+   *                       NimBLE public declarations                        *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  virtual void onAuthenticationComplete(ble_gap_conn_desc *) = 0;
+#endif
 
-  virtual bool onConfirmPIN(uint32_t pin) = 0;
 };  // BLESecurityCallbacks
 
-#endif  /* CONFIG_BLUEDROID_ENABLED */
+#endif  /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif  /* SOC_BLE_SUPPORTED */
 #endif  // COMPONENTS_CPP_UTILS_BLESECURITY_H_
diff --git a/libraries/BLE/src/BLEServer.cpp b/libraries/BLE/src/BLEServer.cpp
index a338cf61451..323237e965e 100644
--- a/libraries/BLE/src/BLEServer.cpp
+++ b/libraries/BLE/src/BLEServer.cpp
@@ -3,14 +3,23 @@
  *
  *  Created on: Apr 16, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/***************************************************************************
+ *                       Common includes                                   *
+ ***************************************************************************/
+
 #include <esp_bt.h>
-#include <esp_bt_main.h>
 #include "GeneralUtils.h"
 #include "BLEDevice.h"
 #include "BLEServer.h"
@@ -21,6 +30,27 @@
 #include <unordered_set>
 #include "esp32-hal-log.h"
 
+/***************************************************************************
+ *                       Bluedroid includes                                *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_bt_main.h>
+#endif
+
+/***************************************************************************
+ *                       NimBLE includes                                   *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <services/gap/ble_svc_gap.h>
+#include <services/gatt/ble_svc_gatt.h>
+#endif
+
+/***************************************************************************
+ *                        Common functions                                 *
+ ***************************************************************************/
+
 /**
  * @brief Construct a %BLE Server
  *
@@ -28,8 +58,17 @@
  * the BLEDevice class.
  */
 BLEServer::BLEServer() {
-  m_appId = ESP_GATT_IF_NONE;
+#ifdef CONFIG_BLUEDROID_ENABLED
   m_gatts_if = ESP_GATT_IF_NONE;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  memset(m_indWait, BLE_HS_CONN_HANDLE_NONE, sizeof(m_indWait));
+  m_svcChanged = false;
+#endif
+
+  m_appId = ESP_GATT_IF_NONE;
+  m_gattsStarted = false;
   m_connectedCount = 0;
   m_connId = ESP_GATT_IF_NONE;
   m_pServerCallbacks = nullptr;
@@ -37,7 +76,9 @@ BLEServer::BLEServer() {
 
 void BLEServer::createApp(uint16_t appId) {
   m_appId = appId;
+#ifdef CONFIG_BLUEDROID_ENABLED
   registerApp(appId);
+#endif
 }  // createApp
 
 /**
@@ -64,7 +105,9 @@ BLEService *BLEServer::createService(const char *uuid) {
  */
 BLEService *BLEServer::createService(BLEUUID uuid, uint32_t numHandles, uint8_t inst_id) {
   log_v(">> createService - %s", uuid.toString().c_str());
+#ifdef CONFIG_BLUEDROID_ENABLED
   m_semaphoreCreateEvt.take("createService");
+#endif
 
   // Check that a service with the supplied UUID does not already exist.
   if (m_serviceMap.getByUUID(uuid) != nullptr) {
@@ -76,7 +119,14 @@ BLEService *BLEServer::createService(BLEUUID uuid, uint32_t numHandles, uint8_t
   m_serviceMap.setByUUID(uuid, pService);  // Save a reference to this service being on this server.
   pService->executeCreate(this);           // Perform the API calls to actually create the service.
 
+#ifdef CONFIG_BLUEDROID_ENABLED
   m_semaphoreCreateEvt.wait("createService");
+#endif
+
+#ifdef CONFIG_NIMBLE_ENABLED
+  m_semaphoreCreateEvt.give();
+  serviceChanged();
+#endif
 
   log_v("<< createService");
   return pService;
@@ -121,6 +171,190 @@ uint32_t BLEServer::getConnectedCount() {
   return m_connectedCount;
 }  // getConnectedCount
 
+void BLEServer::start() {
+  if (m_gattsStarted) {
+    return;
+  }
+
+#ifdef CONFIG_NIMBLE_ENABLED
+  int rc = ble_gatts_start();
+  if (rc != 0) {
+    log_e("ble_gatts_start; rc=%d, %s", rc, BLEUtils::returnCodeToString(rc));
+    return;
+  }
+
+#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
+  ble_gatts_show_local();
+#endif
+
+  BLEService *svc = m_serviceMap.getFirst();
+  while (svc != nullptr) {
+    if (svc->m_removed == 0) {
+      rc = ble_gatts_find_svc(&svc->getUUID().getNative()->u, &svc->m_handle);
+      if (rc != 0) {
+        abort();
+      }
+    }
+
+    BLECharacteristic *chr = svc->m_characteristicMap.getFirst();
+    while (chr != nullptr) {
+      if ((chr->m_properties & BLE_GATT_CHR_F_INDICATE) || (chr->m_properties & BLE_GATT_CHR_F_NOTIFY)) {
+        m_notifyChrVec.push_back(chr);
+      }
+      chr = svc->m_characteristicMap.getNext();
+    }
+
+    svc = m_serviceMap.getNext();
+  }
+
+#endif
+
+  m_gattsStarted = true;
+}
+
+/**
+ * @brief Set the server callbacks.
+ *
+ * As a %BLE server operates, it will generate server level events such as a new client connecting or a previous client
+ * disconnecting.  This function can be called to register a callback handler that will be invoked when these
+ * events are detected.
+ *
+ * @param [in] pCallbacks The callbacks to be invoked.
+ */
+void BLEServer::setCallbacks(BLEServerCallbacks *pCallbacks) {
+  m_pServerCallbacks = pCallbacks;
+}  // setCallbacks
+
+/*
+ * Remove service
+ */
+void BLEServer::removeService(BLEService *service) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  service->stop();
+  service->executeDelete();
+  m_serviceMap.removeService(service);
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  if (service->m_removed == 0) {
+    int rc = ble_gatts_svc_set_visibility(service->getHandle(), 0);
+    if (rc != 0) {
+      return;
+    }
+    service->m_removed = NIMBLE_ATT_REMOVE_DELETE;
+    serviceChanged();
+    m_serviceMap.removeService(service);
+    BLEDevice::getAdvertising()->removeServiceUUID(service->getUUID());
+  }
+#endif
+}
+
+/**
+ * @brief Start advertising.
+ *
+ * Start the server advertising its existence.  This is a convenience function and is equivalent to
+ * retrieving the advertising object and invoking start upon it.
+ */
+void BLEServer::startAdvertising() {
+  log_v(">> startAdvertising");
+  BLEDevice::startAdvertising();
+  log_v("<< startAdvertising");
+}  // startAdvertising
+
+/* multi connect support */
+/* TODO do some more tweaks */
+void BLEServer::updatePeerMTU(uint16_t conn_id, uint16_t mtu) {
+  // set mtu in conn_status_t
+  const std::map<uint16_t, conn_status_t>::iterator it = m_connectedServersMap.find(conn_id);
+  if (it != m_connectedServersMap.end()) {
+    it->second.mtu = mtu;
+    std::swap(m_connectedServersMap[conn_id], it->second);
+  }
+}
+
+std::map<uint16_t, conn_status_t> BLEServer::getPeerDevices(bool _client) {
+  return m_connectedServersMap;
+}
+
+uint16_t BLEServer::getPeerMTU(uint16_t conn_id) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  return m_connectedServersMap.find(conn_id)->second.mtu;
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  return ble_att_mtu(conn_id);
+#endif
+}
+
+void BLEServer::addPeerDevice(void *peer, bool _client, uint16_t conn_id) {
+  conn_status_t status = {.peer_device = peer, .connected = true, .mtu = 23};
+
+  m_connectedServersMap.insert(std::pair<uint16_t, conn_status_t>(conn_id, status));
+}
+
+bool BLEServer::removePeerDevice(uint16_t conn_id, bool _client) {
+  return m_connectedServersMap.erase(conn_id) > 0;
+}
+
+void BLEServerCallbacks::onConnect(BLEServer *pServer) {
+  log_d("BLEServerCallbacks", ">> onConnect(): Default");
+  log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str());
+  log_d("BLEServerCallbacks", "<< onConnect()");
+}  // onConnect
+
+void BLEServerCallbacks::onDisconnect(BLEServer *pServer) {
+  log_d("BLEServerCallbacks", ">> onDisconnect(): Default");
+  log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str());
+  log_d("BLEServerCallbacks", "<< onDisconnect()");
+}  // onDisconnect
+
+/***************************************************************************
+ *                       Bluedroid functions                               *
+ ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+
+/**
+ * Allow to connect GATT server to peer device
+ * Probably can be used in ANCS for iPhone
+ */
+bool BLEServer::connect(BLEAddress address) {
+  esp_bd_addr_t addr;
+  memcpy(&addr, address.getNative(), 6);
+  // Perform the open connection request against the target BLE Server.
+  m_semaphoreOpenEvt.take("connect");
+  esp_err_t errRc = ::esp_ble_gatts_open(
+    getGattsIf(),
+    addr,  // address
+    1      // direct connection
+  );
+  if (errRc != ESP_OK) {
+    log_e("esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+    return false;
+  }
+
+  uint32_t rc = m_semaphoreOpenEvt.wait("connect");  // Wait for the connection to complete.
+  log_v("<< connect(), rc=%d", rc == ESP_GATT_OK);
+  return rc == ESP_GATT_OK;
+}  // connect
+
+/**
+ * Update connection parameters can be called only after connection has been established
+ */
+void BLEServer::updateConnParams(esp_bd_addr_t remote_bda, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t timeout) {
+  esp_ble_conn_update_params_t conn_params;
+  memcpy(conn_params.bda, remote_bda, sizeof(esp_bd_addr_t));
+  conn_params.latency = latency;
+  conn_params.max_int = maxInterval;  // max_int = 0x20*1.25ms = 40ms
+  conn_params.min_int = minInterval;  // min_int = 0x10*1.25ms = 20ms
+  conn_params.timeout = timeout;      // timeout = 400*10ms = 4000ms
+  esp_ble_gap_update_conn_params(&conn_params);
+}
+
+void BLEServer::disconnect(uint16_t connId) {
+  esp_ble_gatts_close(m_gatts_if, connId);
+}
+
 uint16_t BLEServer::getGattsIf() {
   return m_gatts_if;
 }
@@ -288,140 +522,450 @@ void BLEServer::registerApp(uint16_t m_appId) {
   log_v("<< registerApp");
 }  // registerApp
 
+// Bluedroid callbacks
+
+void BLEServerCallbacks::onConnect(BLEServer *pServer, esp_ble_gatts_cb_param_t *param) {
+  log_d("BLEServerCallbacks", ">> onConnect(): Default");
+  log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str());
+  log_d("BLEServerCallbacks", "<< onConnect()");
+}  // onConnect
+
+void BLEServerCallbacks::onDisconnect(BLEServer *pServer, esp_ble_gatts_cb_param_t *param) {
+  log_d("BLEServerCallbacks", ">> onDisconnect(): Default");
+  log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str());
+  log_d("BLEServerCallbacks", "<< onDisconnect()");
+}  // onDisconnect
+
+void BLEServerCallbacks::onMtuChanged(BLEServer *pServer, esp_ble_gatts_cb_param_t *param) {
+  [[maybe_unused]]
+  uint16_t mtu = param->mtu.mtu;
+  log_d("BLEServerCallbacks", ">> onMtuChanged(): Default");
+  log_d("BLEServerCallbacks", "Device: %s MTU: %d", BLEDevice::toString().c_str(), mtu);
+  log_d("BLEServerCallbacks", "<< onMtuChanged()");
+}  // onMtuChanged
+
+#endif
+
+/***************************************************************************
+ *                       NimBLE functions                                  *
+ ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
+uint16_t BLEServer::getHandle() {
+  return getConnId();
+}
+
 /**
- * @brief Set the server callbacks.
+ * @brief Resets the GATT server, used when services are added/removed after initialization.
+ */
+void BLEServer::resetGATT() {
+  if (getConnectedCount() > 0) {
+    return;
+  }
+
+  BLEDevice::stopAdvertising();
+  ble_gatts_reset();
+  ble_svc_gap_init();
+  ble_svc_gatt_init();
+
+  BLEService *svc = m_serviceMap.getFirst();
+  while (svc != nullptr) {
+    if (svc->m_removed > 0) {
+      if (svc->m_removed == NIMBLE_ATT_REMOVE_DELETE) {
+        m_serviceMap.removeService(svc);
+        delete svc;
+      }
+    } else {
+      svc->start();
+    }
+
+    svc = m_serviceMap.getNext();
+  }
+
+  m_svcChanged = false;
+  m_gattsStarted = false;
+}
+
+/**
+ * @brief Handle a GATT Server Event.
  *
- * As a %BLE server operates, it will generate server level events such as a new client connecting or a previous client
- * disconnecting.  This function can be called to register a callback handler that will be invoked when these
- * events are detected.
+ * @param [in] event
+ * @param [in] gatts_if
+ * @param [in] param
  *
- * @param [in] pCallbacks The callbacks to be invoked.
  */
-void BLEServer::setCallbacks(BLEServerCallbacks *pCallbacks) {
-  m_pServerCallbacks = pCallbacks;
-}  // setCallbacks
+int BLEServer::handleGATTServerEvent(struct ble_gap_event *event, void *arg) {
+  BLEServer *server = (BLEServer *)arg;
+  log_v(">> handleGAPEvent: %s", BLEUtils::gapEventToString(event->type));
+  int rc = 0;
+  struct ble_gap_conn_desc desc;
+
+  switch (event->type) {
+    case BLE_GAP_EVENT_CONNECT:
+    {
+      if (event->connect.status != 0) {
+        /* Connection failed; resume advertising */
+        log_e("Connection failed");
+        BLEDevice::startAdvertising();
+      } else {
+        server->m_connId = event->connect.conn_handle;
+        server->addPeerDevice((void *)server, false, event->connect.conn_handle);
+        rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
+        if (rc != 0) {
+          return 0;
+        }
+
+        if (server->m_pServerCallbacks != nullptr) {
+          server->m_pServerCallbacks->onConnect(server);
+          server->m_pServerCallbacks->onConnect(server, &desc);
+        }
+
+        server->m_connectedCount++;
+      }
 
-/*
- * Remove service
- */
-void BLEServer::removeService(BLEService *service) {
-  service->stop();
-  service->executeDelete();
-  m_serviceMap.removeService(service);
+      return 0;
+    }  // BLE_GAP_EVENT_CONNECT
+
+    case BLE_GAP_EVENT_DISCONNECT:
+    {
+      // If Host reset tell the device now before returning to prevent
+      // any errors caused by calling host functions before resyncing.
+      switch (event->disconnect.reason) {
+        case BLE_HS_ETIMEOUT_HCI:
+        case BLE_HS_EOS:
+        case BLE_HS_ECONTROLLER:
+        case BLE_HS_ENOTSYNCED:
+          log_d("Disconnect - host reset, rc=%d", event->disconnect.reason);
+          BLEDevice::onReset(event->disconnect.reason);
+          break;
+        default: break;
+      }
+
+      if (server->removePeerDevice(event->disconnect.conn.conn_handle, false)) {
+        server->m_connectedCount--;
+      }
+
+      if (server->m_svcChanged) {
+        server->resetGATT();
+      }
+
+      if (server->m_pServerCallbacks != nullptr) {
+        server->m_pServerCallbacks->onDisconnect(server);
+        server->m_pServerCallbacks->onDisconnect(server, &event->disconnect.conn);
+      }
+
+      return 0;
+    }  // BLE_GAP_EVENT_DISCONNECT
+
+    case BLE_GAP_EVENT_SUBSCRIBE:
+    {
+      log_i("subscribe event; attr_handle=%d, subscribed: %s", event->subscribe.attr_handle, (event->subscribe.cur_notify ? "true" : "false"));
+
+      for (auto &it : server->m_notifyChrVec) {
+        if (it->getHandle() == event->subscribe.attr_handle) {
+          uint16_t properties = it->getProperties();
+          if ((properties & BLE_GATT_CHR_F_READ_AUTHEN) || (properties & BLE_GATT_CHR_F_READ_AUTHOR) || (properties & BLE_GATT_CHR_F_READ_ENC)) {
+            rc = ble_gap_conn_find(event->subscribe.conn_handle, &desc);
+            if (rc != 0) {
+              break;
+            }
+
+            if (!desc.sec_state.encrypted) {
+              BLESecurity::startSecurity(event->subscribe.conn_handle);
+            }
+          }
+
+          it->setSubscribe(event);
+          break;
+        }
+      }
+
+      return 0;
+    }  // BLE_GAP_EVENT_SUBSCRIBE
+
+    case BLE_GAP_EVENT_MTU:
+    {
+      log_i("mtu update event; conn_handle=%d mtu=%d", event->mtu.conn_handle, event->mtu.value);
+      rc = ble_gap_conn_find(event->mtu.conn_handle, &desc);
+      if (rc != 0) {
+        return 0;
+      }
+
+      if (server->m_pServerCallbacks != nullptr) {
+        server->m_pServerCallbacks->onMtuChanged(server, &desc, event->mtu.value);
+      }
+      return 0;
+    }  // BLE_GAP_EVENT_MTU
+
+    case BLE_GAP_EVENT_NOTIFY_TX:
+    {
+      BLECharacteristic *pChar = nullptr;
+
+      for (auto &it : server->m_notifyChrVec) {
+        if (it->getHandle() == event->notify_tx.attr_handle) {
+          pChar = it;
+        }
+      }
+
+      if (pChar == nullptr) {
+        return 0;
+      }
+
+      BLECharacteristicCallbacks::Status statusRC;
+
+      if (event->notify_tx.indication) {
+        if (event->notify_tx.status != 0) {
+          if (event->notify_tx.status == BLE_HS_EDONE) {
+            statusRC = BLECharacteristicCallbacks::Status::SUCCESS_INDICATE;
+          } else if (rc == BLE_HS_ETIMEOUT) {
+            statusRC = BLECharacteristicCallbacks::Status::ERROR_INDICATE_TIMEOUT;
+          } else {
+            statusRC = BLECharacteristicCallbacks::Status::ERROR_INDICATE_FAILURE;
+          }
+        } else {
+          return 0;
+        }
+
+        server->clearIndicateWait(event->notify_tx.conn_handle);
+      } else {
+        if (event->notify_tx.status == 0) {
+          statusRC = BLECharacteristicCallbacks::Status::SUCCESS_NOTIFY;
+        } else {
+          statusRC = BLECharacteristicCallbacks::Status::ERROR_GATT;
+        }
+      }
+
+      pChar->m_pCallbacks->onStatus(pChar, statusRC, event->notify_tx.status);
+
+      return 0;
+    }  // BLE_GAP_EVENT_NOTIFY_TX
+
+    case BLE_GAP_EVENT_ADV_COMPLETE:
+    {
+      log_d("Advertising Complete");
+      BLEDevice::getAdvertising()->advCompleteCB();
+      return 0;
+    }
+
+    case BLE_GAP_EVENT_CONN_UPDATE:
+    {
+      log_d("Connection parameters updated.");
+      return 0;
+    }  // BLE_GAP_EVENT_CONN_UPDATE
+
+    case BLE_GAP_EVENT_REPEAT_PAIRING:
+    {
+      /* We already have a bond with the peer, but it is attempting to
+       * establish a new secure link.  This app sacrifices security for
+       * convenience: just throw away the old bond and accept the new link.
+       */
+
+      /* Delete the old bond. */
+      rc = ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc);
+      if (rc != 0) {
+        return BLE_GAP_REPEAT_PAIRING_IGNORE;
+      }
+
+      ble_store_util_delete_peer(&desc.peer_id_addr);
+
+      /* Return BLE_GAP_REPEAT_PAIRING_RETRY to indicate that the host should
+       * continue with the pairing operation.
+       */
+      return BLE_GAP_REPEAT_PAIRING_RETRY;
+    }  // BLE_GAP_EVENT_REPEAT_PAIRING
+
+    case BLE_GAP_EVENT_ENC_CHANGE:
+    {
+      rc = ble_gap_conn_find(event->enc_change.conn_handle, &desc);
+      if (rc != 0) {
+        return BLE_ATT_ERR_INVALID_HANDLE;
+      }
+
+      if (BLEDevice::m_securityCallbacks != nullptr) {
+        BLEDevice::m_securityCallbacks->onAuthenticationComplete(&desc);
+      } else if (server->m_pServerCallbacks != nullptr) {
+        server->m_pServerCallbacks->onAuthenticationComplete(&desc);
+      }
+
+      return 0;
+    }  // BLE_GAP_EVENT_ENC_CHANGE
+
+    case BLE_GAP_EVENT_PASSKEY_ACTION:
+    {
+      struct ble_sm_io pkey = {0, 0};
+
+      if (event->passkey.params.action == BLE_SM_IOACT_DISP) {
+        pkey.action = event->passkey.params.action;
+        // backward compatibility
+        pkey.passkey = BLESecurity::m_passkey;
+        // if the (static)passkey is the default, check the callback for custom value
+        // both values default to the same.
+        if (pkey.passkey == BLE_SM_DEFAULT_PASSKEY) {
+          if (server->m_pServerCallbacks != nullptr) {
+            pkey.passkey = server->m_pServerCallbacks->onPassKeyRequest();
+          }
+        }
+        rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
+        log_d("BLE_SM_IOACT_DISP; ble_sm_inject_io result: %d", rc);
+
+      } else if (event->passkey.params.action == BLE_SM_IOACT_NUMCMP) {
+        log_d("Passkey on device's display: %d", event->passkey.params.numcmp);
+        pkey.action = event->passkey.params.action;
+        // Compatibility only - Do not use, should be removed the in future
+        if (BLEDevice::m_securityCallbacks != nullptr) {
+          pkey.numcmp_accept = BLEDevice::m_securityCallbacks->onConfirmPIN(event->passkey.params.numcmp);
+        } else if (server->m_pServerCallbacks != nullptr) {
+          pkey.numcmp_accept = server->m_pServerCallbacks->onConfirmPIN(event->passkey.params.numcmp);
+        }
+
+        rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
+        log_d("BLE_SM_IOACT_NUMCMP; ble_sm_inject_io result: %d", rc);
+
+        //TODO: Handle out of band pairing
+      } else if (event->passkey.params.action == BLE_SM_IOACT_OOB) {
+        static uint8_t tem_oob[16] = {0};
+        pkey.action = event->passkey.params.action;
+        for (int i = 0; i < 16; i++) {
+          pkey.oob[i] = tem_oob[i];
+        }
+        rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
+        log_d("BLE_SM_IOACT_OOB; ble_sm_inject_io result: %d", rc);
+      } else if (event->passkey.params.action == BLE_SM_IOACT_INPUT) {
+        log_d("Enter the passkey");
+        pkey.action = event->passkey.params.action;
+
+        // Compatibility only - Do not use, should be removed the in future
+        if (BLEDevice::m_securityCallbacks != nullptr) {
+          pkey.passkey = BLEDevice::m_securityCallbacks->onPassKeyRequest();
+        } else if (server->m_pServerCallbacks != nullptr) {
+          pkey.passkey = server->m_pServerCallbacks->onPassKeyRequest();
+        }
+
+        rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
+        log_d("BLE_SM_IOACT_INPUT; ble_sm_inject_io result: %d", rc);
+
+      } else if (event->passkey.params.action == BLE_SM_IOACT_NONE) {
+        log_d("No passkey action required");
+      }
+
+      log_d("<< handleGATTServerEvent");
+      return 0;
+    }  // BLE_GAP_EVENT_PASSKEY_ACTION
+
+    default: break;
+  }
+
+  log_d("<< handleGATTServerEvent");
+  return 0;
 }
 
 /**
- * @brief Start advertising.
- *
- * Start the server advertising its existence.  This is a convenience function and is equivalent to
- * retrieving the advertising object and invoking start upon it.
+ * @brief Request an Update the connection parameters:
+ * * Can only be used after a connection has been established.
+ * @param [in] conn_handle The connection handle of the peer to send the request to.
+ * @param [in] minInterval The minimum connection interval in 1.25ms units.
+ * @param [in] maxInterval The maximum connection interval in 1.25ms units.
+ * @param [in] latency The number of packets allowed to skip (extends max interval).
+ * @param [in] timeout The timeout time in 10ms units before disconnecting.
  */
-void BLEServer::startAdvertising() {
-  log_v(">> startAdvertising");
-  BLEDevice::startAdvertising();
-  log_v("<< startAdvertising");
-}  // startAdvertising
+void BLEServer::updateConnParams(uint16_t conn_handle, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t timeout) {
+  ble_gap_upd_params params;
+
+  params.latency = latency;
+  params.itvl_max = maxInterval;                        // max_int = 0x20*1.25ms = 40ms
+  params.itvl_min = minInterval;                        // min_int = 0x10*1.25ms = 20ms
+  params.supervision_timeout = timeout;                 // timeout = 400*10ms = 4000ms
+  params.min_ce_len = BLE_GAP_INITIAL_CONN_MIN_CE_LEN;  // Minimum length of connection event in 0.625ms units
+  params.max_ce_len = BLE_GAP_INITIAL_CONN_MAX_CE_LEN;  // Maximum length of connection event in 0.625ms units
+
+  int rc = ble_gap_update_params(conn_handle, &params);
+  if (rc != 0) {
+    log_e("Update params error: %d, %s", rc, BLEUtils::returnCodeToString(rc));
+  }
+}  // updateConnParams
+
+bool BLEServer::setIndicateWait(uint16_t conn_handle) {
+  for (auto i = 0; i < CONFIG_BT_NIMBLE_MAX_CONNECTIONS; i++) {
+    if (m_indWait[i] == conn_handle) {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+void BLEServer::clearIndicateWait(uint16_t conn_handle) {
+  for (auto i = 0; i < CONFIG_BT_NIMBLE_MAX_CONNECTIONS; i++) {
+    if (m_indWait[i] == conn_handle) {
+      m_indWait[i] = BLE_HS_CONN_HANDLE_NONE;
+      return;
+    }
+  }
+}
 
 /**
- * Allow to connect GATT server to peer device
- * Probably can be used in ANCS for iPhone
+ * @brief Disconnect the specified client with optional reason.
+ * @param [in] connId Connection Id of the client to disconnect.
+ * @param [in] reason code for disconnecting.
+ * @return NimBLE host return code.
  */
-bool BLEServer::connect(BLEAddress address) {
-  esp_bd_addr_t addr;
-  memcpy(&addr, address.getNative(), 6);
-  // Perform the open connection request against the target BLE Server.
-  m_semaphoreOpenEvt.take("connect");
-  esp_err_t errRc = ::esp_ble_gatts_open(
-    getGattsIf(),
-    addr,  // address
-    1      // direct connection
-  );
-  if (errRc != ESP_OK) {
-    log_e("esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-    return false;
+int BLEServer::disconnect(uint16_t connId, uint8_t reason) {
+  log_d(">> disconnect()");
+
+  int rc = ble_gap_terminate(connId, reason);
+  if (rc != 0) {
+    log_e("ble_gap_terminate failed: rc=%d %s", rc, BLEUtils::returnCodeToString(rc));
   }
 
-  uint32_t rc = m_semaphoreOpenEvt.wait("connect");  // Wait for the connection to complete.
-  log_v("<< connect(), rc=%d", rc == ESP_GATT_OK);
-  return rc == ESP_GATT_OK;
-}  // connect
+  log_d("<< disconnect()");
+  return rc;
+}  // disconnect
 
-void BLEServerCallbacks::onConnect(BLEServer *pServer) {
-  log_d("BLEServerCallbacks", ">> onConnect(): Default");
-  log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str());
-  log_d("BLEServerCallbacks", "<< onConnect()");
-}  // onConnect
+/**
+ * @brief Set the service changed flag
+ */
+void BLEServer::serviceChanged() {
+  if (m_gattsStarted) {
+    m_svcChanged = true;
+  }
+}  // serviceChanged
 
-void BLEServerCallbacks::onConnect(BLEServer *pServer, esp_ble_gatts_cb_param_t *param) {
+// NimBLE callbacks
+
+void BLEServerCallbacks::onConnect(BLEServer *pServer, struct ble_gap_conn_desc *desc) {
   log_d("BLEServerCallbacks", ">> onConnect(): Default");
   log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str());
   log_d("BLEServerCallbacks", "<< onConnect()");
 }  // onConnect
 
-void BLEServerCallbacks::onDisconnect(BLEServer *pServer) {
+void BLEServerCallbacks::onDisconnect(BLEServer *pServer, struct ble_gap_conn_desc *desc) {
   log_d("BLEServerCallbacks", ">> onDisconnect(): Default");
   log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str());
   log_d("BLEServerCallbacks", "<< onDisconnect()");
 }  // onDisconnect
 
-void BLEServerCallbacks::onDisconnect(BLEServer *pServer, esp_ble_gatts_cb_param_t *param) {
-  log_d("BLEServerCallbacks", ">> onDisconnect(): Default");
-  log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str());
-  log_d("BLEServerCallbacks", "<< onDisconnect()");
-}  // onDisconnect
-
-void BLEServerCallbacks::onMtuChanged(BLEServer *pServer, esp_ble_gatts_cb_param_t *param) {
+void BLEServerCallbacks::onMtuChanged(BLEServer *pServer, ble_gap_conn_desc *desc, uint16_t mtu) {
   log_d("BLEServerCallbacks", ">> onMtuChanged(): Default");
-  log_d("BLEServerCallbacks", "Device: %s MTU: %d", BLEDevice::toString().c_str(), param->mtu.mtu);
+  log_d("BLEServerCallbacks", "Device: %s MTU: %d", BLEDevice::toString().c_str(), mtu);
   log_d("BLEServerCallbacks", "<< onMtuChanged()");
 }  // onMtuChanged
 
-/* multi connect support */
-/* TODO do some more tweaks */
-void BLEServer::updatePeerMTU(uint16_t conn_id, uint16_t mtu) {
-  // set mtu in conn_status_t
-  const std::map<uint16_t, conn_status_t>::iterator it = m_connectedServersMap.find(conn_id);
-  if (it != m_connectedServersMap.end()) {
-    it->second.mtu = mtu;
-    std::swap(m_connectedServersMap[conn_id], it->second);
-  }
+uint32_t BLEServerCallbacks::onPassKeyRequest() {
+  log_d("BLEServerCallbacks", "onPassKeyRequest: default: 123456");
+  return 123456;
 }
 
-std::map<uint16_t, conn_status_t> BLEServer::getPeerDevices(bool _client) {
-  return m_connectedServersMap;
+void BLEServerCallbacks::onAuthenticationComplete(ble_gap_conn_desc *) {
+  log_d("BLEServerCallbacks", "onAuthenticationComplete: default");
 }
 
-uint16_t BLEServer::getPeerMTU(uint16_t conn_id) {
-  return m_connectedServersMap.find(conn_id)->second.mtu;
+bool BLEServerCallbacks::onConfirmPIN(uint32_t pin) {
+  log_d("BLEServerCallbacks", "onConfirmPIN: default: true");
+  return true;
 }
 
-void BLEServer::addPeerDevice(void *peer, bool _client, uint16_t conn_id) {
-  conn_status_t status = {.peer_device = peer, .connected = true, .mtu = 23};
-
-  m_connectedServersMap.insert(std::pair<uint16_t, conn_status_t>(conn_id, status));
-}
-
-bool BLEServer::removePeerDevice(uint16_t conn_id, bool _client) {
-  return m_connectedServersMap.erase(conn_id) > 0;
-}
-/* multi connect support */
-
-/**
- * Update connection parameters can be called only after connection has been established
- */
-void BLEServer::updateConnParams(esp_bd_addr_t remote_bda, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t timeout) {
-  esp_ble_conn_update_params_t conn_params;
-  memcpy(conn_params.bda, remote_bda, sizeof(esp_bd_addr_t));
-  conn_params.latency = latency;
-  conn_params.max_int = maxInterval;  // max_int = 0x20*1.25ms = 40ms
-  conn_params.min_int = minInterval;  // min_int = 0x10*1.25ms = 20ms
-  conn_params.timeout = timeout;      // timeout = 400*10ms = 4000ms
-  esp_ble_gap_update_conn_params(&conn_params);
-}
-
-void BLEServer::disconnect(uint16_t connId) {
-  esp_ble_gatts_close(m_gatts_if, connId);
-}
+#endif  // CONFIG_NIMBLE_ENABLED
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEServer.h b/libraries/BLE/src/BLEServer.h
index aa10f2210fa..865d1046312 100644
--- a/libraries/BLE/src/BLEServer.h
+++ b/libraries/BLE/src/BLEServer.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Apr 16, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLESERVER_H_
@@ -11,13 +15,16 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
-#include <esp_gatts_api.h>
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/*****************************************************************************
+ *                             Common includes                               *
+ *****************************************************************************/
 
 #include <string>
 #include <string.h>
-// #include "BLEDevice.h"
-
+#include "BLEDevice.h"
+#include "BLEConnInfo.h"
 #include "BLEUUID.h"
 #include "BLEAdvertising.h"
 #include "BLECharacteristic.h"
@@ -25,24 +32,51 @@
 #include "BLESecurity.h"
 #include "RTOS.h"
 #include "BLEAddress.h"
+#include "BLEUtils.h"
+#include "BLEUtils.h"
+
+/*****************************************************************************
+ *                            Bluedroid includes                             *
+ *****************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gatts_api.h>
+#endif
+
+/*****************************************************************************
+ *                       NimBLE includes and definitions                     *
+ *****************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_gatt.h>
+#define ESP_GATT_IF_NONE         BLE_HS_CONN_HANDLE_NONE
+#define NIMBLE_ATT_REMOVE_HIDE   1
+#define NIMBLE_ATT_REMOVE_DELETE 2
+#endif
+
+/*****************************************************************************
+ *                           Forward declarations                            *
+ *****************************************************************************/
 
 class BLEServerCallbacks;
-/* TODO possibly refactor this struct */
-typedef struct {
-  void *peer_device;  // peer device BLEClient or BLEServer - maybe its better to have 2 structures or union here
-  bool connected;     // do we need it?
-  uint16_t mtu;       // every peer device negotiate own mtu
-} conn_status_t;
+class BLEService;
+class BLECharacteristic;
+class BLEDevice;
+class BLESecurity;
+class BLEAdvertising;
 
 /**
- * @brief A data structure that manages the %BLE servers owned by a BLE server.
+ * @brief A data structure that manages the %BLE services owned by a BLE server.
  */
 class BLEServiceMap {
 public:
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   BLEService *getByHandle(uint16_t handle);
   BLEService *getByUUID(const char *uuid);
   BLEService *getByUUID(BLEUUID uuid, uint8_t inst_id = 0);
-  void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
   void setByHandle(uint16_t handle, BLEService *service);
   void setByUUID(const char *uuid, BLEService *service);
   void setByUUID(BLEUUID uuid, BLEService *service);
@@ -52,7 +86,19 @@ class BLEServiceMap {
   void removeService(BLEService *service);
   int getRegisteredServiceCount();
 
+  /***************************************************************************
+   *                       Bluedroid public declarations                     *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
+#endif
+
 private:
+  /***************************************************************************
+   *                       Common private properties                         *
+   ***************************************************************************/
+
   std::map<uint16_t, BLEService *> m_handleMap;
   std::map<BLEService *, String> m_uuidMap;
   std::map<BLEService *, String>::iterator m_iterator;
@@ -63,6 +109,16 @@ class BLEServiceMap {
  */
 class BLEServer {
 public:
+  /***************************************************************************
+   *                        Common public properties                         *
+   ***************************************************************************/
+
+  uint16_t m_appId;
+
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   uint32_t getConnectedCount();
   BLEService *createService(const char *uuid);
   BLEService *createService(BLEUUID uuid, uint32_t numHandles = 15, uint8_t inst_id = 0);
@@ -72,12 +128,9 @@ class BLEServer {
   void removeService(BLEService *service);
   BLEService *getServiceByUUID(const char *uuid);
   BLEService *getServiceByUUID(BLEUUID uuid);
-  bool connect(BLEAddress address);
-  void disconnect(uint16_t connId);
-  uint16_t m_appId;
-  void updateConnParams(esp_bd_addr_t remote_bda, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t timeout);
+  void start();
 
-  /* multi connection support */
+  // Connection management functions
   std::map<uint16_t, conn_status_t> getPeerDevices(bool client);
   void addPeerDevice(void *peer, bool is_client, uint16_t conn_id);
   bool removePeerDevice(uint16_t conn_id, bool client);
@@ -86,28 +139,95 @@ class BLEServer {
   uint16_t getPeerMTU(uint16_t conn_id);
   uint16_t getConnId();
 
+  /***************************************************************************
+   *                       Bluedroid public declarations                     *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  bool connect(BLEAddress address);
+  void updateConnParams(esp_bd_addr_t remote_bda, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t timeout);
+  void disconnect(uint16_t connId);
+#endif
+
+  /***************************************************************************
+   *                       NimBLE public declarations                        *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  uint16_t getHandle();
+  void updateConnParams(uint16_t conn_handle, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t timeout);
+  int disconnect(uint16_t connId, uint8_t reason = BLE_ERR_REM_USER_CONN_TERM);
+#endif
+
 private:
-  BLEServer();
   friend class BLEService;
   friend class BLECharacteristic;
   friend class BLEDevice;
-  esp_ble_adv_data_t m_adv_data;
-  // BLEAdvertising      m_bleAdvertising;
+  friend class BLESecurity;
+  friend class BLEAdvertising;
+
+  /***************************************************************************
+   *                       Common private properties                         *
+   ***************************************************************************/
+
   uint16_t m_connId;
   uint32_t m_connectedCount;
-  uint16_t m_gatts_if;
+  bool m_gattsStarted;
   std::map<uint16_t, conn_status_t> m_connectedServersMap;
-
   FreeRTOS::Semaphore m_semaphoreRegisterAppEvt = FreeRTOS::Semaphore("RegisterAppEvt");
   FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt");
   FreeRTOS::Semaphore m_semaphoreOpenEvt = FreeRTOS::Semaphore("OpenEvt");
   BLEServiceMap m_serviceMap;
   BLEServerCallbacks *m_pServerCallbacks = nullptr;
 
+  /***************************************************************************
+   *                       Bluedroid private properties                       *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  uint16_t m_gatts_if;
+  esp_ble_adv_data_t m_adv_data;
+#endif
+
+  /***************************************************************************
+   *                       NimBLE private properties                         *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  bool m_svcChanged;
+  uint16_t m_indWait[CONFIG_BT_NIMBLE_MAX_CONNECTIONS];
+  std::vector<BLECharacteristic *> m_notifyChrVec;
+  ble_hs_adv_fields m_adv_data;
+#endif
+
+  /***************************************************************************
+   *                       Common private declarations                       *
+   ***************************************************************************/
+
+  BLEServer();
   void createApp(uint16_t appId);
+
+  /***************************************************************************
+   *                       Bluedroid private declarations                    *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
   uint16_t getGattsIf();
-  void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
   void registerApp(uint16_t);
+  void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
+#endif
+
+  /***************************************************************************
+   *                       NimBLE private declarations                       *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  void serviceChanged();
+  void resetGATT();
+  bool setIndicateWait(uint16_t conn_handle);
+  void clearIndicateWait(uint16_t conn_handle);
+  static int handleGATTServerEvent(struct ble_gap_event *event, void *arg);
+#endif
 };  // BLEServer
 
 /**
@@ -115,37 +235,38 @@ class BLEServer {
  */
 class BLEServerCallbacks {
 public:
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   virtual ~BLEServerCallbacks(){};
-  /**
-	 * @brief Handle a new client connection.
-	 *
-	 * When a new client connects, we are invoked.
-	 *
-	 * @param [in] pServer A reference to the %BLE server that received the client connection.
-	 */
   virtual void onConnect(BLEServer *pServer);
-  virtual void onConnect(BLEServer *pServer, esp_ble_gatts_cb_param_t *param);
-  /**
-	 * @brief Handle an existing client disconnection.
-	 *
-	 * When an existing client disconnects, we are invoked.
-	 *
-	 * @param [in] pServer A reference to the %BLE server that received the existing client disconnection.
-	 */
   virtual void onDisconnect(BLEServer *pServer);
-  virtual void onDisconnect(BLEServer *pServer, esp_ble_gatts_cb_param_t *param);
 
-  /**
-	 * @brief Handle a new client connection.
-	 *
-	 * When the MTU changes this method is invoked.
-	 *
-	 * @param [in] pServer A reference to the %BLE server that received the client connection.
-	 * @param [in] param A reference to esp_ble_gatts_cb_param_t.
-	 */
+  /***************************************************************************
+   *                       Bluedroid public declarations                     *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  virtual void onConnect(BLEServer *pServer, esp_ble_gatts_cb_param_t *param);
+  virtual void onDisconnect(BLEServer *pServer, esp_ble_gatts_cb_param_t *param);
   virtual void onMtuChanged(BLEServer *pServer, esp_ble_gatts_cb_param_t *param);
+#endif
+
+  /***************************************************************************
+   *                       NimBLE public declarations                        *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  virtual void onConnect(BLEServer *pServer, ble_gap_conn_desc *desc);
+  virtual void onDisconnect(BLEServer *pServer, ble_gap_conn_desc *desc);
+  virtual void onMtuChanged(BLEServer *pServer, ble_gap_conn_desc *desc, uint16_t mtu);
+  virtual uint32_t onPassKeyRequest();
+  virtual void onAuthenticationComplete(ble_gap_conn_desc *desc);
+  virtual bool onConfirmPIN(uint32_t pin);
+#endif
 };  // BLEServerCallbacks
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLESERVER_H_ */
diff --git a/libraries/BLE/src/BLEService.cpp b/libraries/BLE/src/BLEService.cpp
index 58c5d4eb9c3..60449719b6a 100644
--- a/libraries/BLE/src/BLEService.cpp
+++ b/libraries/BLE/src/BLEService.cpp
@@ -3,6 +3,10 @@
  *
  *  Created on: Mar 25, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 // A service is identified by a UUID.  A service is also the container for one or more characteristics.
@@ -11,10 +15,13 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
-#include <esp_err.h>
-#include <esp_gatts_api.h>
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
 
+/*****************************************************************************
+ *                             Common includes                               *
+ *****************************************************************************/
+
+#include <esp_err.h>
 #include <iomanip>
 #include <sstream>
 #include <string>
@@ -25,8 +32,24 @@
 #include "GeneralUtils.h"
 #include "esp32-hal-log.h"
 
+/*****************************************************************************
+ *                            Bluedroid includes                             *
+ *****************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gatts_api.h>
+#endif
+
+/*****************************************************************************
+ *                             Common definitions                            *
+ *****************************************************************************/
+
 #define NULL_HANDLE (0xffff)
 
+/*****************************************************************************
+ *                             Common functions                              *
+ *****************************************************************************/
+
 /**
  * @brief Construct an instance of the BLEService
  * @param [in] uuid The UUID of the service.
@@ -44,10 +67,32 @@ BLEService::BLEService(BLEUUID uuid, uint16_t numHandles) {
   m_handle = NULL_HANDLE;
   m_pServer = nullptr;
   //m_serializeMutex.setName("BLEService");
-  m_lastCreatedCharacteristic = nullptr;
   m_numHandles = numHandles;
+#ifdef CONFIG_BLUEDROID_ENABLED
+  m_lastCreatedCharacteristic = nullptr;
+#endif
+#if defined(CONFIG_NIMBLE_ENABLED)
+  m_pSvcDef = nullptr;
+#endif
 }  // BLEService
 
+BLEService::~BLEService() {
+#if defined(CONFIG_NIMBLE_ENABLED)
+  if (m_pSvcDef != nullptr) {
+    if (m_pSvcDef->characteristics != nullptr) {
+      for (int i = 0; m_pSvcDef->characteristics[i].uuid != NULL; ++i) {
+        if (m_pSvcDef->characteristics[i].descriptors) {
+          delete (m_pSvcDef->characteristics[i].descriptors);
+        }
+      }
+      delete (m_pSvcDef->characteristics);
+    }
+
+    delete (m_pSvcDef);
+  }
+#endif
+}
+
 /**
  * @brief Create the service.
  * Create the service.
@@ -56,8 +101,9 @@ BLEService::BLEService(BLEUUID uuid, uint16_t numHandles) {
  */
 
 void BLEService::executeCreate(BLEServer *pServer) {
-  log_v(">> executeCreate() - Creating service (esp_ble_gatts_create_service) service uuid: %s", getUUID().toString().c_str());
+  log_v(">> executeCreate() - Creating service with uuid: %s", getUUID().toString().c_str());
   m_pServer = pServer;
+#if defined(CONFIG_BLUEDROID_ENABLED)
   m_semaphoreCreateEvt.take("executeCreate");  // Take the mutex and release at event ESP_GATTS_CREATE_EVT
 
   esp_gatt_srvc_id_t srvc_id;
@@ -73,6 +119,7 @@ void BLEService::executeCreate(BLEServer *pServer) {
   }
 
   m_semaphoreCreateEvt.wait("executeCreate");
+#endif
   log_v("<< executeCreate");
 }  // executeCreate
 
@@ -83,6 +130,7 @@ void BLEService::executeCreate(BLEServer *pServer) {
  */
 
 void BLEService::executeDelete() {
+#if defined(CONFIG_BLUEDROID_ENABLED)
   log_v(">> executeDelete()");
   m_semaphoreDeleteEvt.take("executeDelete");  // Take the mutex and release at event ESP_GATTS_DELETE_EVT
 
@@ -95,6 +143,11 @@ void BLEService::executeDelete() {
 
   m_semaphoreDeleteEvt.wait("executeDelete");
   log_v("<< executeDelete");
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED) && CONFIG_BT_NIMBLE_DYNAMIC_SERVICE
+  ble_gatts_delete_svc(&m_uuid.getNative()->u);
+#endif
 }  // executeDelete
 
 /**
@@ -114,49 +167,11 @@ BLEUUID BLEService::getUUID() {
   return m_uuid;
 }  // getUUID
 
-/**
- * @brief Start the service.
- * Here we wish to start the service which means that we will respond to partner requests about it.
- * Starting a service also means that we can create the corresponding characteristics.
- * @return Start the service.
- */
-void BLEService::start() {
-  // We ask the BLE runtime to start the service and then create each of the characteristics.
-  // We start the service through its local handle which was returned in the ESP_GATTS_CREATE_EVT event
-  // obtained as a result of calling esp_ble_gatts_create_service().
-  //
-  log_v(">> start(): Starting service (esp_ble_gatts_start_service): %s", toString().c_str());
-  if (m_handle == NULL_HANDLE) {
-    log_e("<< !!! We attempted to start a service but don't know its handle!");
-    return;
-  }
-
-  BLECharacteristic *pCharacteristic = m_characteristicMap.getFirst();
-
-  while (pCharacteristic != nullptr) {
-    m_lastCreatedCharacteristic = pCharacteristic;
-    pCharacteristic->executeCreate(this);
-
-    pCharacteristic = m_characteristicMap.getNext();
-  }
-  // Start each of the characteristics ... these are found in the m_characteristicMap.
-
-  m_semaphoreStartEvt.take("start");
-  esp_err_t errRc = ::esp_ble_gatts_start_service(m_handle);
-
-  if (errRc != ESP_OK) {
-    log_e("<< esp_ble_gatts_start_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
-    return;
-  }
-  m_semaphoreStartEvt.wait("start");
-
-  log_v("<< start()");
-}  // start
-
 /**
  * @brief Stop the service.
  */
 void BLEService::stop() {
+#if defined(CONFIG_BLUEDROID_ENABLED)
   // We ask the BLE runtime to start the service and then create each of the characteristics.
   // We start the service through its local handle which was returned in the ESP_GATTS_CREATE_EVT event
   // obtained as a result of calling esp_ble_gatts_create_service().
@@ -176,13 +191,19 @@ void BLEService::stop() {
   m_semaphoreStopEvt.wait("stop");
 
   log_v("<< stop()");
-}  // start
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  log_w("NimBLE does not support stopping a service. Ignoring request.");
+#endif
+}  // stop
 
 /**
  * @brief Set the handle associated with this service.
  * @param [in] handle The handle associated with the service.
  */
 void BLEService::setHandle(uint16_t handle) {
+#if defined(CONFIG_BLUEDROID_ENABLED)
   log_v(">> setHandle - Handle=0x%.2x, service UUID=%s)", handle, getUUID().toString().c_str());
   if (m_handle != NULL_HANDLE) {
     log_e("!!! Handle is already set %.2x", m_handle);
@@ -190,6 +211,11 @@ void BLEService::setHandle(uint16_t handle) {
   }
   m_handle = handle;
   log_v("<< setHandle");
+#endif
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  log_w("NimBLE does not support manually setting the handle of a service. Ignoring request.");
+#endif
 }  // setHandle
 
 /**
@@ -213,14 +239,25 @@ void BLEService::addCharacteristic(BLECharacteristic *pCharacteristic) {
   log_d("Adding characteristic: uuid=%s to service: %s", pCharacteristic->getUUID().toString().c_str(), toString().c_str());
 
   // Check that we don't add the same characteristic twice.
-  if (m_characteristicMap.getByUUID(pCharacteristic->getUUID()) != nullptr) {
+  BLECharacteristic *pExisting = m_characteristicMap.getByUUID(pCharacteristic->getUUID());
+  if (pExisting != nullptr) {
     log_w("<< Adding a new characteristic with the same UUID as a previous one");
-    //return;
   }
 
-  // Remember this characteristic in our map of characteristics.  At this point, we can lookup by UUID
-  // but not by handle.  The handle is allocated to us on the ESP_GATTS_ADD_CHAR_EVT.
-  m_characteristicMap.setByUUID(pCharacteristic, pCharacteristic->getUUID());
+#if defined(CONFIG_NIMBLE_ENABLED)
+  if (pExisting != nullptr) {
+    pExisting->m_removed = 0;
+  } else
+#endif
+  {
+    // Remember this characteristic in our map of characteristics.  At this point, we can lookup by UUID
+    // but not by handle.  The handle is allocated to us on the ESP_GATTS_ADD_CHAR_EVT.
+    m_characteristicMap.setByUUID(pCharacteristic, pCharacteristic->getUUID());
+  }
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  getServer()->serviceChanged();
+#endif
 
   log_v("<< addCharacteristic()");
 }  // addCharacteristic
@@ -247,6 +284,54 @@ BLECharacteristic *BLEService::createCharacteristic(BLEUUID uuid, uint32_t prope
   return pCharacteristic;
 }  // createCharacteristic
 
+BLECharacteristic *BLEService::getCharacteristic(const char *uuid) {
+  return getCharacteristic(BLEUUID(uuid));
+}
+
+BLECharacteristic *BLEService::getCharacteristic(BLEUUID uuid) {
+  return m_characteristicMap.getByUUID(uuid);
+}
+
+/**
+ * @brief Return a string representation of this service.
+ * A service is defined by:
+ * * Its UUID
+ * * Its handle
+ * @return A string representation of this service.
+ */
+String BLEService::toString() {
+  String res = "UUID: " + getUUID().toString();
+  char hex[5];
+  snprintf(hex, sizeof(hex), "%04x", getHandle());
+  res += ", handle: 0x";
+  res += hex;
+  return res;
+}  // toString
+
+/**
+ * @brief Get the BLE server associated with this service.
+ * @return The BLEServer associated with this service.
+ */
+BLEServer *BLEService::getServer() {
+  return m_pServer;
+}  // getServer
+
+/*****************************************************************************
+ *                            Bluedroid functions                            *
+ *****************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+/**
+ * @brief Get the last created characteristic.
+ * It is lamentable that this function has to exist.  It returns the last created characteristic.
+ * We need this because the descriptor API is built around the notion that a new descriptor, when created,
+ * is associated with the last characteristics created and we need that information.
+ * @return The last created characteristic.
+ */
+BLECharacteristic *BLEService::getLastCreatedCharacteristic() {
+  return m_lastCreatedCharacteristic;
+}  // getLastCreatedCharacteristic
+
 /**
  * @brief Handle a GATTS server event.
  */
@@ -347,48 +432,222 @@ void BLEService::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t
   m_characteristicMap.handleGATTServerEvent(event, gatts_if, param);
 }  // handleGATTServerEvent
 
-BLECharacteristic *BLEService::getCharacteristic(const char *uuid) {
-  return getCharacteristic(BLEUUID(uuid));
-}
-
-BLECharacteristic *BLEService::getCharacteristic(BLEUUID uuid) {
-  return m_characteristicMap.getByUUID(uuid);
-}
-
 /**
- * @brief Return a string representation of this service.
- * A service is defined by:
- * * Its UUID
- * * Its handle
- * @return A string representation of this service.
+ * @brief Start the service.
+ * Here we wish to start the service which means that we will respond to partner requests about it.
+ * Starting a service also means that we can create the corresponding characteristics.
+ * @return Start the service.
  */
-String BLEService::toString() {
-  String res = "UUID: " + getUUID().toString();
-  char hex[5];
-  snprintf(hex, sizeof(hex), "%04x", getHandle());
-  res += ", handle: 0x";
-  res += hex;
-  return res;
-}  // toString
 
+bool BLEService::start() {
+  // We ask the BLE runtime to start the service and then create each of the characteristics.
+  // We start the service through its local handle which was returned in the ESP_GATTS_CREATE_EVT event
+  // obtained as a result of calling esp_ble_gatts_create_service().
+  //
+  log_v(">> start(): Starting service (esp_ble_gatts_start_service): %s", toString().c_str());
+  if (m_handle == NULL_HANDLE) {
+    log_e("<< !!! We attempted to start a service but don't know its handle!");
+    return false;
+  }
+
+  BLECharacteristic *pCharacteristic = m_characteristicMap.getFirst();
+
+  while (pCharacteristic != nullptr) {
+    m_lastCreatedCharacteristic = pCharacteristic;
+    pCharacteristic->executeCreate(this);
+
+    pCharacteristic = m_characteristicMap.getNext();
+  }
+  // Start each of the characteristics ... these are found in the m_characteristicMap.
+
+  m_semaphoreStartEvt.take("start");
+  esp_err_t errRc = ::esp_ble_gatts_start_service(m_handle);
+
+  if (errRc != ESP_OK) {
+    log_e("<< esp_ble_gatts_start_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc));
+    return false;
+  }
+  m_semaphoreStartEvt.wait("start");
+
+  log_v("<< start()");
+  return true;
+}  // start
+
+#endif  // CONFIG_BLUEDROID_ENABLED
+
+/*****************************************************************************
+ *                             NimBLE functions                              *
+ *****************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
 /**
- * @brief Get the last created characteristic.
- * It is lamentable that this function has to exist.  It returns the last created characteristic.
- * We need this because the descriptor API is built around the notion that a new descriptor, when created,
- * is associated with the last characteristics created and we need that information.
- * @return The last created characteristic.
+ * @brief Remove a characteristic from the service. Check if the characteristic was already removed and if so, check if this
+ * is being called to delete the object and do so if requested. Otherwise, ignore the call and return.
+ * @param [in] pCharacteristic - The characteristic to remove.
+ * @param [in] deleteChr - If true, delete the characteristic.
  */
-BLECharacteristic *BLEService::getLastCreatedCharacteristic() {
-  return m_lastCreatedCharacteristic;
-}  // getLastCreatedCharacteristic
+void BLEService::removeCharacteristic(BLECharacteristic *pCharacteristic, bool deleteChr) {
+  if (pCharacteristic->m_removed > 0) {
+    if (deleteChr) {
+      BLECharacteristic *pExisting = m_characteristicMap.getByUUID(pCharacteristic->getUUID());
+      if (pExisting != nullptr) {
+        m_characteristicMap.removeCharacteristic(pExisting);
+        delete pExisting;
+      }
+    }
+
+    return;
+  }
+
+  pCharacteristic->m_removed = deleteChr ? NIMBLE_ATT_REMOVE_DELETE : NIMBLE_ATT_REMOVE_HIDE;
+  getServer()->serviceChanged();
+}
 
 /**
- * @brief Get the BLE server associated with this service.
- * @return The BLEServer associated with this service.
+ * @brief Builds the database of characteristics/descriptors for the service
+ * and registers it with the NimBLE stack.
+ * @return bool success/failure .
  */
-BLEServer *BLEService::getServer() {
-  return m_pServer;
-}  // getServer
+bool BLEService::start() {
+  log_d(">> start(): Starting service: %s", toString().c_str());
+
+  // Rebuild the service definition if the server attributes have changed.
+  if (getServer()->m_svcChanged && m_pSvcDef != nullptr) {
+    if (m_pSvcDef[0].characteristics) {
+      if (m_pSvcDef[0].characteristics[0].descriptors) {
+        delete (m_pSvcDef[0].characteristics[0].descriptors);
+      }
+      delete (m_pSvcDef[0].characteristics);
+    }
+    delete (m_pSvcDef);
+    m_pSvcDef = nullptr;
+  }
+
+  if (m_pSvcDef == nullptr) {
+    // Nimble requires an array of services to be sent to the api
+    // Since we are adding 1 at a time we create an array of 2 and set the type
+    // of the second service to 0 to indicate the end of the array.
+    ble_gatt_svc_def *svc = new ble_gatt_svc_def[2]{};
+    ble_gatt_chr_def *pChr_a = nullptr;
+    ble_gatt_dsc_def *pDsc_a = nullptr;
+
+    svc[0].type = BLE_GATT_SVC_TYPE_PRIMARY;
+    svc[0].uuid = (const ble_uuid_t *)&(m_uuid.getNative()->u);
+    svc[0].includes = nullptr;
+
+    int removedCount = 0;
+    BLECharacteristic *pCharacteristic;
+
+    pCharacteristic = m_characteristicMap.getFirst();
+    while (pCharacteristic != nullptr) {
+      if (pCharacteristic->m_removed > 0) {
+        if (pCharacteristic->m_removed == NIMBLE_ATT_REMOVE_DELETE) {
+          m_characteristicMap.removeCharacteristic(pCharacteristic);
+          delete pCharacteristic;
+        } else {
+          ++removedCount;
+        }
+      } else {
+        pCharacteristic->executeCreate(this);
+      }
+
+      pCharacteristic = m_characteristicMap.getNext();
+    }
+
+    size_t numChrs = m_characteristicMap.getRegisteredCharacteristicCount() - removedCount;
+    log_d("Adding %d characteristics for service %s", numChrs, toString().c_str());
+
+    if (!numChrs) {
+      svc[0].characteristics = nullptr;
+    } else {
+      // Nimble requires the last characteristic to have it's uuid = 0 to indicate the end
+      // of the characteristics for the service. We create 1 extra and set it to null
+      // for this purpose.
+      pChr_a = new ble_gatt_chr_def[numChrs + 1]{};
+      uint8_t i = 0;
+      pCharacteristic = m_characteristicMap.getFirst();
+      while (pCharacteristic != nullptr) {
+        if (pCharacteristic->m_removed <= 0) {
+          removedCount = 0;
+          BLEDescriptor *pDescriptor;
+
+          pDescriptor = pCharacteristic->m_descriptorMap.getFirst();
+          while (pDescriptor != nullptr) {
+            if (pDescriptor->m_removed > 0) {
+              if (pDescriptor->m_removed == NIMBLE_ATT_REMOVE_DELETE) {
+                pCharacteristic->m_descriptorMap.removeDescriptor(pDescriptor);
+                delete pDescriptor;
+              } else {
+                ++removedCount;
+              }
+            }
+            pDescriptor = pCharacteristic->m_descriptorMap.getNext();
+          }
+
+          size_t numDscs = pCharacteristic->m_descriptorMap.getRegisteredDescriptorCount() - removedCount;
+          log_d("Adding %d descriptors for characteristic %s", numDscs, pCharacteristic->getUUID().toString().c_str());
+
+          if (!numDscs) {
+            pChr_a[i].descriptors = nullptr;
+          } else {
+            // Must have last descriptor uuid = 0 so we have to create 1 extra
+            pDsc_a = new ble_gatt_dsc_def[numDscs + 1]{};
+            uint8_t d = 0;
+            pDescriptor = pCharacteristic->m_descriptorMap.getFirst();
+            while (pDescriptor != nullptr) {
+              if (pDescriptor->m_removed <= 0) {
+                pDsc_a[d].uuid = (const ble_uuid_t *)&(pDescriptor->m_bleUUID.getNative()->u);
+                pDsc_a[d].att_flags = pDescriptor->m_permissions;
+                pDsc_a[d].min_key_size = 0;
+                pDsc_a[d].access_cb = BLEDescriptor::handleGATTServerEvent;
+                pDsc_a[d].arg = pDescriptor;
+                ++d;
+              }
+              pDescriptor = pCharacteristic->m_descriptorMap.getNext();
+            }
+
+            pDsc_a[numDscs].uuid = nullptr;
+            pChr_a[i].descriptors = pDsc_a;
+          }
+
+          pChr_a[i].uuid = (const ble_uuid_t *)&(pCharacteristic->m_bleUUID.getNative()->u);
+          pChr_a[i].access_cb = BLECharacteristic::handleGATTServerEvent;
+          pChr_a[i].arg = pCharacteristic;
+          pChr_a[i].flags = pCharacteristic->m_properties;
+          pChr_a[i].min_key_size = 0;
+          pChr_a[i].val_handle = &pCharacteristic->m_handle;
+          ++i;
+        }
+
+        pCharacteristic = m_characteristicMap.getNext();
+      }
+
+      pChr_a[numChrs].uuid = nullptr;
+      svc[0].characteristics = pChr_a;
+    }
+
+    // end of services must indicate to api with type = 0
+    svc[1].type = 0;
+    m_pSvcDef = svc;
+  }
+
+  int rc = ble_gatts_count_cfg((const ble_gatt_svc_def *)m_pSvcDef);
+  if (rc != 0) {
+    log_e("ble_gatts_count_cfg failed, rc= %d, %s", rc, BLEUtils::returnCodeToString(rc));
+    return false;
+  }
+
+  rc = ble_gatts_add_svcs((const ble_gatt_svc_def *)m_pSvcDef);
+  if (rc != 0) {
+    log_e("ble_gatts_add_svcs, rc= %d, %s", rc, BLEUtils::returnCodeToString(rc));
+    return false;
+  }
+
+  log_d("<< start()");
+  return true;
+}  // start
+
+#endif
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEService.h b/libraries/BLE/src/BLEService.h
index 61f867b2a02..67088b60310 100644
--- a/libraries/BLE/src/BLEService.h
+++ b/libraries/BLE/src/BLEService.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Mar 25, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLESERVICE_H_
@@ -11,15 +15,38 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
 
-#include <esp_gatts_api.h>
+/*****************************************************************************
+ *                             Common includes                               *
+ *****************************************************************************/
 
 #include "BLECharacteristic.h"
 #include "BLEServer.h"
 #include "BLEUUID.h"
+#include "BLEUtils.h"
 #include "RTOS.h"
 
+/*****************************************************************************
+ *                          Bluedroid includes                               *
+ *****************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gatts_api.h>
+#endif
+
+/*****************************************************************************
+ *                            NimBLE includes                                *
+ *****************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_gatt.h>
+#endif
+
+/*****************************************************************************
+ *                          Forward declarations                             *
+ *****************************************************************************/
+
 class BLEServer;
 
 /**
@@ -27,6 +54,10 @@ class BLEServer;
  */
 class BLECharacteristicMap {
 public:
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   void setByUUID(BLECharacteristic *pCharacteristic, const char *uuid);
   void setByUUID(BLECharacteristic *pCharacteristic, BLEUUID uuid);
   void setByHandle(uint16_t handle, BLECharacteristic *pCharacteristic);
@@ -36,9 +67,30 @@ class BLECharacteristicMap {
   BLECharacteristic *getFirst();
   BLECharacteristic *getNext();
   String toString();
+  int getRegisteredCharacteristicCount();
+  void removeCharacteristic(BLECharacteristic *characteristic);
+
+  /***************************************************************************
+   *                      Bluedroid public declarations                      *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
   void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
+#endif
+
+  /***************************************************************************
+   *                        NimBLE public declarations                       *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  void handleGATTServerEvent(uint16_t conn_handle, uint16_t attr_handle, ble_gatt_access_ctxt *ctxt, void *arg);
+#endif
 
 private:
+  /***************************************************************************
+   *                        Common private properties                        *
+   ***************************************************************************/
+
   std::map<BLECharacteristic *, String> m_uuidMap;
   std::map<uint16_t, BLECharacteristic *> m_handleMap;
   std::map<BLECharacteristic *, String>::iterator m_iterator;
@@ -46,10 +98,19 @@ class BLECharacteristicMap {
 
 /**
  * @brief The model of a %BLE service.
- *
  */
 class BLEService {
 public:
+  /***************************************************************************
+   *                            Common properties                            *
+   ***************************************************************************/
+
+  uint8_t m_instId = 0;
+
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   void addCharacteristic(BLECharacteristic *pCharacteristic);
   BLECharacteristic *createCharacteristic(const char *uuid, uint32_t properties);
   BLECharacteristic *createCharacteristic(BLEUUID uuid, uint32_t properties);
@@ -60,40 +121,81 @@ class BLEService {
   BLECharacteristic *getCharacteristic(BLEUUID uuid);
   BLEUUID getUUID();
   BLEServer *getServer();
-  void start();
+  bool start();
   void stop();
   String toString();
   uint16_t getHandle();
-  uint8_t m_instId = 0;
+
+  /***************************************************************************
+   *                       NimBLE public declarations                        *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  void removeCharacteristic(BLECharacteristic *pCharacteristic, bool deleteChr = false);
+#endif
 
 private:
-  BLEService(const char *uuid, uint16_t numHandles);
-  BLEService(BLEUUID uuid, uint16_t numHandles);
   friend class BLEServer;
   friend class BLEServiceMap;
   friend class BLEDescriptor;
   friend class BLECharacteristic;
   friend class BLEDevice;
 
+  /***************************************************************************
+   *                         Common private properties                       *
+   ***************************************************************************/
+
   BLECharacteristicMap m_characteristicMap;
   uint16_t m_handle;
   BLECharacteristic *m_lastCreatedCharacteristic = nullptr;
   BLEServer *m_pServer = nullptr;
   BLEUUID m_uuid;
+  FreeRTOS::Semaphore m_semaphoreStartEvt = FreeRTOS::Semaphore("StartEvt");
+  uint16_t m_numHandles;
+
+  /***************************************************************************
+   *                       Bluedroid private properties                      *
+   ***************************************************************************/
 
+#if defined(CONFIG_BLUEDROID_ENABLED)
   FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt");
   FreeRTOS::Semaphore m_semaphoreDeleteEvt = FreeRTOS::Semaphore("DeleteEvt");
-  FreeRTOS::Semaphore m_semaphoreStartEvt = FreeRTOS::Semaphore("StartEvt");
   FreeRTOS::Semaphore m_semaphoreStopEvt = FreeRTOS::Semaphore("StopEvt");
+#endif
 
-  uint16_t m_numHandles;
+  /***************************************************************************
+   *                       NimBLE private properties                         *
+   ***************************************************************************/
 
+#if defined(CONFIG_NIMBLE_ENABLED)
+  uint8_t m_removed;
+  ble_gatt_svc_def *m_pSvcDef;
+#endif
+
+  /***************************************************************************
+   *                       Common private declarations                       *
+   ***************************************************************************/
+
+  BLEService(const char *uuid, uint16_t numHandles);
+  BLEService(BLEUUID uuid, uint16_t numHandles);
+  ~BLEService();
+
+  /***************************************************************************
+   *                       Common private declarations                       *
+   ***************************************************************************/
+
+  void setHandle(uint16_t handle);
+
+  /***************************************************************************
+   *                     Bluedroid private declarations                      *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
   BLECharacteristic *getLastCreatedCharacteristic();
   void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
-  void setHandle(uint16_t handle);
-  //void               setService(esp_gatt_srvc_id_t srvc_id);
+#endif
 };  // BLEService
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLESERVICE_H_ */
diff --git a/libraries/BLE/src/BLEServiceMap.cpp b/libraries/BLE/src/BLEServiceMap.cpp
index 30a9db499f1..477da5b4cc2 100644
--- a/libraries/BLE/src/BLEServiceMap.cpp
+++ b/libraries/BLE/src/BLEServiceMap.cpp
@@ -3,16 +3,30 @@
  *
  *  Created on: Jun 22, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/*****************************************************************************
+ *                             Common includes                               *
+ *****************************************************************************/
+
 #include <stdio.h>
 #include <iomanip>
 #include "BLEService.h"
 
+/*****************************************************************************
+ *                             Common functions                              *
+ *****************************************************************************/
+
 /**
  * @brief Return the service by UUID.
  * @param [in] UUID The UUID to look up the service.
@@ -82,13 +96,6 @@ String BLEServiceMap::toString() {
   return res;
 }  // toString
 
-void BLEServiceMap::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) {
-  // Invoke the handler for every Service we have.
-  for (auto &myPair : m_uuidMap) {
-    myPair.first->handleGATTServerEvent(event, gatts_if, param);
-  }
-}
-
 /**
  * @brief Get the first service in the map.
  * @return The first service in the map.
@@ -130,8 +137,21 @@ void BLEServiceMap::removeService(BLEService *service) {
  * @return amount of registered services
  */
 int BLEServiceMap::getRegisteredServiceCount() {
-  return m_handleMap.size();
+  return m_uuidMap.size();
+}
+
+/*****************************************************************************
+ *                            Bluedroid functions                            *
+ *****************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+void BLEServiceMap::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param) {
+  // Invoke the handler for every Service we have.
+  for (auto &myPair : m_uuidMap) {
+    myPair.first->handleGATTServerEvent(event, gatts_if, param);
+  }
 }
+#endif
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEUUID.cpp b/libraries/BLE/src/BLEUUID.cpp
index 8074ea82f8f..d61fb695799 100644
--- a/libraries/BLE/src/BLEUUID.cpp
+++ b/libraries/BLE/src/BLEUUID.cpp
@@ -3,12 +3,22 @@
  *
  *  Created on: Jun 21, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/*****************************************************************************
+ *                             Common includes                               *
+ *****************************************************************************/
+
 #include <string.h>
 #include <sstream>
 #include <iomanip>
@@ -18,25 +28,10 @@
 #include "BLEUUID.h"
 #include "esp32-hal-log.h"
 
-/**
- * @brief Copy memory from source to target but in reverse order.
- *
- * When we move memory from one location it is normally:
- *
- * ```
- * [0][1][2]...[n] -> [0][1][2]...[n]
- * ```
- *
- * with this function, it is:
- *
- * ```
- * [0][1][2]...[n] -> [n][n-1][n-2]...[0]
- * ```
- *
- * @param [in] target The target of the copy
- * @param [in] source The source of the copy
- * @param [in] size The number of bytes to copy
- */
+/*****************************************************************************
+ *                             Common functions                              *
+ *****************************************************************************/
+
 static void memrcpy(uint8_t *target, uint8_t *source, uint32_t size) {
   assert(size > 0);
   target += (size - 1);  // Point target to the last byte of the target data
@@ -48,29 +43,15 @@ static void memrcpy(uint8_t *target, uint8_t *source, uint32_t size) {
   }
 }  // memrcpy
 
-/**
- * @brief Create a UUID from a string.
- *
- * Create a UUID from a string.  There will be two possible stories here.  Either the string represents
- * a binary data field or the string represents a hex encoding of a UUID.
- * For the hex encoding, here is an example:
- *
- * ```
- * "beb5483e-36e1-4688-b7f5-ea07361b26a8"
- *  0 1 2 3  4 5  6 7  8 9  0 1 2 3 4 5
- *  12345678-90ab-cdef-1234-567890abcdef
- * ```
- *
- * This has a length of 36 characters.  We need to parse this into 16 bytes.
- *
- * @param [in] value The string to build a UUID from.
- */
+BLEUUID::BLEUUID() {
+  m_valueSet = false;
+}  // BLEUUID
+
 BLEUUID::BLEUUID(String value) {
-  //Serial.printf("BLEUUID constructor from String=\"%s\"\n", value.c_str());
   m_valueSet = true;
   if (value.length() == 4) {
-    m_uuid.len = ESP_UUID_LEN_16;
-    m_uuid.uuid.uuid16 = 0;
+    UUID_LEN(m_uuid) = BLE_UUID_16_BITS;
+    UUID_VAL_16(m_uuid) = 0;
     for (int i = 0; i < value.length();) {
       uint8_t MSB = value.c_str()[i];
       uint8_t LSB = value.c_str()[i + 1];
@@ -81,12 +62,12 @@ BLEUUID::BLEUUID(String value) {
       if (LSB > '9') {
         LSB -= 7;
       }
-      m_uuid.uuid.uuid16 += (((MSB & 0x0F) << 4) | (LSB & 0x0F)) << (2 - i) * 4;
+      UUID_VAL_16(m_uuid) += (((MSB & 0x0F) << 4) | (LSB & 0x0F)) << (2 - i) * 4;
       i += 2;
     }
   } else if (value.length() == 8) {
-    m_uuid.len = ESP_UUID_LEN_32;
-    m_uuid.uuid.uuid32 = 0;
+    UUID_LEN(m_uuid) = BLE_UUID_32_BITS;
+    UUID_VAL_32(m_uuid) = 0;
     for (int i = 0; i < value.length();) {
       uint8_t MSB = value.c_str()[i];
       uint8_t LSB = value.c_str()[i + 1];
@@ -97,18 +78,14 @@ BLEUUID::BLEUUID(String value) {
       if (LSB > '9') {
         LSB -= 7;
       }
-      m_uuid.uuid.uuid32 += (((MSB & 0x0F) << 4) | (LSB & 0x0F)) << (6 - i) * 4;
+      UUID_VAL_32(m_uuid) += (((MSB & 0x0F) << 4) | (LSB & 0x0F)) << (6 - i) * 4;
       i += 2;
     }
-  } else if (value.length()
-             == 16) {  // How we can have 16 byte length string representing 128 bit uuid??? needs to be investigated (lack of time) - maybe raw data encoded as String (128b==16B)?
-    m_uuid.len = ESP_UUID_LEN_128;
-    memrcpy(m_uuid.uuid.uuid128, (uint8_t *)value.c_str(), 16);
+  } else if (value.length() == 16) {
+    UUID_LEN(m_uuid) = BLE_UUID_128_BITS;
+    memrcpy(UUID_VAL_128(m_uuid), (uint8_t *)value.c_str(), 16);
   } else if (value.length() == 36) {
-    //log_d("36 characters:");
-    // If the length of the string is 36 bytes then we will assume it is a long hex string in
-    // UUID format.
-    m_uuid.len = ESP_UUID_LEN_128;
+    UUID_LEN(m_uuid) = BLE_UUID_128_BITS;
     int n = 0;
     for (int i = 0; i < value.length();) {
       if (value.c_str()[i] == '-') {
@@ -123,7 +100,7 @@ BLEUUID::BLEUUID(String value) {
       if (LSB > '9') {
         LSB -= 7;
       }
-      m_uuid.uuid.uuid128[15 - n++] = ((MSB & 0x0F) << 4) | (LSB & 0x0F);
+      UUID_VAL_128(m_uuid)[15 - n++] = ((MSB & 0x0F) << 4) | (LSB & 0x0F);
       i += 2;
     }
   } else {
@@ -132,128 +109,73 @@ BLEUUID::BLEUUID(String value) {
   }
 }  //BLEUUID(String)
 
-/*
-BLEUUID::BLEUUID(String value) {
-	this.BLEUUID(String(value.c_str(), value.length()));
-} //BLEUUID(String)
-*/
-
-/**
- * @brief Create a UUID from 16 bytes of memory.
- *
- * @param [in] pData The pointer to the start of the UUID.
- * @param [in] size The size of the data.
- * @param [in] msbFirst Is the MSB first in pData memory?
- */
 BLEUUID::BLEUUID(uint8_t *pData, size_t size, bool msbFirst) {
   if (size != 16) {
     log_e("ERROR: UUID length not 16 bytes");
     return;
   }
-  m_uuid.len = ESP_UUID_LEN_128;
+  UUID_LEN(m_uuid) = BLE_UUID_128_BITS;
   if (msbFirst) {
-    memrcpy(m_uuid.uuid.uuid128, pData, 16);
+    memrcpy(UUID_VAL_128(m_uuid), pData, 16);
   } else {
-    memcpy(m_uuid.uuid.uuid128, pData, 16);
+    memcpy(UUID_VAL_128(m_uuid), pData, 16);
   }
   m_valueSet = true;
 }  // BLEUUID
 
-/**
- * @brief Create a UUID from the 16bit value.
- *
- * @param [in] uuid The 16bit short form UUID.
- */
 BLEUUID::BLEUUID(uint16_t uuid) {
-  m_uuid.len = ESP_UUID_LEN_16;
-  m_uuid.uuid.uuid16 = uuid;
+  UUID_LEN(m_uuid) = BLE_UUID_16_BITS;
+  UUID_VAL_16(m_uuid) = uuid;
   m_valueSet = true;
 }  // BLEUUID
 
-/**
- * @brief Create a UUID from the 32bit value.
- *
- * @param [in] uuid The 32bit short form UUID.
- */
 BLEUUID::BLEUUID(uint32_t uuid) {
-  m_uuid.len = ESP_UUID_LEN_32;
-  m_uuid.uuid.uuid32 = uuid;
+  UUID_LEN(m_uuid) = BLE_UUID_32_BITS;
+  UUID_VAL_32(m_uuid) = uuid;
   m_valueSet = true;
 }  // BLEUUID
 
-/**
- * @brief Create a UUID from the native UUID.
- *
- * @param [in] uuid The native UUID.
- */
-BLEUUID::BLEUUID(esp_bt_uuid_t uuid) {
-  m_uuid = uuid;
+BLEUUID::BLEUUID(uint32_t first, uint16_t second, uint16_t third, uint64_t fourth) {
+  UUID_LEN(m_uuid) = BLE_UUID_128_BITS;
+  memcpy(UUID_VAL_128(m_uuid) + 12, &first, 4);
+  memcpy(UUID_VAL_128(m_uuid) + 10, &second, 2);
+  memcpy(UUID_VAL_128(m_uuid) + 8, &third, 2);
+  memcpy(UUID_VAL_128(m_uuid), &fourth, 8);
   m_valueSet = true;
-}  // BLEUUID
-
-/**
- * @brief Create a UUID from the ESP32 esp_gat_id_t.
- *
- * @param [in] gattId The data to create the UUID from.
- */
-BLEUUID::BLEUUID(esp_gatt_id_t gattId) : BLEUUID(gattId.uuid) {}  // BLEUUID
-
-BLEUUID::BLEUUID() {
-  m_valueSet = false;
-}  // BLEUUID
+}
 
-/**
- * @brief Get the number of bits in this uuid.
- * @return The number of bits in the UUID.  One of 16, 32 or 128.
- */
 uint8_t BLEUUID::bitSize() {
   if (!m_valueSet) {
     return 0;
   }
-  switch (m_uuid.len) {
-    case ESP_UUID_LEN_16:  return 16;
-    case ESP_UUID_LEN_32:  return 32;
-    case ESP_UUID_LEN_128: return 128;
-    default:               log_e("Unknown UUID length: %d", m_uuid.len); return 0;
+  switch (UUID_LEN(m_uuid)) {
+    case BLE_UUID_16_BITS:  return 16;
+    case BLE_UUID_32_BITS:  return 32;
+    case BLE_UUID_128_BITS: return 128;
+    default:                log_e("Unknown UUID length: %d", UUID_LEN(m_uuid)); return 0;
   }  // End of switch
 }  // bitSize
 
-/**
- * @brief Compare a UUID against this UUID.
- *
- * @param [in] uuid The UUID to compare against.
- * @return True if the UUIDs are equal and false otherwise.
- */
-bool BLEUUID::equals(BLEUUID uuid) {
-  //log_d("Comparing: %s to %s", toString().c_str(), uuid.toString().c_str());
+bool BLEUUID::equals(const BLEUUID &uuid) const {
   if (!m_valueSet || !uuid.m_valueSet) {
     return false;
   }
 
-  if (uuid.m_uuid.len != m_uuid.len) {
+  if (UUID_LEN(uuid.m_uuid) != UUID_LEN(m_uuid)) {
     return uuid.toString() == toString();
   }
 
-  if (uuid.m_uuid.len == ESP_UUID_LEN_16) {
-    return uuid.m_uuid.uuid.uuid16 == m_uuid.uuid.uuid16;
+  if (UUID_LEN(uuid.m_uuid) == BLE_UUID_16_BITS) {
+    return UUID_VAL_16(uuid.m_uuid) == UUID_VAL_16(m_uuid);
   }
 
-  if (uuid.m_uuid.len == ESP_UUID_LEN_32) {
-    return uuid.m_uuid.uuid.uuid32 == m_uuid.uuid.uuid32;
+  if (UUID_LEN(uuid.m_uuid) == BLE_UUID_32_BITS) {
+    return UUID_VAL_32(uuid.m_uuid) == UUID_VAL_32(m_uuid);
   }
 
-  return memcmp(uuid.m_uuid.uuid.uuid128, m_uuid.uuid.uuid128, 16) == 0;
+  return memcmp(UUID_VAL_128(uuid.m_uuid), UUID_VAL_128(m_uuid), 16) == 0;
 }  // equals
 
-/**
- * Create a BLEUUID from a string of the form:
- * 0xNNNN
- * 0xNNNNNNNN
- * 0x<UUID>
- * NNNN
- * NNNNNNNN
- * <UUID>
- */
 BLEUUID BLEUUID::fromString(String _uuid) {
   uint8_t start = 0;
   if (strstr(_uuid.c_str(), "0x") != nullptr) {  // If the string starts with 0x, skip those characters.
@@ -273,117 +195,142 @@ BLEUUID BLEUUID::fromString(String _uuid) {
   return BLEUUID();
 }  // fromString
 
-/**
- * @brief Get the native UUID value.
- *
- * @return The native UUID value or NULL if not set.
- */
-esp_bt_uuid_t *BLEUUID::getNative() {
-  //log_d(">> getNative()")
-  if (m_valueSet == false) {
-    log_v("<< Return of un-initialized UUID!");
-    return nullptr;
-  }
-  //log_d("<< getNative()");
-  return &m_uuid;
-}  // getNative
-
-/**
- * @brief Convert a UUID to its 128 bit representation.
- *
- * A UUID can be internally represented as 16bit, 32bit or the full 128bit.  This method
- * will convert 16 or 32 bit representations to the full 128bit.
- */
 BLEUUID BLEUUID::to128() {
-  //log_v(">> toFull() - %s", toString().c_str());
-
-  // If we either don't have a value or are already a 128 bit UUID, nothing further to do.
-  if (!m_valueSet || m_uuid.len == ESP_UUID_LEN_128) {
+  if (!m_valueSet || UUID_LEN(m_uuid) == BLE_UUID_128_BITS) {
     return *this;
   }
 
-  // If we are 16 bit or 32 bit, then set the 4 bytes of the variable part of the UUID.
-  if (m_uuid.len == ESP_UUID_LEN_16) {
-    uint16_t temp = m_uuid.uuid.uuid16;
-    m_uuid.uuid.uuid128[15] = 0;
-    m_uuid.uuid.uuid128[14] = 0;
-    m_uuid.uuid.uuid128[13] = (temp >> 8) & 0xff;
-    m_uuid.uuid.uuid128[12] = temp & 0xff;
-
-  } else if (m_uuid.len == ESP_UUID_LEN_32) {
-    uint32_t temp = m_uuid.uuid.uuid32;
-    m_uuid.uuid.uuid128[15] = (temp >> 24) & 0xff;
-    m_uuid.uuid.uuid128[14] = (temp >> 16) & 0xff;
-    m_uuid.uuid.uuid128[13] = (temp >> 8) & 0xff;
-    m_uuid.uuid.uuid128[12] = temp & 0xff;
+  if (UUID_LEN(m_uuid) == BLE_UUID_16_BITS) {
+    uint16_t temp = UUID_VAL_16(m_uuid);
+    UUID_VAL_128(m_uuid)[15] = 0;
+    UUID_VAL_128(m_uuid)[14] = 0;
+    UUID_VAL_128(m_uuid)[13] = (temp >> 8) & 0xff;
+    UUID_VAL_128(m_uuid)[12] = temp & 0xff;
+  } else if (UUID_LEN(m_uuid) == BLE_UUID_32_BITS) {
+    uint16_t temp = UUID_VAL_32(m_uuid);
+    UUID_VAL_128(m_uuid)[15] = (temp >> 24) & 0xff;
+    UUID_VAL_128(m_uuid)[14] = (temp >> 16) & 0xff;
+    UUID_VAL_128(m_uuid)[13] = (temp >> 8) & 0xff;
+    UUID_VAL_128(m_uuid)[12] = temp & 0xff;
   }
 
-  // Set the fixed parts of the UUID.
-  m_uuid.uuid.uuid128[11] = 0x00;
-  m_uuid.uuid.uuid128[10] = 0x00;
-
-  m_uuid.uuid.uuid128[9] = 0x10;
-  m_uuid.uuid.uuid128[8] = 0x00;
+  UUID_VAL_128(m_uuid)[11] = 0x00;
+  UUID_VAL_128(m_uuid)[10] = 0x00;
+  UUID_VAL_128(m_uuid)[9] = 0x10;
+  UUID_VAL_128(m_uuid)[8] = 0x00;
+  UUID_VAL_128(m_uuid)[7] = 0x80;
+  UUID_VAL_128(m_uuid)[6] = 0x00;
+  UUID_VAL_128(m_uuid)[5] = 0x00;
+  UUID_VAL_128(m_uuid)[4] = 0x80;
+  UUID_VAL_128(m_uuid)[3] = 0x5f;
+  UUID_VAL_128(m_uuid)[2] = 0x9b;
+  UUID_VAL_128(m_uuid)[1] = 0x34;
+  UUID_VAL_128(m_uuid)[0] = 0xfb;
+
+  UUID_LEN(m_uuid) = BLE_UUID_128_BITS;
+  return *this;
+}  // to128
 
-  m_uuid.uuid.uuid128[7] = 0x80;
-  m_uuid.uuid.uuid128[6] = 0x00;
+BLEUUID BLEUUID::to16() {
+  if (!m_valueSet || UUID_LEN(m_uuid) == BLE_UUID_16_BITS) {
+    return *this;
+  }
 
-  m_uuid.uuid.uuid128[5] = 0x00;
-  m_uuid.uuid.uuid128[4] = 0x80;
-  m_uuid.uuid.uuid128[3] = 0x5f;
-  m_uuid.uuid.uuid128[2] = 0x9b;
-  m_uuid.uuid.uuid128[1] = 0x34;
-  m_uuid.uuid.uuid128[0] = 0xfb;
+  if (UUID_LEN(m_uuid) == BLE_UUID_128_BITS) {
+    uint8_t base128[] = {0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00};
+    if (memcmp(UUID_VAL_128(m_uuid), base128, sizeof(base128)) == 0) {
+      *this = BLEUUID(*(uint16_t *)(UUID_VAL_128(m_uuid) + 12));
+    }
+  }
 
-  m_uuid.len = ESP_UUID_LEN_128;
-  //log_d("<< toFull <-  %s", toString().c_str());
   return *this;
-}  // to128
+}
 
-/**
- * @brief Get a string representation of the UUID.
- *
- * The format of a string is:
- * 01234567 8901 2345 6789 012345678901
- * 0000180d-0000-1000-8000-00805f9b34fb
- * 0 1 2 3  4 5  6 7  8 9  0 1 2 3 4 5
- *
- * @return A string representation of the UUID.
- */
-String BLEUUID::toString() {
+String BLEUUID::toString() const {
   if (!m_valueSet) {
     return "<NULL>";  // If we have no value, nothing to format.
   }
-  // If the UUIDs are 16 or 32 bit, pad correctly.
 
-  if (m_uuid.len == ESP_UUID_LEN_16) {  // If the UUID is 16bit, pad correctly.
+  if (UUID_LEN(m_uuid) == BLE_UUID_16_BITS) {  // If the UUID is 16bit, pad correctly.
     char hex[9];
-    snprintf(hex, sizeof(hex), "%08x", m_uuid.uuid.uuid16);
+    snprintf(hex, sizeof(hex), "%08x", UUID_VAL_16(m_uuid));
     return String(hex) + "-0000-1000-8000-00805f9b34fb";
   }  // End 16bit UUID
 
-  if (m_uuid.len == ESP_UUID_LEN_32) {  // If the UUID is 32bit, pad correctly.
+  if (UUID_LEN(m_uuid) == BLE_UUID_32_BITS) {  // If the UUID is 32bit, pad correctly.
     char hex[9];
-    snprintf(hex, sizeof(hex), "%08lx", m_uuid.uuid.uuid32);
+    snprintf(hex, sizeof(hex), "%08lx", UUID_VAL_32(m_uuid));
     return String(hex) + "-0000-1000-8000-00805f9b34fb";
   }  // End 32bit UUID
 
   // The UUID is not 16bit or 32bit which means that it is 128bit.
-  //
-  // UUID string format:
-  // AABBCCDD-EEFF-GGHH-IIJJ-KKLLMMNNOOPP
   auto size = 37;  // 32 for UUID data, 4 for '-' delimiters and one for a terminator == 37 chars
   char *hex = (char *)malloc(size);
   snprintf(
-    hex, size, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", m_uuid.uuid.uuid128[15], m_uuid.uuid.uuid128[14],
-    m_uuid.uuid.uuid128[13], m_uuid.uuid.uuid128[12], m_uuid.uuid.uuid128[11], m_uuid.uuid.uuid128[10], m_uuid.uuid.uuid128[9], m_uuid.uuid.uuid128[8],
-    m_uuid.uuid.uuid128[7], m_uuid.uuid.uuid128[6], m_uuid.uuid.uuid128[5], m_uuid.uuid.uuid128[4], m_uuid.uuid.uuid128[3], m_uuid.uuid.uuid128[2],
-    m_uuid.uuid.uuid128[1], m_uuid.uuid.uuid128[0]
+    hex, size, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", UUID_VAL_128(m_uuid)[15], UUID_VAL_128(m_uuid)[14],
+    UUID_VAL_128(m_uuid)[13], UUID_VAL_128(m_uuid)[12], UUID_VAL_128(m_uuid)[11], UUID_VAL_128(m_uuid)[10], UUID_VAL_128(m_uuid)[9], UUID_VAL_128(m_uuid)[8],
+    UUID_VAL_128(m_uuid)[7], UUID_VAL_128(m_uuid)[6], UUID_VAL_128(m_uuid)[5], UUID_VAL_128(m_uuid)[4], UUID_VAL_128(m_uuid)[3], UUID_VAL_128(m_uuid)[2],
+    UUID_VAL_128(m_uuid)[1], UUID_VAL_128(m_uuid)[0]
   );
+
   String res(hex);
   free(hex);
   return res;
 }  // toString
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+bool BLEUUID::operator==(const BLEUUID &rhs) const {
+  return equals(rhs);
+}
+
+bool BLEUUID::operator!=(const BLEUUID &rhs) const {
+  return !equals(rhs);
+}
+
+/*****************************************************************************
+ *                            Bluedroid functions                            *
+ *****************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+BLEUUID::BLEUUID(esp_bt_uuid_t uuid) {
+  m_uuid = uuid;
+  m_valueSet = true;
+}  // BLEUUID
+
+BLEUUID::BLEUUID(esp_gatt_id_t gattId) : BLEUUID(gattId.uuid) {}  // BLEUUID
+
+esp_bt_uuid_t *BLEUUID::getNative() {
+  if (m_valueSet == false) {
+    log_v("<< Return of un-initialized UUID!");
+    return nullptr;
+  }
+  return &m_uuid;
+}  // getNative
+#endif
+
+/*****************************************************************************
+ *                             NimBLE functions                              *
+ *****************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+BLEUUID::BLEUUID(ble_uuid_any_t uuid) {
+  m_uuid = uuid;
+  m_valueSet = true;
+}  // BLEUUID
+
+BLEUUID::BLEUUID(const ble_uuid128_t *uuid) {
+  m_uuid.u.type = BLE_UUID_TYPE_128;
+  memcpy(m_uuid.u128.value, uuid->value, 16);
+  m_valueSet = true;
+}  // BLEUUID
+
+const ble_uuid_any_t *BLEUUID::getNative() const {
+  if (m_valueSet == false) {
+    log_v("<< Return of un-initialized UUID!");
+    return nullptr;
+  }
+  return &m_uuid;
+}  // getNative
+#endif
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEUUID.h b/libraries/BLE/src/BLEUUID.h
index 1be013942e3..43c4e91b01d 100644
--- a/libraries/BLE/src/BLEUUID.h
+++ b/libraries/BLE/src/BLEUUID.h
@@ -3,42 +3,125 @@
  *
  *  Created on: Jun 21, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLEUUID_H_
 #define COMPONENTS_CPP_UTILS_BLEUUID_H_
 #include "soc/soc_caps.h"
-#include "WString.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if CONFIG_BLUEDROID_ENABLED
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/*****************************************************************************
+ *                             Common includes                               *
+ *****************************************************************************/
+
+#include "WString.h"
+
+/*****************************************************************************
+ *                     Bluedroid includes and definitions                    *
+ *****************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
 #include <esp_gatt_defs.h>
+#define BLE_UUID_16_BITS  ESP_UUID_LEN_16
+#define BLE_UUID_32_BITS  ESP_UUID_LEN_32
+#define BLE_UUID_128_BITS ESP_UUID_LEN_128
+#define UUID_LEN(s)       s.len
+#define UUID_VAL_16(s)    s.uuid.uuid16
+#define UUID_VAL_32(s)    s.uuid.uuid32
+#define UUID_VAL_128(s)   s.uuid.uuid128
+#endif
+
+/*****************************************************************************
+ *                       NimBLE includes and definitions                     *
+ *****************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_uuid.h>
+#define BLE_UUID_16_BITS  BLE_UUID_TYPE_16
+#define BLE_UUID_32_BITS  BLE_UUID_TYPE_32
+#define BLE_UUID_128_BITS BLE_UUID_TYPE_128
+#define UUID_LEN(s)       s.u.type
+#define UUID_VAL_16(s)    s.u16.value
+#define UUID_VAL_32(s)    s.u32.value
+#define UUID_VAL_128(s)   s.u128.value
+#endif
 
 /**
  * @brief A model of a %BLE UUID.
  */
 class BLEUUID {
 public:
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   BLEUUID(String uuid);
   BLEUUID(uint16_t uuid);
   BLEUUID(uint32_t uuid);
-  BLEUUID(esp_bt_uuid_t uuid);
   BLEUUID(uint8_t *pData, size_t size, bool msbFirst);
-  BLEUUID(esp_gatt_id_t gattId);
+  BLEUUID(uint32_t first, uint16_t second, uint16_t third, uint64_t fourth);
   BLEUUID();
   uint8_t bitSize();  // Get the number of bits in this uuid.
-  bool equals(BLEUUID uuid);
-  esp_bt_uuid_t *getNative();
+  bool equals(const BLEUUID &uuid) const;
   BLEUUID to128();
-  String toString();
+  BLEUUID to16();
+  String toString() const;
   static BLEUUID fromString(String uuid);  // Create a BLEUUID from a string
 
+  bool operator==(const BLEUUID &rhs) const;
+  bool operator!=(const BLEUUID &rhs) const;
+
+  /***************************************************************************
+   *                      Bluedroid public declarations                      *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  BLEUUID(esp_bt_uuid_t uuid);
+  BLEUUID(esp_gatt_id_t gattId);
+  esp_bt_uuid_t *getNative();
+#endif
+
+  /***************************************************************************
+   *                        NimBLE public declarations                       *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  BLEUUID(ble_uuid_any_t uuid);
+  BLEUUID(const ble_uuid128_t *uuid);
+  const ble_uuid_any_t *getNative() const;
+#endif
+
 private:
-  esp_bt_uuid_t m_uuid;     // The underlying UUID structure that this class wraps.
+  /***************************************************************************
+   *                        Common private properties                        *
+   ***************************************************************************/
+
   bool m_valueSet = false;  // Is there a value set for this instance.
+
+  /***************************************************************************
+   *                       Bluedroid private properties                      *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  esp_bt_uuid_t m_uuid;  // The underlying UUID structure that this class wraps.
+#endif
+
+  /***************************************************************************
+   *                       NimBLE private properties                         *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  ble_uuid_any_t m_uuid;  // The underlying UUID structure that this class wraps.
+#endif
 };  // BLEUUID
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLEUUID_H_ */
diff --git a/libraries/BLE/src/BLEUtils.cpp b/libraries/BLE/src/BLEUtils.cpp
index 05e1e32deed..4ca04e6e2b6 100644
--- a/libraries/BLE/src/BLEUtils.cpp
+++ b/libraries/BLE/src/BLEUtils.cpp
@@ -3,12 +3,22 @@
  *
  *  Created on: Mar 25, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/*****************************************************************************
+ *                             Common includes                               *
+ *****************************************************************************/
+
 #include "BLEAddress.h"
 #include "BLEClient.h"
 #include "BLEUtils.h"
@@ -17,17 +27,56 @@
 
 #include <freertos/FreeRTOS.h>
 #include <freertos/event_groups.h>
-#include <esp_bt.h>           // ESP32 BLE
-#include <esp_bt_main.h>      // ESP32 BLE
-#include <esp_gap_ble_api.h>  // ESP32 BLE
-#include <esp_gattc_api.h>    // ESP32 BLE
-#include <esp_err.h>          // ESP32 ESP-IDF
-#include <map>                // Part of C++ STL
+#include <esp_bt.h>
+
+#include <esp_err.h>
+#include <map>
 #include <sstream>
 #include <iomanip>
 
 #include "esp32-hal-log.h"
 
+/*****************************************************************************
+ *                            Bluedroid includes                             *
+ *****************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_bt_main.h>
+#include <esp_gap_ble_api.h>
+#include <esp_gattc_api.h>
+#endif
+
+/*****************************************************************************
+ *                       NimBLE includes and definitions                     *
+ *****************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <host/ble_gap.h>
+#include <host/ble_att.h>
+#include <host/ble_hs.h>
+#include <host/ble_sm.h>
+#include <host/ble_l2cap.h>
+#include <nimble/hci_common.h>
+#include <nimble/ble.h>
+
+#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
+#define CONFIG_NIMBLE_ENABLE_RETURN_CODE_TEXT
+#define CONFIG_NIMBLE_ENABLE_ADVERTISMENT_TYPE_TEXT
+#define CONFIG_NIMBLE_ENABLE_GAP_EVENT_CODE_TEXT
+#endif
+
+#ifndef CONFIG_NIMBLE_FREERTOS_TASK_BLOCK_BIT
+#define CONFIG_NIMBLE_FREERTOS_TASK_BLOCK_BIT 31
+#endif
+
+constexpr uint32_t TASK_BLOCK_BIT = (1 << CONFIG_NIMBLE_FREERTOS_TASK_BLOCK_BIT);
+#endif
+
+/*****************************************************************************
+ *                       Bluedroid types and constants                       *
+ *****************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
 typedef struct {
   uint32_t assignedNumber;
   const char *name;
@@ -593,90 +642,58 @@ static const gattService_t g_gattServices[] = {
 #endif
   {"", "", 0}
 };
+#endif
 
-/**
- * @brief Convert characteristic properties into a string representation.
- * @param [in] prop Characteristic properties.
- * @return A string representation of characteristic properties.
- */
-String BLEUtils::characteristicPropertiesToString(esp_gatt_char_prop_t prop) {
-  String res = "broadcast: ";
-  res += ((prop & ESP_GATT_CHAR_PROP_BIT_BROADCAST) ? "1" : "0");
-  res += ", read: ";
-  res += ((prop & ESP_GATT_CHAR_PROP_BIT_READ) ? "1" : "0");
-  res += ", write_nr: ";
-  res += ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) ? "1" : "0");
-  res += ", write: ";
-  res += ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE) ? "1" : "0");
-  res += ", notify: ";
-  res += ((prop & ESP_GATT_CHAR_PROP_BIT_NOTIFY) ? "1" : "0");
-  res += ", indicate: ";
-  res += ((prop & ESP_GATT_CHAR_PROP_BIT_INDICATE) ? "1" : "0");
-  res += ", auth: ";
-  res += ((prop & ESP_GATT_CHAR_PROP_BIT_AUTH) ? "1" : "0");
-  return res;
-}  // characteristicPropertiesToString
-
-/**
- * @brief Convert an esp_gatt_id_t to a string.
- */
-static String gattIdToString(esp_gatt_id_t gattId) {
-  String res = "uuid: " + BLEUUID(gattId.uuid).toString() + ", inst_id: ";
-  char val[8];
-  snprintf(val, sizeof(val), "%d", (int)gattId.inst_id);
-  res += val;
-  return res;
-}  // gattIdToString
+/*****************************************************************************
+ *                             Common functions                              *
+ *****************************************************************************/
 
 /**
- * @brief Convert an esp_ble_addr_type_t to a string representation.
+ * @brief Create a hex representation of data.
+ *
+ * @param [in] target Where to write the hex string.  If this is null, we malloc storage.
+ * @param [in] source The start of the binary data.
+ * @param [in] length The length of the data to convert.
+ * @return A pointer to the formatted buffer.
  */
-const char *BLEUtils::addressTypeToString(esp_ble_addr_type_t type) {
-  switch (type) {
-#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
-    case BLE_ADDR_TYPE_PUBLIC:     return "BLE_ADDR_TYPE_PUBLIC";
-    case BLE_ADDR_TYPE_RANDOM:     return "BLE_ADDR_TYPE_RANDOM";
-    case BLE_ADDR_TYPE_RPA_PUBLIC: return "BLE_ADDR_TYPE_RPA_PUBLIC";
-    case BLE_ADDR_TYPE_RPA_RANDOM: return "BLE_ADDR_TYPE_RPA_RANDOM";
-#endif
-    default: return " esp_ble_addr_type_t";
+char *BLEUtils::buildHexData(uint8_t *target, uint8_t *source, uint8_t length) {
+  // Guard against too much data.
+  if (length > 100) {
+    length = 100;
   }
-}  // addressTypeToString
 
-/**
- * @brief Convert the BLE Advertising Data flags to a string.
- * @param adFlags The flags to convert
- * @return String A string representation of the advertising flags.
- */
-String BLEUtils::adFlagsToString(uint8_t adFlags) {
-  String res;
-  if (adFlags & (1 << 0)) {
-    res += "[LE Limited Discoverable Mode] ";
-  }
-  if (adFlags & (1 << 1)) {
-    res += "[LE General Discoverable Mode] ";
-  }
-  if (adFlags & (1 << 2)) {
-    res += "[BR/EDR Not Supported] ";
+  if (target == nullptr) {
+    target = (uint8_t *)malloc(length * 2 + 1);
+    if (target == nullptr) {
+      log_e("buildHexData: malloc failed");
+      return nullptr;
+    }
   }
-  if (adFlags & (1 << 3)) {
-    res += "[Simultaneous LE and BR/EDR to Same Device Capable (Controller)] ";
+  char *startOfData = (char *)target;
+
+  for (int i = 0; i < length; i++) {
+    sprintf((char *)target, "%.2x", (char)*source);
+    source++;
+    target += 2;
   }
-  if (adFlags & (1 << 4)) {
-    res += "[Simultaneous LE and BR/EDR to Same Device Capable (Host)] ";
+
+  // Handle the special case where there was no data.
+  if (length == 0) {
+    *startOfData = 0;
   }
-  return res;
-}  // adFlagsToString
+
+  return startOfData;
+}  // buildHexData
 
 /**
- * @brief Given an advertising type, return a string representation of the type.
+ * @brief Given an advertising data type, return a string representation of the type.
  *
  * For details see ...
  * https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile
  *
  * @return A string representation of the type.
  */
-const char *BLEUtils::advTypeToString(uint8_t advType) {
+const char *BLEUtils::advDataTypeToString(uint8_t advType) {
   switch (advType) {
 #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
     case ESP_BLE_AD_TYPE_FLAG:  // 0x01
@@ -721,7 +738,8 @@ const char *BLEUtils::advTypeToString(uint8_t advType) {
       return "ESP_BLE_AD_TYPE_APPEARANCE";
     case ESP_BLE_AD_TYPE_ADV_INT:  // 0x1a
       return "ESP_BLE_AD_TYPE_ADV_INT";
-    case ESP_BLE_AD_TYPE_32SOL_SRV_UUID: return "ESP_BLE_AD_TYPE_32SOL_SRV_UUID";
+    case ESP_BLE_AD_TYPE_32SOL_SRV_UUID:  // 0x1f
+      return "ESP_BLE_AD_TYPE_32SOL_SRV_UUID";
     case ESP_BLE_AD_TYPE_32SERVICE_DATA:  // 0x20
       return "ESP_BLE_AD_TYPE_32SERVICE_DATA";
     case ESP_BLE_AD_TYPE_128SERVICE_DATA:  // 0x21
@@ -731,58 +749,36 @@ const char *BLEUtils::advTypeToString(uint8_t advType) {
 #endif
     default: log_v(" adv data type: 0x%x", advType); return "";
   }  // End switch
-}  // advTypeToString
+}  // advDataTypeToString
 
-esp_gatt_id_t BLEUtils::buildGattId(esp_bt_uuid_t uuid, uint8_t inst_id) {
-  esp_gatt_id_t retGattId;
-  retGattId.uuid = uuid;
-  retGattId.inst_id = inst_id;
-  return retGattId;
-}
+/*****************************************************************************
+ *                            Bluedroid functions                            *
+ *****************************************************************************/
 
-esp_gatt_srvc_id_t BLEUtils::buildGattSrvcId(esp_gatt_id_t gattId, bool is_primary) {
-  esp_gatt_srvc_id_t retSrvcId;
-  retSrvcId.id = gattId;
-  retSrvcId.is_primary = is_primary;
-  return retSrvcId;
-}
+#if defined(CONFIG_BLUEDROID_ENABLED)
 
 /**
- * @brief Create a hex representation of data.
- *
- * @param [in] target Where to write the hex string.  If this is null, we malloc storage.
- * @param [in] source The start of the binary data.
- * @param [in] length The length of the data to convert.
- * @return A pointer to the formatted buffer.
+ * @brief Convert characteristic properties into a string representation.
+ * @param [in] prop Characteristic properties.
+ * @return A string representation of characteristic properties.
  */
-char *BLEUtils::buildHexData(uint8_t *target, uint8_t *source, uint8_t length) {
-  // Guard against too much data.
-  if (length > 100) {
-    length = 100;
-  }
-
-  if (target == nullptr) {
-    target = (uint8_t *)malloc(length * 2 + 1);
-    if (target == nullptr) {
-      log_e("buildHexData: malloc failed");
-      return nullptr;
-    }
-  }
-  char *startOfData = (char *)target;
-
-  for (int i = 0; i < length; i++) {
-    sprintf((char *)target, "%.2x", (char)*source);
-    source++;
-    target += 2;
-  }
-
-  // Handle the special case where there was no data.
-  if (length == 0) {
-    *startOfData = 0;
-  }
-
-  return startOfData;
-}  // buildHexData
+String BLEUtils::characteristicPropertiesToString(uint8_t prop) {
+  String res = "broadcast: ";
+  res += ((prop & ESP_GATT_CHAR_PROP_BIT_BROADCAST) ? "1" : "0");
+  res += ", read: ";
+  res += ((prop & ESP_GATT_CHAR_PROP_BIT_READ) ? "1" : "0");
+  res += ", write_nr: ";
+  res += ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) ? "1" : "0");
+  res += ", write: ";
+  res += ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE) ? "1" : "0");
+  res += ", notify: ";
+  res += ((prop & ESP_GATT_CHAR_PROP_BIT_NOTIFY) ? "1" : "0");
+  res += ", indicate: ";
+  res += ((prop & ESP_GATT_CHAR_PROP_BIT_INDICATE) ? "1" : "0");
+  res += ", auth: ";
+  res += ((prop & ESP_GATT_CHAR_PROP_BIT_AUTH) ? "1" : "0");
+  return res;
+}  // characteristicPropertiesToString
 
 /**
  * @brief Build a printable string of memory range.
@@ -802,6 +798,71 @@ String BLEUtils::buildPrintData(uint8_t *source, size_t length) {
   return res;
 }  // buildPrintData
 
+/**
+ * @brief Convert an esp_gatt_id_t to a string.
+ */
+static String gattIdToString(esp_gatt_id_t gattId) {
+  String res = "uuid: " + BLEUUID(gattId.uuid).toString() + ", inst_id: ";
+  char val[8];
+  snprintf(val, sizeof(val), "%d", (int)gattId.inst_id);
+  res += val;
+  return res;
+}  // gattIdToString
+
+/**
+ * @brief Convert an esp_ble_addr_type_t to a string representation.
+ */
+const char *BLEUtils::addressTypeToString(esp_ble_addr_type_t type) {
+  switch (type) {
+#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
+    case BLE_ADDR_TYPE_PUBLIC:     return "BLE_ADDR_TYPE_PUBLIC";
+    case BLE_ADDR_TYPE_RANDOM:     return "BLE_ADDR_TYPE_RANDOM";
+    case BLE_ADDR_TYPE_RPA_PUBLIC: return "BLE_ADDR_TYPE_RPA_PUBLIC";
+    case BLE_ADDR_TYPE_RPA_RANDOM: return "BLE_ADDR_TYPE_RPA_RANDOM";
+#endif
+    default: return " esp_ble_addr_type_t";
+  }
+}  // addressTypeToString
+
+/**
+ * @brief Convert the BLE Advertising Data flags to a string.
+ * @param adFlags The flags to convert
+ * @return String A string representation of the advertising flags.
+ */
+String BLEUtils::adFlagsToString(uint8_t adFlags) {
+  String res;
+  if (adFlags & (1 << 0)) {
+    res += "[LE Limited Discoverable Mode] ";
+  }
+  if (adFlags & (1 << 1)) {
+    res += "[LE General Discoverable Mode] ";
+  }
+  if (adFlags & (1 << 2)) {
+    res += "[BR/EDR Not Supported] ";
+  }
+  if (adFlags & (1 << 3)) {
+    res += "[Simultaneous LE and BR/EDR to Same Device Capable (Controller)] ";
+  }
+  if (adFlags & (1 << 4)) {
+    res += "[Simultaneous LE and BR/EDR to Same Device Capable (Host)] ";
+  }
+  return res;
+}  // adFlagsToString
+
+esp_gatt_id_t BLEUtils::buildGattId(esp_bt_uuid_t uuid, uint8_t inst_id) {
+  esp_gatt_id_t retGattId;
+  retGattId.uuid = uuid;
+  retGattId.inst_id = inst_id;
+  return retGattId;
+}
+
+esp_gatt_srvc_id_t BLEUtils::buildGattSrvcId(esp_gatt_id_t gattId, bool is_primary) {
+  esp_gatt_srvc_id_t retSrvcId;
+  retSrvcId.id = gattId;
+  retSrvcId.is_primary = is_primary;
+  return retSrvcId;
+}
+
 /**
  * @brief Convert a close/disconnect reason to a string.
  * @param [in] reason The close reason.
@@ -1817,5 +1878,380 @@ const char *BLEUtils::searchEventTypeToString(esp_gap_search_evt_t searchEvt) {
   }
 }  // searchEventTypeToString
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif  // CONFIG_BLUEDROID_ENABLED
+
+/*****************************************************************************
+ *                             NimBLE functions                              *
+ *****************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
+/**
+ * @brief Construct a BLETaskData instance.
+ * @param [in] pInstance An instance of the class that will be waiting.
+ * @param [in] flags General purpose flags for the caller.
+ * @param [in] buf A buffer for data.
+ */
+BLETaskData::BLETaskData(void *pInstance, int flags, void *buf) : m_pInstance{pInstance}, m_flags{flags}, m_pBuf{buf}, m_pHandle{xTaskGetCurrentTaskHandle()} {}
+
+/**
+ * @brief Destructor.
+ */
+BLETaskData::~BLETaskData() {}
+
+/**
+ * @brief A function for checking validity of connection parameters.
+ * @param [in] params A pointer to the structure containing the parameters to check.
+ * @return valid == 0 or error code.
+ */
+int BLEUtils::checkConnParams(ble_gap_conn_params *params) {
+  /* Check connection interval min */
+  if ((params->itvl_min < BLE_HCI_CONN_ITVL_MIN) || (params->itvl_min > BLE_HCI_CONN_ITVL_MAX)) {
+    return BLE_ERR_INV_HCI_CMD_PARMS;
+  }
+  /* Check connection interval max */
+  if ((params->itvl_max < BLE_HCI_CONN_ITVL_MIN) || (params->itvl_max > BLE_HCI_CONN_ITVL_MAX) || (params->itvl_max < params->itvl_min)) {
+    return BLE_ERR_INV_HCI_CMD_PARMS;
+  }
+
+  /* Check connection latency */
+  if (params->latency > BLE_HCI_CONN_LATENCY_MAX) {
+    return BLE_ERR_INV_HCI_CMD_PARMS;
+  }
+
+  /* Check supervision timeout */
+  if ((params->supervision_timeout < BLE_HCI_CONN_SPVN_TIMEOUT_MIN) || (params->supervision_timeout > BLE_HCI_CONN_SPVN_TIMEOUT_MAX)) {
+    return BLE_ERR_INV_HCI_CMD_PARMS;
+  }
+
+  /* Check connection event length */
+  if (params->min_ce_len > params->max_ce_len) {
+    return BLE_ERR_INV_HCI_CMD_PARMS;
+  }
+
+  return 0;
+}
+
+/**
+ * @brief Converts a return code from the NimBLE stack to a text string.
+ * @param [in] rc The return code to convert.
+ * @return A string representation of the return code.
+ */
+const char *BLEUtils::returnCodeToString(int rc) {
+#if defined(CONFIG_NIMBLE_ENABLE_RETURN_CODE_TEXT)
+  switch (rc) {
+    case 0:                                             return "SUCCESS";
+    case BLE_HS_EAGAIN:                                 return "Temporary failure; try again.";
+    case BLE_HS_EALREADY:                               return "Operation already in progress or completed.";
+    case BLE_HS_EINVAL:                                 return "One or more arguments are invalid.";
+    case BLE_HS_EMSGSIZE:                               return "The provided buffer is too small.";
+    case BLE_HS_ENOENT:                                 return "No entry matching the specified criteria.";
+    case BLE_HS_ENOMEM:                                 return "Operation failed due to resource exhaustion.";
+    case BLE_HS_ENOTCONN:                               return "No open connection with the specified handle.";
+    case BLE_HS_ENOTSUP:                                return "Operation disabled at compile time.";
+    case BLE_HS_EAPP:                                   return "Application callback behaved unexpectedly.";
+    case BLE_HS_EBADDATA:                               return "Command from peer is invalid.";
+    case BLE_HS_EOS:                                    return "Mynewt OS error.";
+    case BLE_HS_ECONTROLLER:                            return "Event from controller is invalid.";
+    case BLE_HS_ETIMEOUT:                               return "Operation timed out.";
+    case BLE_HS_EDONE:                                  return "Operation completed successfully.";
+    case BLE_HS_EBUSY:                                  return "Operation cannot be performed until procedure completes.";
+    case BLE_HS_EREJECT:                                return "Peer rejected a connection parameter update request.";
+    case BLE_HS_EUNKNOWN:                               return "Unexpected failure; catch all.";
+    case BLE_HS_EROLE:                                  return "Operation requires different role (e.g., central vs. peripheral).";
+    case BLE_HS_ETIMEOUT_HCI:                           return "HCI request timed out; controller unresponsive.";
+    case BLE_HS_ENOMEM_EVT:                             return "Controller failed to send event due to memory exhaustion (combined host-controller only).";
+    case BLE_HS_ENOADDR:                                return "Operation requires an identity address but none configured.";
+    case BLE_HS_ENOTSYNCED:                             return "Attempt to use the host before it is synced with controller.";
+    case BLE_HS_EAUTHEN:                                return "Insufficient authentication.";
+    case BLE_HS_EAUTHOR:                                return "Insufficient authorization.";
+    case BLE_HS_EENCRYPT:                               return "Insufficient encryption level.";
+    case BLE_HS_EENCRYPT_KEY_SZ:                        return "Insufficient key size.";
+    case BLE_HS_ESTORE_CAP:                             return "Storage at capacity.";
+    case BLE_HS_ESTORE_FAIL:                            return "Storage IO error.";
+    case BLE_HS_EPREEMPTED:                             return "Operation was preempted.";
+    case BLE_HS_EDISABLED:                              return "Operation disabled.";
+    case BLE_HS_ESTALLED:                               return "Operation stalled.";
+    case (0x0100 + BLE_ATT_ERR_INVALID_HANDLE):         return "The attribute handle given was not valid on this server.";
+    case (0x0100 + BLE_ATT_ERR_READ_NOT_PERMITTED):     return "The attribute cannot be read.";
+    case (0x0100 + BLE_ATT_ERR_WRITE_NOT_PERMITTED):    return "The attribute cannot be written.";
+    case (0x0100 + BLE_ATT_ERR_INVALID_PDU):            return "The attribute PDU was invalid.";
+    case (0x0100 + BLE_ATT_ERR_INSUFFICIENT_AUTHEN):    return "The attribute requires authentication before it can be read or written.";
+    case (0x0100 + BLE_ATT_ERR_REQ_NOT_SUPPORTED):      return "Attribute server does not support the request received from the client.";
+    case (0x0100 + BLE_ATT_ERR_INVALID_OFFSET):         return "Offset specified was past the end of the attribute.";
+    case (0x0100 + BLE_ATT_ERR_INSUFFICIENT_AUTHOR):    return "The attribute requires authorization before it can be read or written.";
+    case (0x0100 + BLE_ATT_ERR_PREPARE_QUEUE_FULL):     return "Too many prepare writes have been queued.";
+    case (0x0100 + BLE_ATT_ERR_ATTR_NOT_FOUND):         return "No attribute found within the given attribute handle range.";
+    case (0x0100 + BLE_ATT_ERR_ATTR_NOT_LONG):          return "The attribute cannot be read or written using the Read Blob Request.";
+    case (0x0100 + BLE_ATT_ERR_INSUFFICIENT_KEY_SZ):    return "The Encryption Key Size used for encrypting this link is insufficient.";
+    case (0x0100 + BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN): return "The attribute value length is invalid for the operation.";
+    case (0x0100 + BLE_ATT_ERR_UNLIKELY):               return "The attribute request has encountered an error that was unlikely, could not be completed as requested.";
+    case (0x0100 + BLE_ATT_ERR_INSUFFICIENT_ENC):       return "The attribute requires encryption before it can be read or written.";
+    case (0x0100 + BLE_ATT_ERR_UNSUPPORTED_GROUP):
+      return "The attribute type is not a supported grouping attribute as defined by a higher layer specification.";
+    case (0x0100 + BLE_ATT_ERR_INSUFFICIENT_RES):         return "Insufficient Resources to complete the request.";
+    case (0x0200 + BLE_ERR_UNKNOWN_HCI_CMD):              return "Unknown HCI Command";
+    case (0x0200 + BLE_ERR_UNK_CONN_ID):                  return "Unknown Connection Identifier";
+    case (0x0200 + BLE_ERR_HW_FAIL):                      return "Hardware Failure";
+    case (0x0200 + BLE_ERR_PAGE_TMO):                     return "Page Timeout";
+    case (0x0200 + BLE_ERR_AUTH_FAIL):                    return "Authentication Failure";
+    case (0x0200 + BLE_ERR_PINKEY_MISSING):               return "PIN or Key Missing";
+    case (0x0200 + BLE_ERR_MEM_CAPACITY):                 return "Memory Capacity Exceeded";
+    case (0x0200 + BLE_ERR_CONN_SPVN_TMO):                return "Connection Timeout";
+    case (0x0200 + BLE_ERR_CONN_LIMIT):                   return "Connection Limit Exceeded";
+    case (0x0200 + BLE_ERR_SYNCH_CONN_LIMIT):             return "Synchronous Connection Limit To A Device Exceeded";
+    case (0x0200 + BLE_ERR_ACL_CONN_EXISTS):              return "ACL Connection Already Exists";
+    case (0x0200 + BLE_ERR_CMD_DISALLOWED):               return "Command Disallowed";
+    case (0x0200 + BLE_ERR_CONN_REJ_RESOURCES):           return "Connection Rejected due to Limited Resources";
+    case (0x0200 + BLE_ERR_CONN_REJ_SECURITY):            return "Connection Rejected Due To Security Reasons";
+    case (0x0200 + BLE_ERR_CONN_REJ_BD_ADDR):             return "Connection Rejected due to Unacceptable BD_ADDR";
+    case (0x0200 + BLE_ERR_CONN_ACCEPT_TMO):              return "Connection Accept Timeout Exceeded";
+    case (0x0200 + BLE_ERR_UNSUPPORTED):                  return "Unsupported Feature or Parameter Value";
+    case (0x0200 + BLE_ERR_INV_HCI_CMD_PARMS):            return "Invalid HCI Command Parameters";
+    case (0x0200 + BLE_ERR_REM_USER_CONN_TERM):           return "Remote User Terminated Connection";
+    case (0x0200 + BLE_ERR_RD_CONN_TERM_RESRCS):          return "Remote Device Terminated Connection due to Low Resources";
+    case (0x0200 + BLE_ERR_RD_CONN_TERM_PWROFF):          return "Remote Device Terminated Connection due to Power Off";
+    case (0x0200 + BLE_ERR_CONN_TERM_LOCAL):              return "Connection Terminated By Local Host";
+    case (0x0200 + BLE_ERR_REPEATED_ATTEMPTS):            return "Repeated Attempts";
+    case (0x0200 + BLE_ERR_NO_PAIRING):                   return "Pairing Not Allowed";
+    case (0x0200 + BLE_ERR_UNK_LMP):                      return "Unknown LMP PDU";
+    case (0x0200 + BLE_ERR_UNSUPP_REM_FEATURE):           return "Unsupported Remote Feature / Unsupported LMP Feature";
+    case (0x0200 + BLE_ERR_SCO_OFFSET):                   return "SCO Offset Rejected";
+    case (0x0200 + BLE_ERR_SCO_ITVL):                     return "SCO Interval Rejected";
+    case (0x0200 + BLE_ERR_SCO_AIR_MODE):                 return "SCO Air Mode Rejected";
+    case (0x0200 + BLE_ERR_INV_LMP_LL_PARM):              return "Invalid LMP Parameters / Invalid LL Parameters";
+    case (0x0200 + BLE_ERR_UNSPECIFIED):                  return "Unspecified Error";
+    case (0x0200 + BLE_ERR_UNSUPP_LMP_LL_PARM):           return "Unsupported LMP Parameter Value / Unsupported LL Parameter Value";
+    case (0x0200 + BLE_ERR_NO_ROLE_CHANGE):               return "Role Change Not Allowed";
+    case (0x0200 + BLE_ERR_LMP_LL_RSP_TMO):               return "LMP Response Timeout / LL Response Timeout";
+    case (0x0200 + BLE_ERR_LMP_COLLISION):                return "LMP Error Transaction Collision";
+    case (0x0200 + BLE_ERR_LMP_PDU):                      return "LMP PDU Not Allowed";
+    case (0x0200 + BLE_ERR_ENCRYPTION_MODE):              return "Encryption Mode Not Acceptable";
+    case (0x0200 + BLE_ERR_LINK_KEY_CHANGE):              return "Link Key cannot be Changed";
+    case (0x0200 + BLE_ERR_UNSUPP_QOS):                   return "Requested QoS Not Supported";
+    case (0x0200 + BLE_ERR_INSTANT_PASSED):               return "Instant Passed";
+    case (0x0200 + BLE_ERR_UNIT_KEY_PAIRING):             return "Pairing With Unit Key Not Supported";
+    case (0x0200 + BLE_ERR_DIFF_TRANS_COLL):              return "Different Transaction Collision";
+    case (0x0200 + BLE_ERR_QOS_PARM):                     return "QoS Unacceptable Parameter";
+    case (0x0200 + BLE_ERR_QOS_REJECTED):                 return "QoS Rejected";
+    case (0x0200 + BLE_ERR_CHAN_CLASS):                   return "Channel Classification Not Supported";
+    case (0x0200 + BLE_ERR_INSUFFICIENT_SEC):             return "Insufficient Security";
+    case (0x0200 + BLE_ERR_PARM_OUT_OF_RANGE):            return "Parameter Out Of Mandatory Range";
+    case (0x0200 + BLE_ERR_PENDING_ROLE_SW):              return "Role Switch Pending";
+    case (0x0200 + BLE_ERR_RESERVED_SLOT):                return "Reserved Slot Violation";
+    case (0x0200 + BLE_ERR_ROLE_SW_FAIL):                 return "Role Switch Failed";
+    case (0x0200 + BLE_ERR_INQ_RSP_TOO_BIG):              return "Extended Inquiry Response Too Large";
+    case (0x0200 + BLE_ERR_SEC_SIMPLE_PAIR):              return "Secure Simple Pairing Not Supported By Host";
+    case (0x0200 + BLE_ERR_HOST_BUSY_PAIR):               return "Host Busy - Pairing";
+    case (0x0200 + BLE_ERR_CONN_REJ_CHANNEL):             return "Connection Rejected, No Suitable Channel Found";
+    case (0x0200 + BLE_ERR_CTLR_BUSY):                    return "Controller Busy";
+    case (0x0200 + BLE_ERR_CONN_PARMS):                   return "Unacceptable Connection Parameters";
+    case (0x0200 + BLE_ERR_DIR_ADV_TMO):                  return "Directed Advertising Timeout";
+    case (0x0200 + BLE_ERR_CONN_TERM_MIC):                return "Connection Terminated due to MIC Failure";
+    case (0x0200 + BLE_ERR_CONN_ESTABLISHMENT):           return "Connection Failed to be Established";
+    case (0x0200 + BLE_ERR_MAC_CONN_FAIL):                return "MAC Connection Failed";
+    case (0x0200 + BLE_ERR_COARSE_CLK_ADJ):               return "Coarse Clock Adjustment Rejected";
+    case (0x0300 + BLE_L2CAP_SIG_ERR_CMD_NOT_UNDERSTOOD): return "Invalid or unsupported incoming L2CAP sig command.";
+    case (0x0300 + BLE_L2CAP_SIG_ERR_MTU_EXCEEDED):       return "Incoming packet too large.";
+    case (0x0300 + BLE_L2CAP_SIG_ERR_INVALID_CID):        return "No channel with specified ID.";
+    case (0x0400 + BLE_SM_ERR_PASSKEY):                   return "The user input of passkey failed, for example, the user canceled the operation.";
+    case (0x0400 + BLE_SM_ERR_OOB):                       return "The OOB data is not available.";
+    case (0x0400 + BLE_SM_ERR_AUTHREQ):
+      return "The pairing procedure cannot be performed as authentication requirements cannot be met due to IO capabilities of one or both devices.";
+    case (0x0400 + BLE_SM_ERR_CONFIRM_MISMATCH): return "The confirm value does not match the calculated compare value.";
+    case (0x0400 + BLE_SM_ERR_PAIR_NOT_SUPP):    return "Pairing is not supported by the device.";
+    case (0x0400 + BLE_SM_ERR_ENC_KEY_SZ):       return "The resultant encryption key size is insufficient for the security requirements of this device.";
+    case (0x0400 + BLE_SM_ERR_CMD_NOT_SUPP):     return "The SMP command received is not supported on this device.";
+    case (0x0400 + BLE_SM_ERR_UNSPECIFIED):      return "Pairing failed due to an unspecified reason.";
+    case (0x0400 + BLE_SM_ERR_REPEATED):
+      return "Pairing or authentication procedure disallowed, too little time has elapsed since last pairing request or security request.";
+    case (0x0400 + BLE_SM_ERR_INVAL):   return "Command length is invalid or that a parameter is outside of the specified range.";
+    case (0x0400 + BLE_SM_ERR_DHKEY):   return "DHKey Check value received doesn't match the one calculated by the local device.";
+    case (0x0400 + BLE_SM_ERR_NUMCMP):  return "Confirm values in the numeric comparison protocol do not match.";
+    case (0x0400 + BLE_SM_ERR_ALREADY): return "Pairing over the LE transport failed - Pairing Request sent over the BR/EDR transport in process.";
+    case (0x0400 + BLE_SM_ERR_CROSS_TRANS):
+      return "BR/EDR Link Key generated on the BR/EDR transport cannot be used to derive and distribute keys for the LE transport.";
+    case (0x0500 + BLE_SM_ERR_PASSKEY): return "The user input of passkey failed or the user canceled the operation.";
+    case (0x0500 + BLE_SM_ERR_OOB):     return "The OOB data is not available.";
+    case (0x0500 + BLE_SM_ERR_AUTHREQ):
+      return "The pairing procedure cannot be performed as authentication requirements cannot be met due to IO capabilities of one or both devices.";
+    case (0x0500 + BLE_SM_ERR_CONFIRM_MISMATCH): return "The confirm value does not match the calculated compare value.";
+    case (0x0500 + BLE_SM_ERR_PAIR_NOT_SUPP):    return "Pairing is not supported by the device.";
+    case (0x0500 + BLE_SM_ERR_ENC_KEY_SZ):       return "The resultant encryption key size is insufficient for the security requirements of this device.";
+    case (0x0500 + BLE_SM_ERR_CMD_NOT_SUPP):     return "The SMP command received is not supported on this device.";
+    case (0x0500 + BLE_SM_ERR_UNSPECIFIED):      return "Pairing failed due to an unspecified reason.";
+    case (0x0500 + BLE_SM_ERR_REPEATED):
+      return "Pairing or authentication procedure is disallowed because too little time has elapsed since last pairing request or security request.";
+    case (0x0500 + BLE_SM_ERR_INVAL): return "Command length is invalid or a parameter is outside of the specified range.";
+    case (0x0500 + BLE_SM_ERR_DHKEY):
+      return "Indicates to the remote device that the DHKey Check value received doesn't match the one calculated by the local device.";
+    case (0x0500 + BLE_SM_ERR_NUMCMP):  return "Confirm values in the numeric comparison protocol do not match.";
+    case (0x0500 + BLE_SM_ERR_ALREADY): return "Pairing over the LE transport failed - Pairing Request sent over the BR/EDR transport in process.";
+    case (0x0500 + BLE_SM_ERR_CROSS_TRANS):
+      return "BR/EDR Link Key generated on the BR/EDR transport cannot be used to derive and distribute keys for the LE transport.";
+    default: return "Unknown";
+  }
+#else   // #if defined(CONFIG_NIMBLE_ENABLE_RETURN_CODE_TEXT)
+  return "";
+#endif  // #if defined(CONFIG_NIMBLE_ENABLE_RETURN_CODE_TEXT)
+}
+
+/**
+ * @brief Utility function to log the gap event info.
+ * @param [in] event A pointer to the gap event structure.
+ * @param [in] arg Unused.
+ */
+void BLEUtils::dumpGapEvent(ble_gap_event *event, void *arg) {
+#if defined(CONFIG_NIMBLE_ENABLE_GAP_EVENT_CODE_TEXT)
+  log_d("Received a GAP event: %s", gapEventToString(event->type));
+#endif
+}
+
+/**
+ * @brief Convert a GAP event type to a string representation.
+ * @param [in] eventType The type of event.
+ * @return A string representation of the event type.
+ */
+const char *BLEUtils::gapEventToString(uint8_t eventType) {
+#if defined(CONFIG_NIMBLE_ENABLE_GAP_EVENT_CODE_TEXT)
+  switch (eventType) {
+    case BLE_GAP_EVENT_CONNECT:  //0
+      return "BLE_GAP_EVENT_CONNECT ";
+
+    case BLE_GAP_EVENT_DISCONNECT:  //1
+      return "BLE_GAP_EVENT_DISCONNECT";
+
+    case BLE_GAP_EVENT_CONN_UPDATE:  //3
+      return "BLE_GAP_EVENT_CONN_UPDATE";
+
+    case BLE_GAP_EVENT_CONN_UPDATE_REQ:  //4
+      return "BLE_GAP_EVENT_CONN_UPDATE_REQ";
+
+    case BLE_GAP_EVENT_L2CAP_UPDATE_REQ:  //5
+      return "BLE_GAP_EVENT_L2CAP_UPDATE_REQ";
+
+    case BLE_GAP_EVENT_TERM_FAILURE:  //6
+      return "BLE_GAP_EVENT_TERM_FAILURE";
+
+    case BLE_GAP_EVENT_DISC:  //7
+      return "BLE_GAP_EVENT_DISC";
+
+    case BLE_GAP_EVENT_DISC_COMPLETE:  //8
+      return "BLE_GAP_EVENT_DISC_COMPLETE";
+
+    case BLE_GAP_EVENT_ADV_COMPLETE:  //9
+      return "BLE_GAP_EVENT_ADV_COMPLETE";
+
+    case BLE_GAP_EVENT_ENC_CHANGE:  //10
+      return "BLE_GAP_EVENT_ENC_CHANGE";
+
+    case BLE_GAP_EVENT_PASSKEY_ACTION:  //11
+      return "BLE_GAP_EVENT_PASSKEY_ACTION";
+
+    case BLE_GAP_EVENT_NOTIFY_RX:  //12
+      return "BLE_GAP_EVENT_NOTIFY_RX";
+
+    case BLE_GAP_EVENT_NOTIFY_TX:  //13
+      return "BLE_GAP_EVENT_NOTIFY_TX";
+
+    case BLE_GAP_EVENT_SUBSCRIBE:  //14
+      return "BLE_GAP_EVENT_SUBSCRIBE";
+
+    case BLE_GAP_EVENT_MTU:  //15
+      return "BLE_GAP_EVENT_MTU";
+
+    case BLE_GAP_EVENT_IDENTITY_RESOLVED:  //16
+      return "BLE_GAP_EVENT_IDENTITY_RESOLVED";
+
+    case BLE_GAP_EVENT_REPEAT_PAIRING:  //17
+      return "BLE_GAP_EVENT_REPEAT_PAIRING";
+
+    case BLE_GAP_EVENT_PHY_UPDATE_COMPLETE:  //18
+      return "BLE_GAP_EVENT_PHY_UPDATE_COMPLETE";
+
+    case BLE_GAP_EVENT_EXT_DISC:  //19
+      return "BLE_GAP_EVENT_EXT_DISC";
+#ifdef BLE_GAP_EVENT_PERIODIC_SYNC     // IDF 4.0 does not support these
+    case BLE_GAP_EVENT_PERIODIC_SYNC:  //20
+      return "BLE_GAP_EVENT_PERIODIC_SYNC";
+
+    case BLE_GAP_EVENT_PERIODIC_REPORT:  //21
+      return "BLE_GAP_EVENT_PERIODIC_REPORT";
+
+    case BLE_GAP_EVENT_PERIODIC_SYNC_LOST:  //22
+      return "BLE_GAP_EVENT_PERIODIC_SYNC_LOST";
+
+    case BLE_GAP_EVENT_SCAN_REQ_RCVD:  //23
+      return "BLE_GAP_EVENT_SCAN_REQ_RCVD";
+#endif
+    default: log_d("gapEventToString: Unknown event type %d 0x%.2x", eventType, eventType); return "Unknown event type";
+  }
+#else   // #if defined(CONFIG_NIMBLE_ENABLE_GAP_EVENT_CODE_TEXT)
+  return "";
+#endif  // #if defined(CONFIG_NIMBLE_ENABLE_GAP_EVENT_CODE_TEXT)
+}  // gapEventToString
+
+/**
+ * @brief Convert characteristic properties into a string representation.
+ * @param [in] prop Characteristic properties.
+ * @return A string representation of characteristic properties.
+ */
+String BLEUtils::characteristicPropertiesToString(uint8_t prop) {
+  String res = "broadcast: ";
+  res += ((prop & BLE_GATT_CHR_PROP_BROADCAST) ? "1" : "0");
+  res += ", read: ";
+  res += ((prop & BLE_GATT_CHR_PROP_READ) ? "1" : "0");
+  res += ", write_nr: ";
+  res += ((prop & BLE_GATT_CHR_PROP_WRITE_NO_RSP) ? "1" : "0");
+  res += ", write: ";
+  res += ((prop & BLE_GATT_CHR_PROP_WRITE) ? "1" : "0");
+  res += ", notify: ";
+  res += ((prop & BLE_GATT_CHR_PROP_NOTIFY) ? "1" : "0");
+  res += ", indicate: ";
+  res += ((prop & BLE_GATT_CHR_PROP_INDICATE) ? "1" : "0");
+  res += ", auth_sign_write: ";
+  res += ((prop & BLE_GATT_CHR_PROP_AUTH_SIGN_WRITE) ? "1" : "0");
+  res += ", extended: ";
+  res += ((prop & BLE_GATT_CHR_PROP_EXTENDED) ? "1" : "0");
+  return res;
+}  // characteristicPropertiesToString
+
+/**
+ * @brief Blocks the calling task until released or timeout.
+ * @param [in] taskData A pointer to the task data structure.
+ * @param [in] timeout The time to wait in milliseconds.
+ * @return True if the task completed, false if the timeout was reached.
+ */
+bool BLEUtils::taskWait(const BLETaskData &taskData, uint32_t timeout) {
+  ble_npl_time_t ticks;
+  if (timeout == BLE_NPL_TIME_FOREVER) {
+    ticks = BLE_NPL_TIME_FOREVER;
+  } else {
+    ble_npl_time_ms_to_ticks(timeout, &ticks);
+  }
+
+  uint32_t notificationValue;
+  xTaskNotifyWait(0, TASK_BLOCK_BIT, &notificationValue, 0);
+  if (notificationValue & TASK_BLOCK_BIT) {
+    return true;
+  }
+
+  return xTaskNotifyWait(0, TASK_BLOCK_BIT, nullptr, ticks) == pdTRUE;
+}  // taskWait
+
+/**
+ * @brief Release a task.
+ * @param [in] taskData A pointer to the task data structure.
+ * @param [in] flags A return value to set in the task data structure.
+ */
+void BLEUtils::taskRelease(const BLETaskData &taskData, int flags) {
+  taskData.m_flags = flags;
+  if (taskData.m_pHandle != nullptr) {
+    xTaskNotify(static_cast<TaskHandle_t>(taskData.m_pHandle), TASK_BLOCK_BIT, eSetBits);
+  }
+}  // taskRelease
+
+#endif  // CONFIG_NIMBLE_ENABLED
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEUtils.h b/libraries/BLE/src/BLEUtils.h
index 7c6f58d284b..2689706b7a1 100644
--- a/libraries/BLE/src/BLEUtils.h
+++ b/libraries/BLE/src/BLEUtils.h
@@ -3,6 +3,10 @@
  *
  *  Created on: Mar 25, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLEUTILS_H_
@@ -11,24 +15,99 @@
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
-#include <esp_gattc_api.h>    // ESP32 BLE
-#include <esp_gatts_api.h>    // ESP32 BLE
-#include <esp_gap_ble_api.h>  // ESP32 BLE
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/*****************************************************************************
+ *                             Common includes                               *
+ *****************************************************************************/
+
 #include <string>
-#include "BLEClient.h"
+#include "BLEAddress.h"
+#include "WString.h"
+#include <freertos/task.h>
+
+/*****************************************************************************
+ *                            Bluedroid includes                             *
+ *****************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+#include <esp_gattc_api.h>
+#include <esp_gatts_api.h>
+#include <esp_gap_ble_api.h>
+#endif
+
+/*****************************************************************************
+ *                              NimBLE includes                              *
+ *****************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+#include <stdlib.h>
+#include <climits>
+#include <host/ble_gap.h>
+#endif
+
+/*****************************************************************************
+ *                             Common types                                  *
+ *****************************************************************************/
+
+typedef struct {
+  void *peer_device;  // peer device BLEClient or BLEServer
+  bool connected;     // connection status
+  uint16_t mtu;       // negotiated MTU per peer device
+} conn_status_t;
+
+/*****************************************************************************
+ *                             NimBLE types                                  *
+ *****************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+
+/**
+ * @brief A structure to hold data for a task that is waiting for a response.
+ * @details This structure is used in conjunction with BLEUtils::taskWait() and BLEUtils::taskRelease().
+ * All items are optional, the m_pHandle will be set in taskWait().
+ */
+struct BLETaskData {
+  BLETaskData(void *pInstance = nullptr, int flags = 0, void *buf = nullptr);
+  ~BLETaskData();
+  void *m_pInstance{nullptr};
+  mutable int m_flags{0};
+  void *m_pBuf{nullptr};
+
+private:
+  mutable void *m_pHandle{nullptr};  // semaphore or task handle
+  friend class BLEUtils;
+};
+
+#endif
+
+/*****************************************************************************
+ *                         Forward declarations                              *
+ *****************************************************************************/
+
+class BLEClient;
 
 /**
  * @brief A set of general %BLE utilities.
  */
 class BLEUtils {
 public:
-  static const char *addressTypeToString(esp_ble_addr_type_t type);
-  static String adFlagsToString(uint8_t adFlags);
-  static const char *advTypeToString(uint8_t advType);
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   static char *buildHexData(uint8_t *target, uint8_t *source, uint8_t length);
   static String buildPrintData(uint8_t *source, size_t length);
-  static String characteristicPropertiesToString(esp_gatt_char_prop_t prop);
+  static const char *advDataTypeToString(uint8_t advType);
+  static String characteristicPropertiesToString(uint8_t prop);
+
+  /***************************************************************************
+   *                      Bluedroid public declarations                      *
+   ***************************************************************************/
+
+#if defined(CONFIG_BLUEDROID_ENABLED)
+  static const char *addressTypeToString(esp_ble_addr_type_t type);
+  static String adFlagsToString(uint8_t adFlags);
   static const char *devTypeToString(esp_bt_dev_type_t type);
   static esp_gatt_id_t buildGattId(esp_bt_uuid_t uuid, uint8_t inst_id = 0);
   static esp_gatt_srvc_id_t buildGattSrvcId(esp_gatt_id_t gattId, bool is_primary = true);
@@ -52,8 +131,22 @@ class BLEUtils {
   static void registerByAddress(BLEAddress address, BLEClient *pDevice);
   static void registerByConnId(uint16_t conn_id, BLEClient *pDevice);
   static const char *searchEventTypeToString(esp_gap_search_evt_t searchEvt);
+#endif
+
+  /***************************************************************************
+   *                        NimBLE public declarations                       *
+   ***************************************************************************/
+
+#if defined(CONFIG_NIMBLE_ENABLED)
+  static void dumpGapEvent(ble_gap_event *event, void *arg);
+  static const char *gapEventToString(uint8_t eventType);
+  static const char *returnCodeToString(int rc);
+  static int checkConnParams(ble_gap_conn_params *params);
+  static bool taskWait(const BLETaskData &taskData, uint32_t timeout);
+  static void taskRelease(const BLETaskData &taskData, int rc = 0);
+#endif
 };
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLEUTILS_H_ */
diff --git a/libraries/BLE/src/BLEValue.cpp b/libraries/BLE/src/BLEValue.cpp
index 26811c985ac..efc97697baa 100644
--- a/libraries/BLE/src/BLEValue.cpp
+++ b/libraries/BLE/src/BLEValue.cpp
@@ -3,15 +3,29 @@
  *
  *  Created on: Jul 17, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
+
 #include "soc/soc_caps.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/*****************************************************************************
+ *                             Common includes                               *
+ *****************************************************************************/
+
 #include "BLEValue.h"
 #include "esp32-hal-log.h"
 
+/*****************************************************************************
+ *                             Common functions                              *
+ *****************************************************************************/
+
 BLEValue::BLEValue() {
   m_accumulation = "";
   m_value = "";
@@ -120,5 +134,5 @@ void BLEValue::setValue(uint8_t *pData, size_t length) {
   m_value = String((char *)pData, length);
 }  // setValue
 
-#endif /* CONFIG_BLUEDROID_ENABLED */
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
diff --git a/libraries/BLE/src/BLEValue.h b/libraries/BLE/src/BLEValue.h
index f9c91bdcd4e..56a7a5bc4ec 100644
--- a/libraries/BLE/src/BLEValue.h
+++ b/libraries/BLE/src/BLEValue.h
@@ -3,22 +3,36 @@
  *
  *  Created on: Jul 17, 2017
  *      Author: kolban
+ *
+ *  Modified on: Feb 18, 2025
+ *      Author: lucasssvaz (based on kolban's and h2zero's work)
+ *      Description: Added support for NimBLE
  */
 
 #ifndef COMPONENTS_CPP_UTILS_BLEVALUE_H_
 #define COMPONENTS_CPP_UTILS_BLEVALUE_H_
+
 #include "soc/soc_caps.h"
-#include "WString.h"
 #if SOC_BLE_SUPPORTED
 
 #include "sdkconfig.h"
-#if defined(CONFIG_BLUEDROID_ENABLED)
+#if defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)
+
+/*****************************************************************************
+ *                              Common includes                              *
+ *****************************************************************************/
+
+#include "WString.h"
 
 /**
  * @brief The model of a %BLE value.
  */
 class BLEValue {
 public:
+  /***************************************************************************
+   *                       Common public declarations                        *
+   ***************************************************************************/
+
   BLEValue();
   void addPart(String part);
   void addPart(uint8_t *pData, size_t length);
@@ -33,10 +47,15 @@ class BLEValue {
   void setValue(uint8_t *pData, size_t length);
 
 private:
+  /***************************************************************************
+   *                        Common private properties                        *
+   ***************************************************************************/
+
   String m_accumulation;
   uint16_t m_readOffset;
   String m_value;
 };
-#endif /* CONFIG_BLUEDROID_ENABLED */
+
+#endif /* CONFIG_BLUEDROID_ENABLED || CONFIG_NIMBLE_ENABLED */
 #endif /* SOC_BLE_SUPPORTED */
 #endif /* COMPONENTS_CPP_UTILS_BLEVALUE_H_ */

From 36d049659bcea13e4e2afb4463e7f29bc998ffa3 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Tue, 24 Jun 2025 12:30:29 +0300
Subject: [PATCH 032/105] IDF release/v5.5 (#11504)

* IDF release/v5.5 4c3d086c

* fix(prov): Enable BLE provisioning with NimBLE

* fix(uart): idf 5.5 new gpio_iomux_* functions (#11507)

* fix(uart): idf 5.5 new gpio_iomux_* functions

* fix(uart): formatting and style

* fix(uart): commentaries style fix

* fix(uart): commentaries style fix

* fix(uart): commentaries style fix

* fix(uart): support to any idf 5.x version

* fix(uart): changing assert in order to avoid reset

* ci(pre-commit): Apply automatic fixes

---------

Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>

* IDF release/v5.5 cbe9388f

---------

Co-authored-by: Sugar Glider <rodrigo.garcia@espressif.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 cores/esp32/esp32-hal-uart.c                  | 19 ++++--
 .../WiFiProv/examples/WiFiProv/WiFiProv.ino   |  2 +-
 libraries/WiFiProv/src/WiFiProv.cpp           | 20 +++---
 libraries/WiFiProv/src/WiFiProv.h             |  4 +-
 package/package_esp32_index.template.json     | 68 +++++++++----------
 5 files changed, 62 insertions(+), 51 deletions(-)

diff --git a/cores/esp32/esp32-hal-uart.c b/cores/esp32/esp32-hal-uart.c
index 3e33c588c3b..6e5a22da9f8 100644
--- a/cores/esp32/esp32-hal-uart.c
+++ b/cores/esp32/esp32-hal-uart.c
@@ -317,13 +317,24 @@ static bool _uartTrySetIomuxPin(uart_port_t uart_num, int io_num, uint32_t idx)
   }
 
   // Assign the correct function to the GPIO.
-  assert(upin->iomux_func != -1);
+  if (upin->iomux_func == -1) {
+    log_e("IO#%d has bad IOMUX internal information. Switching to GPIO Matrix UART function.", io_num);
+    return false;
+  }
   if (uart_num < SOC_UART_HP_NUM) {
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
+    if (upin->input) {
+      gpio_iomux_input(io_num, upin->iomux_func, upin->signal);
+    } else {
+      gpio_iomux_output(io_num, upin->iomux_func);
+    }
+#else
     gpio_iomux_out(io_num, upin->iomux_func, false);
     // If the pin is input, we also have to redirect the signal, in order to bypass the GPIO matrix.
     if (upin->input) {
       gpio_iomux_in(io_num, upin->signal);
     }
+#endif
   }
 #if (SOC_UART_LP_NUM >= 1) && (SOC_RTCIO_PIN_COUNT >= 1)
   else {
@@ -1276,11 +1287,11 @@ bool uartSetClockSource(uint8_t uartNum, uart_sclk_t clkSrc) {
 #if SOC_UART_LP_NUM >= 1
   if (uart->num >= SOC_UART_HP_NUM) {
     switch (clkSrc) {
-      case UART_SCLK_XTAL:    uart->_uart_clock_source = LP_UART_SCLK_XTAL_D2; break;
+      case UART_SCLK_XTAL: uart->_uart_clock_source = LP_UART_SCLK_XTAL_D2; break;
 #if CONFIG_IDF_TARGET_ESP32C5
-      case UART_SCLK_RTC:     uart->_uart_clock_source = LP_UART_SCLK_RC_FAST; break;
+      case UART_SCLK_RTC: uart->_uart_clock_source = LP_UART_SCLK_RC_FAST; break;
 #else
-      case UART_SCLK_RTC:     uart->_uart_clock_source = LP_UART_SCLK_LP_FAST; break;
+      case UART_SCLK_RTC: uart->_uart_clock_source = LP_UART_SCLK_LP_FAST; break;
 #endif
       case UART_SCLK_DEFAULT:
       default:                uart->_uart_clock_source = LP_UART_SCLK_DEFAULT;
diff --git a/libraries/WiFiProv/examples/WiFiProv/WiFiProv.ino b/libraries/WiFiProv/examples/WiFiProv/WiFiProv.ino
index 76025d75770..2f7d8c5089f 100644
--- a/libraries/WiFiProv/examples/WiFiProv/WiFiProv.ino
+++ b/libraries/WiFiProv/examples/WiFiProv/WiFiProv.ino
@@ -62,7 +62,7 @@ void setup() {
   WiFi.onEvent(SysProvEvent);
 
 // BLE Provisioning using the ESP SoftAP Prov works fine for any BLE SoC, including ESP32, ESP32S3 and ESP32C3.
-#if CONFIG_BLUEDROID_ENABLED && !defined(USE_SOFT_AP)
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h") && !defined(USE_SOFT_AP)
   Serial.println("Begin Provisioning using BLE");
   // Sample uuid that user can pass during provisioning using BLE
   uint8_t uuid[16] = {0xb4, 0xdf, 0x5a, 0x1c, 0x3f, 0x6b, 0xf4, 0xbf, 0xea, 0x4a, 0x82, 0x03, 0x04, 0x90, 0x1a, 0x02};
diff --git a/libraries/WiFiProv/src/WiFiProv.cpp b/libraries/WiFiProv/src/WiFiProv.cpp
index 31337196b5f..f372caf0e49 100644
--- a/libraries/WiFiProv/src/WiFiProv.cpp
+++ b/libraries/WiFiProv/src/WiFiProv.cpp
@@ -34,7 +34,7 @@
 #endif
 
 #include <nvs_flash.h>
-#if CONFIG_BLUEDROID_ENABLED
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
 #include "network_provisioning/scheme_ble.h"
 #endif
 #include <network_provisioning/scheme_softap.h>
@@ -47,7 +47,7 @@
 
 bool wifiLowLevelInit(bool persistent);
 
-#if CONFIG_BLUEDROID_ENABLED
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
 static const uint8_t custom_service_uuid[16] = {
   0xb4, 0xdf, 0x5a, 0x1c, 0x3f, 0x6b, 0xf4, 0xbf, 0xea, 0x4a, 0x82, 0x03, 0x04, 0x90, 0x1a, 0x02,
 };
@@ -61,13 +61,13 @@ static void get_device_service_name(prov_scheme_t prov_scheme, char *service_nam
     log_e("esp_wifi_get_mac failed!");
     return;
   }
-#if CONFIG_IDF_TARGET_ESP32 && defined(CONFIG_BLUEDROID_ENABLED)
+#if CONFIG_IDF_TARGET_ESP32 && (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
   if (prov_scheme == NETWORK_PROV_SCHEME_BLE) {
     snprintf(service_name, max, "%s%02X%02X%02X", SERV_NAME_PREFIX_PROV, eth_mac[3], eth_mac[4], eth_mac[5]);
   } else {
 #endif
     snprintf(service_name, max, "%s%02X%02X%02X", SERV_NAME_PREFIX_PROV, eth_mac[3], eth_mac[4], eth_mac[5]);
-#if CONFIG_IDF_TARGET_ESP32 && defined(CONFIG_BLUEDROID_ENABLED)
+#if CONFIG_IDF_TARGET_ESP32 && (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
   }
 #endif
 }
@@ -78,20 +78,20 @@ void WiFiProvClass ::initProvision(prov_scheme_t prov_scheme, scheme_handler_t s
     return;
   }
   network_prov_mgr_config_t config;
-#if CONFIG_BLUEDROID_ENABLED
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
   if (prov_scheme == NETWORK_PROV_SCHEME_BLE) {
     config.scheme = network_prov_scheme_ble;
   } else {
 #endif
     config.scheme = network_prov_scheme_softap;
-#if CONFIG_BLUEDROID_ENABLED
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
   }
 
   if (scheme_handler == NETWORK_PROV_SCHEME_HANDLER_NONE) {
 #endif
     network_prov_event_handler_t scheme_event_handler = NETWORK_PROV_EVENT_HANDLER_NONE;
     memcpy(&config.scheme_event_handler, &scheme_event_handler, sizeof(network_prov_event_handler_t));
-#if CONFIG_BLUEDROID_ENABLED
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
   } else if (scheme_handler == NETWORK_PROV_SCHEME_HANDLER_FREE_BTDM) {
     network_prov_event_handler_t scheme_event_handler = NETWORK_PROV_SCHEME_BLE_EVENT_HANDLER_FREE_BTDM;
     memcpy(&config.scheme_event_handler, &scheme_event_handler, sizeof(network_prov_event_handler_t));
@@ -133,7 +133,7 @@ void WiFiProvClass ::beginProvision(
   }
   static char service_name_temp[32];
   if (provisioned == false) {
-#if CONFIG_BLUEDROID_ENABLED
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
     if (prov_scheme == NETWORK_PROV_SCHEME_BLE) {
       service_key = NULL;
       if (uuid == NULL) {
@@ -148,7 +148,7 @@ void WiFiProvClass ::beginProvision(
       service_name = (const char *)service_name_temp;
     }
 
-#if CONFIG_BLUEDROID_ENABLED
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
     if (prov_scheme == NETWORK_PROV_SCHEME_BLE) {
       log_i("Starting AP using BLE. service_name : %s, pop : %s", service_name, pop);
     } else {
@@ -158,7 +158,7 @@ void WiFiProvClass ::beginProvision(
       } else {
         log_i("Starting provisioning AP using SOFTAP. service_name : %s, password : %s, pop : %s", service_name, service_key, pop);
       }
-#if CONFIG_BLUEDROID_ENABLED
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
     }
 #endif
     if (network_prov_mgr_start_provisioning(security, pop, service_name, service_key) != ESP_OK) {
diff --git a/libraries/WiFiProv/src/WiFiProv.h b/libraries/WiFiProv/src/WiFiProv.h
index b660f8cf064..d34727b6896 100644
--- a/libraries/WiFiProv/src/WiFiProv.h
+++ b/libraries/WiFiProv/src/WiFiProv.h
@@ -29,7 +29,7 @@
 //Select the scheme using which you want to provision
 typedef enum {
   NETWORK_PROV_SCHEME_SOFTAP,
-#if CONFIG_BLUEDROID_ENABLED
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
   NETWORK_PROV_SCHEME_BLE,
 #endif
   NETWORK_PROV_SCHEME_MAX
@@ -37,7 +37,7 @@ typedef enum {
 
 typedef enum {
   NETWORK_PROV_SCHEME_HANDLER_NONE,
-#if CONFIG_BLUEDROID_ENABLED
+#if (defined(CONFIG_BLUEDROID_ENABLED) || defined(CONFIG_NIMBLE_ENABLED)) && __has_include("esp_bt.h")
   NETWORK_PROV_SCHEME_HANDLER_FREE_BTDM,
   NETWORK_PROV_SCHEME_HANDLER_FREE_BLE,
   NETWORK_PROV_SCHEME_HANDLER_FREE_BT,
diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index 3ae2ff09ee6..1d753792b43 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-release_v5.5-28ac0243-v1"
+              "version": "idf-release_v5.5-cbe9388f-v1"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-release_v5.5-28ac0243-v1",
+          "version": "idf-release_v5.5-cbe9388f-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
-              "size": "405149394"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
+              "size": "421300036"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
-              "size": "405149394"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
+              "size": "421300036"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
-              "size": "405149394"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
+              "size": "421300036"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
-              "size": "405149394"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
+              "size": "421300036"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
-              "size": "405149394"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
+              "size": "421300036"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
-              "size": "405149394"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
+              "size": "421300036"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
-              "size": "405149394"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
+              "size": "421300036"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-28ac0243-v1.zip",
-              "checksum": "SHA-256:280401ea803d8a782c11ef4f96cfbf80eb12a0f51bd12eac9cb96d6c26489f6e",
-              "size": "405149394"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
+              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
+              "size": "421300036"
             }
           ]
         },

From d4e5c5f969aba994e3e1c1994348bffb9856e95a Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Thu, 3 Jul 2025 12:25:33 +0300
Subject: [PATCH 033/105] IDF release/v5.5 adb3f2a5 (#11543)

IDF release/v5.5 adb3f2a5
---
 package/package_esp32_index.template.json | 68 +++++++++++------------
 1 file changed, 34 insertions(+), 34 deletions(-)

diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index 1d753792b43..a02be509094 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-release_v5.5-cbe9388f-v1"
+              "version": "idf-release_v5.5-adb3f2a5-v1"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-release_v5.5-cbe9388f-v1",
+          "version": "idf-release_v5.5-adb3f2a5-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
-              "size": "421300036"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
+              "size": "430508851"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
-              "size": "421300036"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
+              "size": "430508851"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
-              "size": "421300036"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
+              "size": "430508851"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
-              "size": "421300036"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
+              "size": "430508851"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
-              "size": "421300036"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
+              "size": "430508851"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
-              "size": "421300036"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
+              "size": "430508851"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
-              "size": "421300036"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
+              "size": "430508851"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cbe9388f-v1.zip",
-              "checksum": "SHA-256:b737ffb86a1b377db12dd610d06936ca8d85d877c872f532a68f6f0a3f666a3f",
-              "size": "421300036"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
+              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
+              "size": "430508851"
             }
           ]
         },

From c2d23258f197d0f3422c31e75ab848919fc097bb Mon Sep 17 00:00:00 2001
From: Sugar Glider <rodrigo.garcia@espressif.com>
Date: Thu, 3 Jul 2025 06:25:51 -0300
Subject: [PATCH 034/105] feat(matter): enables BLE Matter commissioning with
 NimBLE (#11537)

* feat(matter): enables BLE Matter commissioning with NimBLE

* fix(matter): commentary typo and formatting

* fix(matter): commentary typo and formatting

* fix(matter): removes forcing second network clustter

* fix(matter): adds matter source code to CMakeLists.txt

* ci(pre-commit): Apply automatic fixes

---------

Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 CMakeLists.txt                                |   3 +-
 .../MatterColorLight/MatterColorLight.ino     |  15 +-
 .../MatterCommissionTest.ino                  |  13 +-
 .../MatterComposedLights.ino                  |  13 +-
 .../MatterContactSensor.ino                   |  13 +-
 .../MatterDimmableLight.ino                   |  15 +-
 .../MatterEnhancedColorLight.ino              |  15 +-
 .../examples/MatterEvents/MatterEvents.ino    |   9 ++
 .../Matter/examples/MatterFan/MatterFan.ino   |  15 +-
 .../MatterHumiditySensor.ino                  |  13 +-
 .../examples/MatterMinimum/MatterMinimum.ino  |  11 +-
 .../MatterOccupancySensor.ino                 |  13 +-
 .../MatterOnIdentify/MatterOnIdentify.ino     |  13 +-
 .../MatterOnOffLight/MatterOnOffLight.ino     |  15 +-
 .../MatterOnOffPlugin/MatterOnOffPlugin.ino   |  15 +-
 .../MatterPressureSensor.ino                  |  13 +-
 .../MatterSmartButon/MatterSmartButon.ino     |  15 +-
 .../MatterTemperatureLight.ino                |  15 +-
 .../MatterTemperatureSensor.ino               |  13 +-
 .../MatterThermostat/MatterThermostat.ino     |  13 +-
 libraries/Matter/src/Matter.cpp               |  18 ++-
 libraries/Matter/src/Matter.h                 |   2 +-
 libraries/Matter/src/MatterEndPoint.cpp       | 139 ++++++++++++++++++
 libraries/Matter/src/MatterEndPoint.h         | 117 +++++----------
 .../src/MatterEndpoints/MatterColorLight.cpp  |   2 +-
 .../src/MatterEndpoints/MatterColorLight.h    |   2 +-
 .../MatterColorTemperatureLight.cpp           |   2 +-
 .../MatterColorTemperatureLight.h             |   2 +-
 .../MatterEndpoints/MatterContactSensor.cpp   |   3 +-
 .../src/MatterEndpoints/MatterContactSensor.h |   2 +-
 .../MatterEndpoints/MatterDimmableLight.cpp   |   2 +-
 .../src/MatterEndpoints/MatterDimmableLight.h |   2 +-
 .../MatterEnhancedColorLight.cpp              |   2 +-
 .../MatterEnhancedColorLight.h                |   2 +-
 .../Matter/src/MatterEndpoints/MatterFan.cpp  |   3 +-
 .../Matter/src/MatterEndpoints/MatterFan.h    |   2 +-
 .../MatterEndpoints/MatterGenericSwitch.cpp   |   3 +-
 .../src/MatterEndpoints/MatterGenericSwitch.h |   2 +-
 .../MatterEndpoints/MatterHumiditySensor.cpp  |   3 +-
 .../MatterEndpoints/MatterHumiditySensor.h    |   2 +-
 .../MatterEndpoints/MatterOccupancySensor.cpp |   3 +-
 .../MatterEndpoints/MatterOccupancySensor.h   |   2 +-
 .../src/MatterEndpoints/MatterOnOffLight.cpp  |   3 +-
 .../src/MatterEndpoints/MatterOnOffLight.h    |   2 +-
 .../src/MatterEndpoints/MatterOnOffPlugin.cpp |   3 +-
 .../src/MatterEndpoints/MatterOnOffPlugin.h   |   2 +-
 .../MatterEndpoints/MatterPressureSensor.cpp  |   3 +-
 .../MatterEndpoints/MatterPressureSensor.h    |   2 +-
 .../MatterTemperatureSensor.cpp               |   3 +-
 .../MatterEndpoints/MatterTemperatureSensor.h |   2 +-
 .../src/MatterEndpoints/MatterThermostat.cpp  |   3 +-
 .../src/MatterEndpoints/MatterThermostat.h    |   2 +-
 52 files changed, 447 insertions(+), 155 deletions(-)
 create mode 100644 libraries/Matter/src/MatterEndPoint.cpp

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 20cfc2b0955..e71911c1e38 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -184,7 +184,8 @@ set(ARDUINO_LIBRARY_Matter_SRCS
   libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp
   libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.cpp
   libraries/Matter/src/MatterEndpoints/MatterThermostat.cpp
-  libraries/Matter/src/Matter.cpp)
+  libraries/Matter/src/Matter.cpp
+  libraries/Matter/src/MatterEndPoint.cpp)
 
 set(ARDUINO_LIBRARY_PPP_SRCS
   libraries/PPP/src/PPP.cpp
diff --git a/libraries/Matter/examples/MatterColorLight/MatterColorLight.ino b/libraries/Matter/examples/MatterColorLight/MatterColorLight.ino
index f3e45887576..e28c96e266c 100644
--- a/libraries/Matter/examples/MatterColorLight/MatterColorLight.ino
+++ b/libraries/Matter/examples/MatterColorLight/MatterColorLight.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -14,16 +14,22 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 #include <Preferences.h>
 
 // List of Matter Endpoints for this Node
 // Color Light Endpoint
 MatterColorLight ColorLight;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // it will keep last OnOff & HSV Color state stored, using Preferences
 Preferences matterPref;
@@ -81,6 +87,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // We start by connecting to a WiFi network
   Serial.print("Connecting to ");
   Serial.println(ssid);
@@ -95,6 +103,7 @@ void setup() {
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   delay(500);
+#endif
 
   // Initialize Matter EndPoint
   matterPref.begin("MatterPrefs", false);
@@ -121,7 +130,7 @@ void setup() {
   Matter.begin();
   // This may be a restart of a already commissioned Matter accessory
   if (Matter.isDeviceCommissioned()) {
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
     Serial.printf(
       "Initial state: %s | RGB Color: (%d,%d,%d) \r\n", ColorLight ? "ON" : "OFF", ColorLight.getColorRGB().r, ColorLight.getColorRGB().g,
       ColorLight.getColorRGB().b
@@ -154,7 +163,7 @@ void loop() {
     );
     // configure the Light based on initial on-off state and its color
     ColorLight.updateAccessory();
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 
   // A button is also used to control the light
diff --git a/libraries/Matter/examples/MatterCommissionTest/MatterCommissionTest.ino b/libraries/Matter/examples/MatterCommissionTest/MatterCommissionTest.ino
index 0e93ed6d155..aa593758548 100644
--- a/libraries/Matter/examples/MatterCommissionTest/MatterCommissionTest.ino
+++ b/libraries/Matter/examples/MatterCommissionTest/MatterCommissionTest.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -14,19 +14,27 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
 // List of Matter Endpoints for this Node
 // On/Off Light Endpoint
 MatterOnOffLight OnOffLight;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 void setup() {
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // We start by connecting to a WiFi network
   Serial.print("Connecting to ");
   Serial.println(ssid);
@@ -41,6 +49,7 @@ void setup() {
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   delay(500);
+#endif
 
   // Initialize at least one Matter EndPoint
   OnOffLight.begin();
@@ -64,7 +73,7 @@ void loop() {
       Serial.println("Matter Fabric not commissioned yet. Waiting for commissioning.");
     }
   }
-  Serial.println("Matter Node is commissioned and connected to Wi-Fi.");
+  Serial.println("Matter Node is commissioned and connected to the network.");
   Serial.println("====> Decommissioning in 30 seconds. <====");
   delay(30000);
   Matter.decommission();
diff --git a/libraries/Matter/examples/MatterComposedLights/MatterComposedLights.ino b/libraries/Matter/examples/MatterComposedLights/MatterComposedLights.ino
index b98cc8e19c9..48a6db8bedd 100644
--- a/libraries/Matter/examples/MatterComposedLights/MatterComposedLights.ino
+++ b/libraries/Matter/examples/MatterComposedLights/MatterComposedLights.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -14,7 +14,10 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
 // List of Matter Endpoints for this Node
 // There will be 3 On/Off Light Endpoints in the same Node
@@ -22,9 +25,12 @@ MatterOnOffLight Light1;
 MatterDimmableLight Light2;
 MatterColorLight Light3;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // set your board USER BUTTON pin here -  USED to decommission the Matter Node
 const uint8_t buttonPin = BOOT_PIN;  // Set your pin here. Using BOOT Button.
@@ -56,6 +62,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // We start by connecting to a WiFi network
   Serial.print("Connecting to ");
   Serial.println(ssid);
@@ -71,6 +79,7 @@ void setup() {
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   delay(500);
+#endif
 
   // Initialize all 3 Matter EndPoints
   Light1.begin();
@@ -103,7 +112,7 @@ void loop() {
         Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
       }
     }
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 
   //displays the Light state every 5 seconds
diff --git a/libraries/Matter/examples/MatterContactSensor/MatterContactSensor.ino b/libraries/Matter/examples/MatterContactSensor/MatterContactSensor.ino
index e4c41460d3a..6472012a2ff 100644
--- a/libraries/Matter/examples/MatterContactSensor/MatterContactSensor.ino
+++ b/libraries/Matter/examples/MatterContactSensor/MatterContactSensor.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -30,15 +30,21 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
 // List of Matter Endpoints for this Node
 // Matter Contact Sensor Endpoint
 MatterContactSensor ContactSensor;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // LED will be used to indicate the Contact Sensor state
 // set your board RGB LED pin here
@@ -67,6 +73,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // Manually connect to WiFi
   WiFi.begin(ssid, password);
   // Wait for connection
@@ -75,6 +83,7 @@ void setup() {
     Serial.print(".");
   }
   Serial.println();
+#endif
 
   // set initial contact sensor state as false (default)
   ContactSensor.begin();
@@ -99,7 +108,7 @@ void setup() {
         Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
       }
     }
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 }
 
diff --git a/libraries/Matter/examples/MatterDimmableLight/MatterDimmableLight.ino b/libraries/Matter/examples/MatterDimmableLight/MatterDimmableLight.ino
index 79751905c20..2b853b25677 100644
--- a/libraries/Matter/examples/MatterDimmableLight/MatterDimmableLight.ino
+++ b/libraries/Matter/examples/MatterDimmableLight/MatterDimmableLight.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -14,16 +14,22 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 #include <Preferences.h>
 
 // List of Matter Endpoints for this Node
 // Dimmable Light Endpoint
 MatterDimmableLight DimmableLight;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // it will keep last OnOff & Brightness state stored, using Preferences
 Preferences matterPref;
@@ -77,6 +83,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // We start by connecting to a WiFi network
   Serial.print("Connecting to ");
   Serial.println(ssid);
@@ -91,6 +99,7 @@ void setup() {
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   delay(500);
+#endif
 
   // Initialize Matter EndPoint
   matterPref.begin("MatterPrefs", false);
@@ -116,7 +125,7 @@ void setup() {
   Matter.begin();
   // This may be a restart of a already commissioned Matter accessory
   if (Matter.isDeviceCommissioned()) {
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
     Serial.printf("Initial state: %s | brightness: %d\r\n", DimmableLight ? "ON" : "OFF", DimmableLight.getBrightness());
     // configure the Light based on initial on-off state and brightness
     DimmableLight.updateAccessory();
@@ -143,7 +152,7 @@ void loop() {
     Serial.printf("Initial state: %s | brightness: %d\r\n", DimmableLight ? "ON" : "OFF", DimmableLight.getBrightness());
     // configure the Light based on initial on-off state and brightness
     DimmableLight.updateAccessory();
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 
   // A button is also used to control the light
diff --git a/libraries/Matter/examples/MatterEnhancedColorLight/MatterEnhancedColorLight.ino b/libraries/Matter/examples/MatterEnhancedColorLight/MatterEnhancedColorLight.ino
index 8e12581fdf2..ac22ae768c5 100644
--- a/libraries/Matter/examples/MatterEnhancedColorLight/MatterEnhancedColorLight.ino
+++ b/libraries/Matter/examples/MatterEnhancedColorLight/MatterEnhancedColorLight.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -14,16 +14,22 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 #include <Preferences.h>
 
 // List of Matter Endpoints for this Node
 // Color Light Endpoint
 MatterEnhancedColorLight EnhancedColorLight;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // It will use HSV color to control all Matter Attribute Changes
 HsvColor_t currentHSVColor = {0, 0, 0};
@@ -85,6 +91,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // We start by connecting to a WiFi network
   Serial.print("Connecting to ");
   Serial.println(ssid);
@@ -99,6 +107,7 @@ void setup() {
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   delay(500);
+#endif
 
   // Initialize Matter EndPoint
   matterPref.begin("MatterPrefs", false);
@@ -143,7 +152,7 @@ void setup() {
   Matter.begin();
   // This may be a restart of a already commissioned Matter accessory
   if (Matter.isDeviceCommissioned()) {
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
     Serial.printf(
       "Initial state: %s | RGB Color: (%d,%d,%d) \r\n", EnhancedColorLight ? "ON" : "OFF", EnhancedColorLight.getColorRGB().r,
       EnhancedColorLight.getColorRGB().g, EnhancedColorLight.getColorRGB().b
@@ -176,7 +185,7 @@ void loop() {
     );
     // configure the Light based on initial on-off state and its color
     EnhancedColorLight.updateAccessory();
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 
   // A button is also used to control the light
diff --git a/libraries/Matter/examples/MatterEvents/MatterEvents.ino b/libraries/Matter/examples/MatterEvents/MatterEvents.ino
index dac599bf9fa..f33b13cf7fb 100644
--- a/libraries/Matter/examples/MatterEvents/MatterEvents.ino
+++ b/libraries/Matter/examples/MatterEvents/MatterEvents.ino
@@ -14,11 +14,17 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // List of Matter Endpoints for this Node
 // On/Off Light Endpoint
@@ -119,6 +125,8 @@ void setup() {
     delay(10);  // Wait for Serial to initialize
   }
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // We start by connecting to a WiFi network
   Serial.print("Connecting to ");
   Serial.println(ssid);
@@ -134,6 +142,7 @@ void setup() {
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   delay(500);
+#endif
 
   // Initialize at least one Matter EndPoint
   OnOffLight.begin();
diff --git a/libraries/Matter/examples/MatterFan/MatterFan.ino b/libraries/Matter/examples/MatterFan/MatterFan.ino
index 705aa4853da..ac620167a40 100644
--- a/libraries/Matter/examples/MatterFan/MatterFan.ino
+++ b/libraries/Matter/examples/MatterFan/MatterFan.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -14,15 +14,21 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
 // List of Matter Endpoints for this Node
 // Fan Endpoint - On/Off control + Speed Percent Control + Fan Modes
 MatterFan Fan;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // set your board USER BUTTON pin here - used for toggling On/Off and decommission the Matter Node
 const uint8_t buttonPin = BOOT_PIN;  // Set your pin here. Using BOOT Button.
@@ -76,6 +82,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // We start by connecting to a WiFi network
   Serial.print("Connecting to ");
   Serial.println(ssid);
@@ -90,6 +98,7 @@ void setup() {
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   delay(500);
+#endif
 
   // On Boot or Reset, Fan is set at 0% speed, OFF, changing between OFF, ON, SMART and HIGH
   Fan.begin(0, MatterFan::FAN_MODE_OFF, MatterFan::FAN_MODE_SEQ_OFF_HIGH);
@@ -141,7 +150,7 @@ void setup() {
   Matter.begin();
   // This may be a restart of a already commissioned Matter accessory
   if (Matter.isDeviceCommissioned()) {
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 }
 
@@ -162,7 +171,7 @@ void loop() {
         Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
       }
     }
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 
   // A builtin button is used to trigger and send a command to the Matter Controller
diff --git a/libraries/Matter/examples/MatterHumiditySensor/MatterHumiditySensor.ino b/libraries/Matter/examples/MatterHumiditySensor/MatterHumiditySensor.ino
index 1c7889db849..3149cf1dfbe 100644
--- a/libraries/Matter/examples/MatterHumiditySensor/MatterHumiditySensor.ino
+++ b/libraries/Matter/examples/MatterHumiditySensor/MatterHumiditySensor.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -21,15 +21,21 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
 // List of Matter Endpoints for this Node
 // Matter Humidity Sensor Endpoint
 MatterHumiditySensor SimulatedHumiditySensor;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // set your board USER BUTTON pin here - decommissioning button
 const uint8_t buttonPin = BOOT_PIN;  // Set your pin here. Using BOOT Button.
@@ -60,6 +66,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // Manually connect to WiFi
   WiFi.begin(ssid, password);
   // Wait for connection
@@ -68,6 +76,7 @@ void setup() {
     Serial.print(".");
   }
   Serial.println();
+#endif
 
   // set initial humidity sensor measurement
   // Simulated Sensor - it shall initially print 95% and then move to the 10% to 30% humidity range
@@ -92,7 +101,7 @@ void setup() {
         Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
       }
     }
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 }
 
diff --git a/libraries/Matter/examples/MatterMinimum/MatterMinimum.ino b/libraries/Matter/examples/MatterMinimum/MatterMinimum.ino
index db591ee2226..31599ad10cb 100644
--- a/libraries/Matter/examples/MatterMinimum/MatterMinimum.ino
+++ b/libraries/Matter/examples/MatterMinimum/MatterMinimum.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -22,15 +22,21 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
 // List of Matter Endpoints for this Node
 // Single On/Off Light Endpoint - at least one per node
 MatterOnOffLight OnOffLight;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // Light GPIO that can be controlled by Matter APP
 #ifdef LED_BUILTIN
@@ -62,6 +68,8 @@ void setup() {
   // Initialize the LED GPIO
   pinMode(ledPin, OUTPUT);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // Manually connect to WiFi
   WiFi.begin(ssid, password);
   // Wait for connection
@@ -73,6 +81,7 @@ void setup() {
     delay(500);
   }
   Serial.println();
+#endif
 
   // Initialize at least one Matter EndPoint
   OnOffLight.begin();
diff --git a/libraries/Matter/examples/MatterOccupancySensor/MatterOccupancySensor.ino b/libraries/Matter/examples/MatterOccupancySensor/MatterOccupancySensor.ino
index 333f178e9de..ecab016b473 100644
--- a/libraries/Matter/examples/MatterOccupancySensor/MatterOccupancySensor.ino
+++ b/libraries/Matter/examples/MatterOccupancySensor/MatterOccupancySensor.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -28,15 +28,21 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
 // List of Matter Endpoints for this Node
 // Matter Occupancy Sensor Endpoint
 MatterOccupancySensor OccupancySensor;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // set your board USER BUTTON pin here - decommissioning only
 const uint8_t buttonPin = BOOT_PIN;  // Set your pin here. Using BOOT Button.
@@ -52,6 +58,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // Manually connect to WiFi
   WiFi.begin(ssid, password);
   // Wait for connection
@@ -60,6 +68,7 @@ void setup() {
     Serial.print(".");
   }
   Serial.println();
+#endif
 
   // set initial occupancy sensor state as false and connected to a PIR sensor type (default)
   OccupancySensor.begin();
@@ -83,7 +92,7 @@ void setup() {
         Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
       }
     }
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 }
 
diff --git a/libraries/Matter/examples/MatterOnIdentify/MatterOnIdentify.ino b/libraries/Matter/examples/MatterOnIdentify/MatterOnIdentify.ino
index b2e77900e95..ec7129ecad9 100644
--- a/libraries/Matter/examples/MatterOnIdentify/MatterOnIdentify.ino
+++ b/libraries/Matter/examples/MatterOnIdentify/MatterOnIdentify.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -26,15 +26,21 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
 // List of Matter Endpoints for this Node
 // Single On/Off Light Endpoint - at least one per node
 MatterOnOffLight OnOffLight;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // Light GPIO that can be controlled by Matter APP
 #ifdef LED_BUILTIN
@@ -88,6 +94,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // Manually connect to WiFi
   WiFi.begin(ssid, password);
   // Wait for connection
@@ -96,6 +104,7 @@ void setup() {
     Serial.print(".");
   }
   Serial.println();
+#endif
 
   // Initialize at least one Matter EndPoint
   OnOffLight.begin();
@@ -125,7 +134,7 @@ void setup() {
         Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
       }
     }
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 }
 
diff --git a/libraries/Matter/examples/MatterOnOffLight/MatterOnOffLight.ino b/libraries/Matter/examples/MatterOnOffLight/MatterOnOffLight.ino
index 5faa0a385b0..3310cb8c4e9 100644
--- a/libraries/Matter/examples/MatterOnOffLight/MatterOnOffLight.ino
+++ b/libraries/Matter/examples/MatterOnOffLight/MatterOnOffLight.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -14,12 +14,18 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 #include <Preferences.h>
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // List of Matter Endpoints for this Node
 // On/Off Light Endpoint
@@ -68,6 +74,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // We start by connecting to a WiFi network
   Serial.print("Connecting to ");
   Serial.println(ssid);
@@ -82,6 +90,7 @@ void setup() {
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   delay(500);
+#endif
 
   // Initialize Matter EndPoint
   matterPref.begin("MatterPrefs", false);
@@ -93,7 +102,7 @@ void setup() {
   Matter.begin();
   // This may be a restart of a already commissioned Matter accessory
   if (Matter.isDeviceCommissioned()) {
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
     Serial.printf("Initial state: %s\r\n", OnOffLight.getOnOff() ? "ON" : "OFF");
     OnOffLight.updateAccessory();  // configure the Light based on initial state
   }
@@ -118,7 +127,7 @@ void loop() {
     }
     Serial.printf("Initial state: %s\r\n", OnOffLight.getOnOff() ? "ON" : "OFF");
     OnOffLight.updateAccessory();  // configure the Light based on initial state
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 
   // A button is also used to control the light
diff --git a/libraries/Matter/examples/MatterOnOffPlugin/MatterOnOffPlugin.ino b/libraries/Matter/examples/MatterOnOffPlugin/MatterOnOffPlugin.ino
index d14e2189ec1..372874ddc9a 100644
--- a/libraries/Matter/examples/MatterOnOffPlugin/MatterOnOffPlugin.ino
+++ b/libraries/Matter/examples/MatterOnOffPlugin/MatterOnOffPlugin.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -14,16 +14,22 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 #include <Preferences.h>
 
 // List of Matter Endpoints for this Node
 // On/Off Plugin Endpoint
 MatterOnOffPlugin OnOffPlugin;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // it will keep last OnOff state stored, using Preferences
 Preferences matterPref;
@@ -67,6 +73,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // We start by connecting to a WiFi network
   Serial.print("Connecting to ");
   Serial.println(ssid);
@@ -80,6 +88,7 @@ void setup() {
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   delay(500);
+#endif
 
   // Initialize Matter EndPoint
   matterPref.begin("MatterPrefs", false);
@@ -91,7 +100,7 @@ void setup() {
   Matter.begin();
   // This may be a restart of a already commissioned Matter accessory
   if (Matter.isDeviceCommissioned()) {
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
     Serial.printf("Initial state: %s\r\n", OnOffPlugin.getOnOff() ? "ON" : "OFF");
     OnOffPlugin.updateAccessory();  // configure the Plugin based on initial state
   }
@@ -116,7 +125,7 @@ void loop() {
     }
     Serial.printf("Initial state: %s\r\n", OnOffPlugin.getOnOff() ? "ON" : "OFF");
     OnOffPlugin.updateAccessory();  // configure the Plugin based on initial state
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 
   // Check if the button has been pressed
diff --git a/libraries/Matter/examples/MatterPressureSensor/MatterPressureSensor.ino b/libraries/Matter/examples/MatterPressureSensor/MatterPressureSensor.ino
index db035e951c9..0a097ec979b 100644
--- a/libraries/Matter/examples/MatterPressureSensor/MatterPressureSensor.ino
+++ b/libraries/Matter/examples/MatterPressureSensor/MatterPressureSensor.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -21,15 +21,21 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
 // List of Matter Endpoints for this Node
 // Matter Pressure Sensor Endpoint
 MatterPressureSensor SimulatedPressureSensor;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // set your board USER BUTTON pin here - decommissioning button
 const uint8_t buttonPin = BOOT_PIN;  // Set your pin here. Using BOOT Button.
@@ -60,6 +66,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // Manually connect to WiFi
   WiFi.begin(ssid, password);
   // Wait for connection
@@ -68,6 +76,7 @@ void setup() {
     Serial.print(".");
   }
   Serial.println();
+#endif
 
   // set initial pressure sensor measurement
   // Simulated Sensor - it shall initially print 900hPa and then move to the 950 to 1100 hPa as pressure range
@@ -92,7 +101,7 @@ void setup() {
         Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
       }
     }
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 }
 
diff --git a/libraries/Matter/examples/MatterSmartButon/MatterSmartButon.ino b/libraries/Matter/examples/MatterSmartButon/MatterSmartButon.ino
index f8da970595d..29caf00004c 100644
--- a/libraries/Matter/examples/MatterSmartButon/MatterSmartButon.ino
+++ b/libraries/Matter/examples/MatterSmartButon/MatterSmartButon.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -14,15 +14,21 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
 // List of Matter Endpoints for this Node
 // Generic Switch Endpoint - works as a smart button with a single click
 MatterGenericSwitch SmartButton;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // set your board USER BUTTON pin here
 const uint8_t buttonPin = BOOT_PIN;  // Set your pin here. Using BOOT Button.
@@ -43,6 +49,8 @@ void setup() {
   Serial.print("Connecting to ");
   Serial.println(ssid);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // Manually connect to WiFi
   WiFi.begin(ssid, password);
   // Wait for connection
@@ -54,6 +62,7 @@ void setup() {
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   delay(500);
+#endif
 
   // Initialize the Matter EndPoint
   SmartButton.begin();
@@ -62,7 +71,7 @@ void setup() {
   Matter.begin();
   // This may be a restart of a already commissioned Matter accessory
   if (Matter.isDeviceCommissioned()) {
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 }
 
@@ -83,7 +92,7 @@ void loop() {
         Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
       }
     }
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 
   // A builtin button is used to trigger a command to the Matter Controller
diff --git a/libraries/Matter/examples/MatterTemperatureLight/MatterTemperatureLight.ino b/libraries/Matter/examples/MatterTemperatureLight/MatterTemperatureLight.ino
index d46427591ab..b7fcc11d873 100644
--- a/libraries/Matter/examples/MatterTemperatureLight/MatterTemperatureLight.ino
+++ b/libraries/Matter/examples/MatterTemperatureLight/MatterTemperatureLight.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -14,16 +14,22 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 #include <Preferences.h>
 
 // List of Matter Endpoints for this Node
 // Color Temperature CW/WW Light Endpoint
 MatterColorTemperatureLight CW_WW_Light;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // it will keep last OnOff & Brightness state stored, using Preferences
 Preferences matterPref;
@@ -88,6 +94,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // We start by connecting to a WiFi network
   Serial.print("Connecting to ");
   Serial.println(ssid);
@@ -102,6 +110,7 @@ void setup() {
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   delay(500);
+#endif
 
   // Initialize Matter EndPoint
   matterPref.begin("MatterPrefs", false);
@@ -133,7 +142,7 @@ void setup() {
   Matter.begin();
   // This may be a restart of a already commissioned Matter accessory
   if (Matter.isDeviceCommissioned()) {
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
     Serial.printf(
       "Initial state: %s | brightness: %d | Color Temperature: %d mireds \r\n", CW_WW_Light ? "ON" : "OFF", CW_WW_Light.getBrightness(),
       CW_WW_Light.getColorTemperature()
@@ -166,7 +175,7 @@ void loop() {
     );
     // configure the Light based on initial on-off state and brightness
     CW_WW_Light.updateAccessory();
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 
   // A button is also used to control the light
diff --git a/libraries/Matter/examples/MatterTemperatureSensor/MatterTemperatureSensor.ino b/libraries/Matter/examples/MatterTemperatureSensor/MatterTemperatureSensor.ino
index 086155aeffe..46d6ace361f 100644
--- a/libraries/Matter/examples/MatterTemperatureSensor/MatterTemperatureSensor.ino
+++ b/libraries/Matter/examples/MatterTemperatureSensor/MatterTemperatureSensor.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -21,15 +21,21 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
 // List of Matter Endpoints for this Node
 // Matter Temperature Sensor Endpoint
 MatterTemperatureSensor SimulatedTemperatureSensor;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // set your board USER BUTTON pin here - decommissioning button
 const uint8_t buttonPin = BOOT_PIN;  // Set your pin here. Using BOOT Button.
@@ -60,6 +66,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // Manually connect to WiFi
   WiFi.begin(ssid, password);
   // Wait for connection
@@ -68,6 +76,7 @@ void setup() {
     Serial.print(".");
   }
   Serial.println();
+#endif
 
   // set initial temperature sensor measurement
   // Simulated Sensor - it shall initially print -25C and then move to the -10C to 10C range
@@ -92,7 +101,7 @@ void setup() {
         Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
       }
     }
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
   }
 }
 
diff --git a/libraries/Matter/examples/MatterThermostat/MatterThermostat.ino b/libraries/Matter/examples/MatterThermostat/MatterThermostat.ino
index bf76477c846..2c446f59e34 100644
--- a/libraries/Matter/examples/MatterThermostat/MatterThermostat.ino
+++ b/libraries/Matter/examples/MatterThermostat/MatterThermostat.ino
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -21,15 +21,21 @@
 
 // Matter Manager
 #include <Matter.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
 #include <WiFi.h>
+#endif
 
 // List of Matter Endpoints for this Node
 // Matter Thermostat Endpoint
 MatterThermostat SimulatedThermostat;
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
 // WiFi is manually set and started
 const char *ssid = "your-ssid";          // Change this to your WiFi SSID
 const char *password = "your-password";  // Change this to your WiFi password
+#endif
 
 // set your board USER BUTTON pin here - decommissioning button
 const uint8_t buttonPin = BOOT_PIN;  // Set your pin here. Using BOOT Button.
@@ -62,6 +68,8 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // Manually connect to WiFi
   WiFi.begin(ssid, password);
   // Wait for connection
@@ -70,6 +78,7 @@ void setup() {
     Serial.print(".");
   }
   Serial.println();
+#endif
 
   // Simulated Thermostat in COOLING and HEATING mode with Auto Mode to keep the temperature between setpoints
   // Auto Mode can only be used when the control sequence of operation is Cooling & Heating
@@ -94,7 +103,7 @@ void setup() {
         Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
       }
     }
-    Serial.println("Matter Node is commissioned and connected to Wi-Fi. Ready for use.");
+    Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
 
     // after commissioning, set initial thermostat parameters
     // start the thermostat in AUTO mode
diff --git a/libraries/Matter/src/Matter.cpp b/libraries/Matter/src/Matter.cpp
index b16edfd85c1..5ddacc1622c 100644
--- a/libraries/Matter/src/Matter.cpp
+++ b/libraries/Matter/src/Matter.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -17,6 +17,10 @@
 
 #include <Matter.h>
 #include <app/server/Server.h>
+#if CONFIG_ENABLE_MATTER_OVER_THREAD
+#include "esp_openthread_types.h"
+#include "platform/ESP32/OpenthreadLauncher.h"
+#endif
 
 using namespace esp_matter;
 using namespace esp_matter::attribute;
@@ -151,6 +155,18 @@ void ArduinoMatter::begin() {
     return;
   }
 
+#if CONFIG_ENABLE_MATTER_OVER_THREAD
+  // Set OpenThread platform config
+  esp_openthread_platform_config_t config;
+  memset(&config, 0, sizeof(esp_openthread_platform_config_t));
+  config.radio_config.radio_mode = RADIO_MODE_NATIVE;
+  config.host_config.host_connection_mode = HOST_CONNECTION_MODE_NONE;
+  config.port_config.storage_partition_name = "nvs";
+  config.port_config.netif_queue_size = 10;
+  config.port_config.task_queue_size = 10;
+  set_openthread_platform_config(&config);
+#endif
+
   /* Matter start */
   esp_err_t err = esp_matter::start(app_event_cb);
   if (err != ESP_OK) {
diff --git a/libraries/Matter/src/Matter.h b/libraries/Matter/src/Matter.h
index 682a0498076..09e59b4e04b 100644
--- a/libraries/Matter/src/Matter.h
+++ b/libraries/Matter/src/Matter.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndPoint.cpp b/libraries/Matter/src/MatterEndPoint.cpp
new file mode 100644
index 00000000000..ecf1acff579
--- /dev/null
+++ b/libraries/Matter/src/MatterEndPoint.cpp
@@ -0,0 +1,139 @@
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <sdkconfig.h>
+#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL
+
+#include <MatterEndPoint.h>
+
+uint16_t MatterEndPoint::secondary_network_endpoint_id = 0;
+
+// This function is called to create a secondary network interface endpoint.
+// It can be used for devices that support multiple network interfaces,
+// such as Ethernet, Thread and Wi-Fi.
+bool MatterEndPoint::createSecondaryNetworkInterface() {
+  if (secondary_network_endpoint_id != 0) {
+    log_v("Secondary network interface endpoint already exists with ID %d", secondary_network_endpoint_id);
+    return false;
+  }
+  // Create a secondary network interface endpoint
+  endpoint::secondary_network_interface::config_t secondary_network_interface_config;
+  secondary_network_interface_config.network_commissioning.feature_map = chip::to_underlying(
+    //chip::app::Clusters::NetworkCommissioning::Feature::kWiFiNetworkInterface) |
+    chip::app::Clusters::NetworkCommissioning::Feature::kThreadNetworkInterface
+  );
+  endpoint_t *endpoint = endpoint::secondary_network_interface::create(node::get(), &secondary_network_interface_config, ENDPOINT_FLAG_NONE, nullptr);
+  if (endpoint == nullptr) {
+    log_e("Failed to create secondary network interface endpoint");
+    return false;
+  }
+  secondary_network_endpoint_id = endpoint::get_id(endpoint);
+  log_i("Secondary Network Interface created with endpoint_id %d", secondary_network_endpoint_id);
+  return true;
+}
+
+uint16_t MatterEndPoint::getSecondaryNetworkEndPointId() {
+  return secondary_network_endpoint_id;
+}
+
+uint16_t MatterEndPoint::getEndPointId() {
+  return endpoint_id;
+}
+
+void MatterEndPoint::setEndPointId(uint16_t ep) {
+  if (ep == 0) {
+    log_e("Invalid endpoint ID");
+    return;
+  }
+  log_v("Endpoint ID set to %d", ep);
+
+  endpoint_id = ep;
+}
+
+// helper functions for attribute manipulation
+esp_matter::attribute_t *MatterEndPoint::getAttribute(uint32_t cluster_id, uint32_t attribute_id) {
+  if (endpoint_id == 0) {
+    log_e("Endpoint ID is not set");
+    return nullptr;
+  }
+  endpoint_t *endpoint = endpoint::get(node::get(), endpoint_id);
+  if (endpoint == nullptr) {
+    log_e("Endpoint [%d] not found", endpoint_id);
+    return nullptr;
+  }
+  cluster_t *cluster = cluster::get(endpoint, cluster_id);
+  if (cluster == nullptr) {
+    log_e("Cluster [%d] not found", cluster_id);
+    return nullptr;
+  }
+  esp_matter::attribute_t *attribute = attribute::get(cluster, attribute_id);
+  if (attribute == nullptr) {
+    log_e("Attribute [%d] not found", attribute_id);
+    return nullptr;
+  }
+  return attribute;
+}
+
+// get the value of an attribute from its cluster id and attribute it
+bool MatterEndPoint::getAttributeVal(uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *attrVal) {
+  esp_matter::attribute_t *attribute = getAttribute(cluster_id, attribute_id);
+  if (attribute == nullptr) {
+    return false;
+  }
+  if (attribute::get_val(attribute, attrVal) == ESP_OK) {
+    log_v("GET_VAL Success for cluster %d, attribute %d with value %d", cluster_id, attribute_id, attrVal->val.u32);
+    return true;
+  }
+  log_e("GET_VAL FAILED! for cluster %d, attribute %d with value %d", cluster_id, attribute_id, attrVal->val.u32);
+  return false;
+}
+
+// set the value of an attribute from its cluster id and attribute it
+bool MatterEndPoint::setAttributeVal(uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *attrVal) {
+  esp_matter::attribute_t *attribute = getAttribute(cluster_id, attribute_id);
+  if (attribute == nullptr) {
+    return false;
+  }
+  if (attribute::set_val(attribute, attrVal) == ESP_OK) {
+    log_v("SET_VAL Success for cluster %d, attribute %d with value %d", cluster_id, attribute_id, attrVal->val.u32);
+    return true;
+  }
+  log_e("SET_VAL FAILED! for cluster %d, attribute %d with value %d", cluster_id, attribute_id, attrVal->val.u32);
+  return false;
+}
+
+// update the value of an attribute from its cluster id and attribute it
+bool MatterEndPoint::updateAttributeVal(uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *attrVal) {
+  if (attribute::update(endpoint_id, cluster_id, attribute_id, attrVal) == ESP_OK) {
+    log_v("Update Success for cluster %d, attribute %d with value %d", cluster_id, attribute_id, attrVal->val.u32);
+    return true;
+  }
+  log_e("Update FAILED! for cluster %d, attribute %d with value %d", cluster_id, attribute_id, attrVal->val.u32);
+  return false;
+}
+
+// This callback is invoked when clients interact with the Identify Cluster of an specific endpoint.
+bool MatterEndPoint::endpointIdentifyCB(uint16_t endpoint_id, bool identifyIsEnabled) {
+  if (_onEndPointIdentifyCB) {
+    return _onEndPointIdentifyCB(identifyIsEnabled);
+  }
+  return true;
+}
+
+// User callback for the Identify Cluster functionality
+void MatterEndPoint::onIdentify(EndPointIdentifyCB onEndPointIdentifyCB) {
+  _onEndPointIdentifyCB = onEndPointIdentifyCB;
+}
+
+#endif /* CONFIG_ESP_MATTER_ENABLE_DATA_MODEL */
diff --git a/libraries/Matter/src/MatterEndPoint.h b/libraries/Matter/src/MatterEndPoint.h
index 95d3d3c08df..3138014d624 100644
--- a/libraries/Matter/src/MatterEndPoint.h
+++ b/libraries/Matter/src/MatterEndPoint.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -16,7 +16,8 @@
 #include <sdkconfig.h>
 #ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL
 
-#include <Matter.h>
+#include <Arduino.h>
+#include <esp_matter.h>
 #include <functional>
 
 using namespace esp_matter;
@@ -29,93 +30,47 @@ class MatterEndPoint {
     ATTR_UPDATE = true
   };
 
-  uint16_t getEndPointId() {
-    return endpoint_id;
-  }
+  using EndPointIdentifyCB = std::function<bool(bool)>;
+
+  // this function is called by Matter internal event processor. It could be overwritten by the application, if necessary.
+  virtual bool attributeChangeCB(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *val) = 0;
+
+  // This function is called to create a secondary network interface endpoint.
+  // It can be used for devices that support multiple network interfaces,
+  // such as Ethernet, Thread and Wi-Fi.
+  bool createSecondaryNetworkInterface();
+
+  // This function is called to get the secondary network interface endpoint ID.
+  uint16_t getSecondaryNetworkEndPointId();
+
+  // This function is called to get the current Matter Accessory endpoint ID.
+  uint16_t getEndPointId();
 
-  void setEndPointId(uint16_t ep) {
-    endpoint_id = ep;
-  }
+  // This function is called to set the current Matter Accessory endpoint ID.
+  void setEndPointId(uint16_t ep);
 
   // helper functions for attribute manipulation
-  esp_matter::attribute_t *getAttribute(uint32_t cluster_id, uint32_t attribute_id) {
-    if (endpoint_id == 0) {
-      log_e("Endpoint ID is not set");
-      return nullptr;
-    }
-    endpoint_t *endpoint = endpoint::get(node::get(), endpoint_id);
-    if (endpoint == nullptr) {
-      log_e("Endpoint [%d] not found", endpoint_id);
-      return nullptr;
-    }
-    cluster_t *cluster = cluster::get(endpoint, cluster_id);
-    if (cluster == nullptr) {
-      log_e("Cluster [%d] not found", cluster_id);
-      return nullptr;
-    }
-    esp_matter::attribute_t *attribute = attribute::get(cluster, attribute_id);
-    if (attribute == nullptr) {
-      log_e("Attribute [%d] not found", attribute_id);
-      return nullptr;
-    }
-    return attribute;
-  }
-
-  // get the value of an attribute from its cluster id and attribute it
-  bool getAttributeVal(uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *attrVal) {
-    esp_matter::attribute_t *attribute = getAttribute(cluster_id, attribute_id);
-    if (attribute == nullptr) {
-      return false;
-    }
-    if (attribute::get_val(attribute, attrVal) == ESP_OK) {
-      log_v("GET_VAL Success for cluster %d, attribute %d with value %d", cluster_id, attribute_id, attrVal->val.u32);
-      return true;
-    }
-    log_e("GET_VAL FAILED! for cluster %d, attribute %d with value %d", cluster_id, attribute_id, attrVal->val.u32);
-    return false;
-  }
-
-  // set the value of an attribute from its cluster id and attribute it
-  bool setAttributeVal(uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *attrVal) {
-    esp_matter::attribute_t *attribute = getAttribute(cluster_id, attribute_id);
-    if (attribute == nullptr) {
-      return false;
-    }
-    if (attribute::set_val(attribute, attrVal) == ESP_OK) {
-      log_v("SET_VAL Success for cluster %d, attribute %d with value %d", cluster_id, attribute_id, attrVal->val.u32);
-      return true;
-    }
-    log_e("SET_VAL FAILED! for cluster %d, attribute %d with value %d", cluster_id, attribute_id, attrVal->val.u32);
-    return false;
-  }
-
-  // update the value of an attribute from its cluster id and attribute it
-  bool updateAttributeVal(uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *attrVal) {
-    if (attribute::update(endpoint_id, cluster_id, attribute_id, attrVal) == ESP_OK) {
-      log_v("Update Success for cluster %d, attribute %d with value %d", cluster_id, attribute_id, attrVal->val.u32);
-      return true;
-    }
-    log_e("Update FAILED! for cluster %d, attribute %d with value %d", cluster_id, attribute_id, attrVal->val.u32);
-    return false;
-  }
+  esp_matter::attribute_t *getAttribute(uint32_t cluster_id, uint32_t attribute_id);
 
-  // this function is called by Matter internal event processor. It could be overwritten by the application, if necessary.
-  virtual bool attributeChangeCB(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *val) = 0;
+  // get the value of an attribute from its cluster id and
+  bool getAttributeVal(uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *attrVal);
+
+  // set the value of an attribute from its cluster id and
+  bool setAttributeVal(uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *attrVal);
+
+  // update the value of an attribute from its cluster id
+  bool updateAttributeVal(uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *attrVal);
 
   // This callback is invoked when clients interact with the Identify Cluster of an specific endpoint.
-  bool endpointIdentifyCB(uint16_t endpoint_id, bool identifyIsEnabled) {
-    if (_onEndPointIdentifyCB) {
-      return _onEndPointIdentifyCB(identifyIsEnabled);
-    }
-    return true;
-  }
-  // User callaback for the Identify Cluster functionality
-  using EndPointIdentifyCB = std::function<bool(bool)>;
-  void onIdentify(EndPointIdentifyCB onEndPointIdentifyCB) {
-    _onEndPointIdentifyCB = onEndPointIdentifyCB;
-  }
+  bool endpointIdentifyCB(uint16_t endpoint_id, bool identifyIsEnabled);
+
+  // User callback for the Identify Cluster functionality
+  void onIdentify(EndPointIdentifyCB onEndPointIdentifyCB);
 
 protected:
+  // used for secondary network interface endpoints
+  static uint16_t secondary_network_endpoint_id;
+  // main endpoint ID
   uint16_t endpoint_id = 0;
   EndPointIdentifyCB _onEndPointIdentifyCB = nullptr;
 };
diff --git a/libraries/Matter/src/MatterEndpoints/MatterColorLight.cpp b/libraries/Matter/src/MatterEndpoints/MatterColorLight.cpp
index 39d79e86325..aff0972528b 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterColorLight.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterColorLight.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterColorLight.h b/libraries/Matter/src/MatterEndpoints/MatterColorLight.h
index 99449addd50..b07432a2cf5 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterColorLight.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterColorLight.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterColorTemperatureLight.cpp b/libraries/Matter/src/MatterEndpoints/MatterColorTemperatureLight.cpp
index 3c4fccfa046..db90edf1177 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterColorTemperatureLight.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterColorTemperatureLight.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterColorTemperatureLight.h b/libraries/Matter/src/MatterEndpoints/MatterColorTemperatureLight.h
index 539bc386e92..3c8b2dca882 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterColorTemperatureLight.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterColorTemperatureLight.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterContactSensor.cpp b/libraries/Matter/src/MatterEndpoints/MatterContactSensor.cpp
index 17b0fe7a247..52dcc8da7c0 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterContactSensor.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterContactSensor.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -60,6 +60,7 @@ bool MatterContactSensor::begin(bool _contactState) {
   contactState = _contactState;
   setEndPointId(endpoint::get_id(endpoint));
   log_i("Contact Sensor created with endpoint_id %d", getEndPointId());
+
   started = true;
   return true;
 }
diff --git a/libraries/Matter/src/MatterEndpoints/MatterContactSensor.h b/libraries/Matter/src/MatterEndpoints/MatterContactSensor.h
index 257da785e53..687bf0d0b4b 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterContactSensor.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterContactSensor.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterDimmableLight.cpp b/libraries/Matter/src/MatterEndpoints/MatterDimmableLight.cpp
index 5167cf1f21c..4659dd71675 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterDimmableLight.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterDimmableLight.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterDimmableLight.h b/libraries/Matter/src/MatterEndpoints/MatterDimmableLight.h
index 4497edd2fe2..45b112100cb 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterDimmableLight.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterDimmableLight.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterEnhancedColorLight.cpp b/libraries/Matter/src/MatterEndpoints/MatterEnhancedColorLight.cpp
index 9b245fb9408..5e9feb5aadd 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterEnhancedColorLight.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterEnhancedColorLight.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterEnhancedColorLight.h b/libraries/Matter/src/MatterEndpoints/MatterEnhancedColorLight.h
index a4baef968a4..97f0279b9e4 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterEnhancedColorLight.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterEnhancedColorLight.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterFan.cpp b/libraries/Matter/src/MatterEndpoints/MatterFan.cpp
index 1647490aa05..5745604ebde 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterFan.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterFan.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -110,6 +110,7 @@ bool MatterFan::begin(uint8_t percent, FanMode_t fanMode, FanModeSequence_t fanM
 
   setEndPointId(endpoint::get_id(endpoint));
   log_i("Fan created with endpoint_id %d", getEndPointId());
+
   started = true;
   return true;
 }
diff --git a/libraries/Matter/src/MatterEndpoints/MatterFan.h b/libraries/Matter/src/MatterEndpoints/MatterFan.h
index a1cd6e42423..53736ac70f2 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterFan.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterFan.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterGenericSwitch.cpp b/libraries/Matter/src/MatterEndpoints/MatterGenericSwitch.cpp
index e20479af088..f69d4a2ab7f 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterGenericSwitch.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterGenericSwitch.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -79,6 +79,7 @@ bool MatterGenericSwitch::begin() {
 
   setEndPointId(endpoint::get_id(endpoint));
   log_i("Generic Switch created with endpoint_id %d", getEndPointId());
+
   started = true;
   return true;
 }
diff --git a/libraries/Matter/src/MatterEndpoints/MatterGenericSwitch.h b/libraries/Matter/src/MatterEndpoints/MatterGenericSwitch.h
index 14118462932..ffcc6f47706 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterGenericSwitch.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterGenericSwitch.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterHumiditySensor.cpp b/libraries/Matter/src/MatterEndpoints/MatterHumiditySensor.cpp
index d31d0e43728..ef8276e4a04 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterHumiditySensor.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterHumiditySensor.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -68,6 +68,7 @@ bool MatterHumiditySensor::begin(uint16_t _rawHumidity) {
   rawHumidity = _rawHumidity;
   setEndPointId(endpoint::get_id(endpoint));
   log_i("Humidity Sensor created with endpoint_id %d", getEndPointId());
+
   started = true;
   return true;
 }
diff --git a/libraries/Matter/src/MatterEndpoints/MatterHumiditySensor.h b/libraries/Matter/src/MatterEndpoints/MatterHumiditySensor.h
index aed758b7b7a..48c3a4b9e28 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterHumiditySensor.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterHumiditySensor.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp b/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp
index 0d55c37708a..f91a02e14a9 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -71,6 +71,7 @@ bool MatterOccupancySensor::begin(bool _occupancyState, OccupancySensorType_t _o
   occupancyState = _occupancyState;
   setEndPointId(endpoint::get_id(endpoint));
   log_i("Occupancy Sensor created with endpoint_id %d", getEndPointId());
+
   started = true;
   return true;
 }
diff --git a/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.h b/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.h
index 30f312a9841..acfa7fec632 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterOccupancySensor.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterOnOffLight.cpp b/libraries/Matter/src/MatterEndpoints/MatterOnOffLight.cpp
index f400390f9a7..afd764088c5 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterOnOffLight.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterOnOffLight.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -79,6 +79,7 @@ bool MatterOnOffLight::begin(bool initialState) {
 
   setEndPointId(endpoint::get_id(endpoint));
   log_i("On-Off Light created with endpoint_id %d", getEndPointId());
+
   started = true;
   return true;
 }
diff --git a/libraries/Matter/src/MatterEndpoints/MatterOnOffLight.h b/libraries/Matter/src/MatterEndpoints/MatterOnOffLight.h
index ec524d2c300..2c52858cc9a 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterOnOffLight.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterOnOffLight.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.cpp b/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.cpp
index 9b08958684c..33cee105833 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -78,6 +78,7 @@ bool MatterOnOffPlugin::begin(bool initialState) {
   onOffState = initialState;
   setEndPointId(endpoint::get_id(endpoint));
   log_i("On-Off Plugin created with endpoint_id %d", getEndPointId());
+
   started = true;
   return true;
 }
diff --git a/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.h b/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.h
index 0b05c0944c4..e3489b355a8 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterOnOffPlugin.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterPressureSensor.cpp b/libraries/Matter/src/MatterEndpoints/MatterPressureSensor.cpp
index 86d245d4041..8674ad5936b 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterPressureSensor.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterPressureSensor.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -61,6 +61,7 @@ bool MatterPressureSensor::begin(int16_t _rawPressure) {
   rawPressure = _rawPressure;
   setEndPointId(endpoint::get_id(endpoint));
   log_i("Pressure Sensor created with endpoint_id %d", getEndPointId());
+
   started = true;
   return true;
 }
diff --git a/libraries/Matter/src/MatterEndpoints/MatterPressureSensor.h b/libraries/Matter/src/MatterEndpoints/MatterPressureSensor.h
index 0715c05609d..6b1973049ca 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterPressureSensor.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterPressureSensor.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterTemperatureSensor.cpp b/libraries/Matter/src/MatterEndpoints/MatterTemperatureSensor.cpp
index 863f86386c1..248bd29f05f 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterTemperatureSensor.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterTemperatureSensor.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -61,6 +61,7 @@ bool MatterTemperatureSensor::begin(int16_t _rawTemperature) {
   rawTemperature = _rawTemperature;
   setEndPointId(endpoint::get_id(endpoint));
   log_i("Temperature Sensor created with endpoint_id %d", getEndPointId());
+
   started = true;
   return true;
 }
diff --git a/libraries/Matter/src/MatterEndpoints/MatterTemperatureSensor.h b/libraries/Matter/src/MatterEndpoints/MatterTemperatureSensor.h
index 3be6101166c..51a1eeb3b0a 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterTemperatureSensor.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterTemperatureSensor.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
diff --git a/libraries/Matter/src/MatterEndpoints/MatterThermostat.cpp b/libraries/Matter/src/MatterEndpoints/MatterThermostat.cpp
index 5a68421bd8a..6ee18ef0cc9 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterThermostat.cpp
+++ b/libraries/Matter/src/MatterEndpoints/MatterThermostat.cpp
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -202,6 +202,7 @@ bool MatterThermostat::begin(ControlSequenceOfOperation_t _controlSequence, Ther
 
   setEndPointId(endpoint::get_id(endpoint));
   log_i("Thermostat created with endpoint_id %d", getEndPointId());
+
   started = true;
   return true;
 }
diff --git a/libraries/Matter/src/MatterEndpoints/MatterThermostat.h b/libraries/Matter/src/MatterEndpoints/MatterThermostat.h
index 2d64bdf3b01..53df61d191e 100644
--- a/libraries/Matter/src/MatterEndpoints/MatterThermostat.h
+++ b/libraries/Matter/src/MatterEndpoints/MatterThermostat.h
@@ -1,4 +1,4 @@
-// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.

From 1426927c837dfa0c10835eb3c769f7000db64c26 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Fri, 4 Jul 2025 18:37:56 +0300
Subject: [PATCH 035/105] fix(matter): Fix MatterSmartButon.ino when CHIPOBLE
 is on

---
 .../Matter/examples/MatterSmartButon/MatterSmartButon.ino     | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/libraries/Matter/examples/MatterSmartButon/MatterSmartButon.ino b/libraries/Matter/examples/MatterSmartButon/MatterSmartButon.ino
index 29caf00004c..f4d978175cc 100644
--- a/libraries/Matter/examples/MatterSmartButon/MatterSmartButon.ino
+++ b/libraries/Matter/examples/MatterSmartButon/MatterSmartButon.ino
@@ -45,12 +45,12 @@ void setup() {
 
   Serial.begin(115200);
 
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
   // We start by connecting to a WiFi network
   Serial.print("Connecting to ");
   Serial.println(ssid);
 
-// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
-#if !CONFIG_ENABLE_CHIPOBLE
   // Manually connect to WiFi
   WiFi.begin(ssid, password);
   // Wait for connection

From 6a5839acb2ead9b98bf0761c8bef16cbf327e6ca Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Tue, 8 Jul 2025 11:56:23 -0300
Subject: [PATCH 036/105] change(esptool): Upgrade esptool to release v5.0.0
 (#11562)

---
 .github/scripts/package_esptool.sh        | 129 ------------
 .github/scripts/update_esptool.py         | 236 ++++++++++++++++++++++
 package/package_esp32_index.template.json |  60 +++---
 3 files changed, 266 insertions(+), 159 deletions(-)
 delete mode 100755 .github/scripts/package_esptool.sh
 create mode 100644 .github/scripts/update_esptool.py

diff --git a/.github/scripts/package_esptool.sh b/.github/scripts/package_esptool.sh
deleted file mode 100755
index 32b87b277e9..00000000000
--- a/.github/scripts/package_esptool.sh
+++ /dev/null
@@ -1,129 +0,0 @@
-#!/bin/bash
-
-set -euo pipefail
-
-# Check version argument
-if [[ $# -ne 3 ]]; then
-  echo "Usage: $0 <version> <base_folder> <json_path>"
-  echo "Example: $0 5.0.dev1 /tmp/esptool /tmp/esptool-5.0.dev1.json"
-  exit 1
-fi
-
-VERSION=$1
-BASE_FOLDER=$2
-JSON_PATH=$3
-
-export COPYFILE_DISABLE=1
-
-shopt -s nullglob  # So for loop doesn't run if no matches
-
-# Function to update JSON for a given host
-function update_json_for_host {
-  local host=$1
-  local archive=$2
-
-  # Extract the old url from the JSON for this host, then replace only the filename
-  old_url=$(jq -r --arg host "$host" '
-    .packages[].tools[] | select(.name == "esptool_py") | .systems[] | select(.host == $host) | .url // empty
-  ' "$tmp_json")
-  if [[ -n "$old_url" ]]; then
-    base_url="${old_url%/*}"
-    url="$base_url/$archive"
-  else
-    echo "No old url found for $host"
-    exit 1
-  fi
-
-  archiveFileName="$archive"
-  checksum="SHA-256:$(shasum -a 256 "$archive" | awk '{print $1}')"
-  size=$(stat -f%z "$archive")
-
-  # Use jq to update the JSON
-  jq --arg host "$host" \
-     --arg url "$url" \
-     --arg archiveFileName "$archiveFileName" \
-     --arg checksum "$checksum" \
-     --arg size "$size" \
-     '
-     .packages[].tools[]
-     |= if .name == "esptool_py" then
-          .systems = (
-            ((.systems // []) | map(select(.host != $host))) + [{
-              host: $host,
-              url: $url,
-              archiveFileName: $archiveFileName,
-              checksum: $checksum,
-              size: $size
-            }]
-          )
-        else
-          .
-        end
-     ' "$tmp_json" > "$tmp_json.new" && mv "$tmp_json.new" "$tmp_json"
-}
-
-cd "$BASE_FOLDER"
-
-# Delete all archives before starting
-rm -f esptool-*.tar.gz esptool-*.zip
-
-for dir in esptool-*; do
-  # Check if directory exists and is a directory
-  if [[ ! -d "$dir" ]]; then
-    continue
-  fi
-
-  base="${dir#esptool-}"
-
-  # Add 'linux-' prefix if base doesn't contain linux/macos/win64
-  if [[ "$base" != *linux* && "$base" != *macos* && "$base" != *win64* ]]; then
-    base="linux-${base}"
-  fi
-
-  if [[ "$dir" == esptool-win* ]]; then
-    # Windows zip archive
-    zipfile="esptool-v${VERSION}-${base}.zip"
-    echo "Creating $zipfile from $dir ..."
-    zip -r "$zipfile" "$dir"
-  else
-    # Non-Windows: set permissions and tar.gz archive
-    tarfile="esptool-v${VERSION}-${base}.tar.gz"
-    echo "Setting permissions and creating $tarfile from $dir ..."
-    chmod -R u=rwx,g=rx,o=rx "$dir"
-    tar -cvzf "$tarfile" "$dir"
-  fi
-done
-
-# After the for loop, update the JSON for each archive
-# Create a temporary JSON file to accumulate changes
-tmp_json="${JSON_PATH}.tmp"
-cp "$JSON_PATH" "$tmp_json"
-
-for archive in esptool-v"${VERSION}"-*.tar.gz esptool-v"${VERSION}"-*.zip; do
-  [ -f "$archive" ] || continue
-
-  echo "Updating JSON for $archive"
-
-  # Determine host from archive name
-  case "$archive" in
-    *linux-amd64*)   host="x86_64-pc-linux-gnu" ;;
-    *linux-armv7*)   host="arm-linux-gnueabihf" ;;
-    *linux-aarch64*) host="aarch64-linux-gnu" ;;
-    *macos-amd64*)   host="x86_64-apple-darwin" ;;
-    *macos-arm64*)   host="arm64-apple-darwin" ;;
-    *win64*)         hosts=("x86_64-mingw32" "i686-mingw32") ;;
-    *) echo "Unknown host for $archive"; continue ;;
-  esac
-
-  # For win64, loop over both hosts; otherwise, use a single host
-  if [[ "$archive" == *win64* ]]; then
-    for host in "${hosts[@]}"; do
-      update_json_for_host "$host" "$archive"
-    done
-  else
-    update_json_for_host "$host" "$archive"
-  fi
-done
-
-# After all archives are processed, move the temporary JSON to the final file
-mv "$tmp_json" "$JSON_PATH"
diff --git a/.github/scripts/update_esptool.py b/.github/scripts/update_esptool.py
new file mode 100644
index 00000000000..d99462fcb8f
--- /dev/null
+++ b/.github/scripts/update_esptool.py
@@ -0,0 +1,236 @@
+#!/usr/bin/env python3
+
+# This script is used to re-package the esptool if needed and update the JSON file
+# for the Arduino ESP32 platform.
+#
+# The script has only been tested on macOS.
+#
+# For regular esptool releases, the generated packages already contain the correct permissions,
+# extensions and are uploaded to the GitHub release assets. In this case, the script will only
+# update the JSON file with the information from the GitHub release.
+#
+# The script can be used in two modes:
+# 1. Local build: The build artifacts must be already downloaded and extracted in the base_folder.
+#    This is useful for esptool versions that are not yet released and that are grabbed from the
+#    GitHub build artifacts.
+# 2. Release build: The script will get the release information from GitHub and update the JSON file.
+#    This is useful for esptool versions that are already released and that are uploaded to the
+#    GitHub release assets.
+#
+#    For local build, the artifacts must be already downloaded and extracted in the base_folder
+#    set with the -l option.
+#    For example, a base folder "esptool" should contain the following folders extracted directly
+#    from the GitHub build artifacts:
+#        esptool/esptool-linux-aarch64
+#        esptool/esptool-linux-amd64
+#        esptool/esptool-linux-armv7
+#        esptool/esptool-macos-amd64
+#        esptool/esptool-macos-arm64
+#        esptool/esptool-windows-amd64
+
+import argparse
+import json
+import os
+import shutil
+import stat
+import tarfile
+import zipfile
+import hashlib
+import requests
+from pathlib import Path
+
+def compute_sha256(filepath):
+    sha256 = hashlib.sha256()
+    with open(filepath, "rb") as f:
+        for block in iter(lambda: f.read(4096), b""):
+            sha256.update(block)
+    return f"SHA-256:{sha256.hexdigest()}"
+
+def get_file_size(filepath):
+    return os.path.getsize(filepath)
+
+def update_json_for_host(tmp_json_path, version, host, url, archiveFileName, checksum, size):
+    with open(tmp_json_path) as f:
+        data = json.load(f)
+
+    for pkg in data.get("packages", []):
+        for tool in pkg.get("tools", []):
+            if tool.get("name") == "esptool_py":
+                tool["version"] = version
+
+                if url is None:
+                    # If the URL is not set, we need to find the old URL and update it
+                    for system in tool.get("systems", []):
+                        if system.get("host") == host:
+                            url = system.get("url").replace(system.get("archiveFileName"), archiveFileName)
+                            break
+                    else:
+                        print(f"No old URL found for host {host}. Using empty URL.")
+                        url = ""
+
+                # Preserve existing systems order and update or append the new system
+                systems = tool.get("systems", [])
+                system_updated = False
+                for i, system in enumerate(systems):
+                    if system.get("host") == host:
+                        systems[i] = {
+                            "host": host,
+                            "url": url,
+                            "archiveFileName": archiveFileName,
+                            "checksum": checksum,
+                            "size": str(size),
+                        }
+                        system_updated = True
+                        break
+
+                if not system_updated:
+                    systems.append({
+                        "host": host,
+                        "url": url,
+                        "archiveFileName": archiveFileName,
+                        "checksum": checksum,
+                        "size": str(size),
+                    })
+                tool["systems"] = systems
+
+    with open(tmp_json_path, "w") as f:
+        json.dump(data, f, indent=2, sort_keys=False, ensure_ascii=False)
+        f.write("\n")
+
+def update_tools_dependencies(tmp_json_path, version):
+    with open(tmp_json_path) as f:
+        data = json.load(f)
+
+    for pkg in data.get("packages", []):
+        for platform in pkg.get("platforms", []):
+            for dep in platform.get("toolsDependencies", []):
+                if dep.get("name") == "esptool_py":
+                    dep["version"] = version
+
+    with open(tmp_json_path, "w") as f:
+        json.dump(data, f, indent=2, sort_keys=False, ensure_ascii=False)
+        f.write("\n")
+
+def create_archives(version, base_folder):
+    archive_files = []
+
+    for dirpath in Path(base_folder).glob("esptool-*"):
+        if not dirpath.is_dir():
+            continue
+
+        base = dirpath.name[len("esptool-"):]
+
+        if "windows" in dirpath.name:
+            zipfile_name = f"esptool-v{version}-{base}.zip"
+            print(f"Creating {zipfile_name} from {dirpath} ...")
+            with zipfile.ZipFile(zipfile_name, "w", zipfile.ZIP_DEFLATED) as zipf:
+                for root, _, files in os.walk(dirpath):
+                    for file in files:
+                        full_path = os.path.join(root, file)
+                        zipf.write(full_path, os.path.relpath(full_path, start=dirpath))
+            archive_files.append(zipfile_name)
+        else:
+            tarfile_name = f"esptool-v{version}-{base}.tar.gz"
+            print(f"Creating {tarfile_name} from {dirpath} ...")
+            for root, dirs, files in os.walk(dirpath):
+                for name in dirs + files:
+                    os.chmod(os.path.join(root, name), stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR |
+                                                        stat.S_IRGRP | stat.S_IXGRP |
+                                                        stat.S_IROTH | stat.S_IXOTH)
+            with tarfile.open(tarfile_name, "w:gz") as tar:
+                tar.add(dirpath, arcname=dirpath.name)
+            archive_files.append(tarfile_name)
+
+    return archive_files
+
+def determine_hosts(archive_name):
+    if "linux-amd64" in archive_name:
+        return ["x86_64-pc-linux-gnu"]
+    elif "linux-armv7" in archive_name:
+        return ["arm-linux-gnueabihf"]
+    elif "linux-aarch64" in archive_name:
+        return ["aarch64-linux-gnu"]
+    elif "macos-amd64" in archive_name:
+        return ["x86_64-apple-darwin"]
+    elif "macos-arm64" in archive_name:
+        return ["arm64-apple-darwin"]
+    elif "windows-amd64" in archive_name:
+        return ["x86_64-mingw32", "i686-mingw32"]
+    else:
+        return []
+
+def update_json_from_local_build(tmp_json_path, version, base_folder, archive_files):
+    for archive in archive_files:
+        print(f"Processing archive: {archive}")
+        hosts = determine_hosts(archive)
+        if not hosts:
+            print(f"Skipping unknown archive type: {archive}")
+            continue
+
+        archive_path = Path(archive)
+        checksum = compute_sha256(archive_path)
+        size = get_file_size(archive_path)
+
+        for host in hosts:
+            update_json_for_host(tmp_json_path, version, host, None, archive_path.name, checksum, size)
+
+def update_json_from_release(tmp_json_path, version, release_info):
+    assets = release_info.get("assets", [])
+    for asset in assets:
+        if (asset.get("name").endswith(".tar.gz") or asset.get("name").endswith(".zip")) and "esptool" in asset.get("name"):
+            asset_fname = asset.get("name")
+            print(f"Processing asset: {asset_fname}")
+            hosts = determine_hosts(asset_fname)
+            if not hosts:
+                print(f"Skipping unknown archive type: {asset_fname}")
+                continue
+
+            asset_url = asset.get("browser_download_url")
+            asset_checksum = asset.get("digest").replace("sha256:", "SHA-256:")
+            asset_size = asset.get("size")
+            if asset_checksum is None:
+                asset_checksum = ""
+                print(f"Asset {asset_fname} has no checksum. Please set the checksum in the JSON file.")
+
+            for host in hosts:
+                update_json_for_host(tmp_json_path, version, host, asset_url, asset_fname, asset_checksum, asset_size)
+
+def get_release_info(version):
+    url = f"https://api.github.com/repos/espressif/esptool/releases/tags/v{version}"
+    response = requests.get(url)
+    response.raise_for_status()
+    return response.json()
+
+def main():
+    parser = argparse.ArgumentParser(description="Repack esptool and update JSON metadata.")
+    parser.add_argument("version", help="Version of the esptool (e.g. 5.0.dev1)")
+    parser.add_argument("-l", "--local", dest="base_folder", help="Enable local build mode and set the base folder with unpacked artifacts")
+    args = parser.parse_args()
+
+    script_dir = Path(__file__).resolve().parent
+    json_path = (script_dir / "../../package/package_esp32_index.template.json").resolve()
+    tmp_json_path = Path(str(json_path) + ".tmp")
+    shutil.copy(json_path, tmp_json_path)
+
+    local_build = args.base_folder is not None
+
+    if local_build:
+        os.chdir(args.base_folder)
+        os.environ['COPYFILE_DISABLE'] = 'true'  # this disables including resource forks in tar files on macOS
+        # Clear any existing archive files
+        for file in Path(args.base_folder).glob("esptool-*.*"):
+            file.unlink()
+        archive_files = create_archives(args.version, args.base_folder)
+        update_json_from_local_build(tmp_json_path, args.version, args.base_folder, archive_files)
+    else:
+        release_info = get_release_info(args.version)
+        update_json_from_release(tmp_json_path, args.version, release_info)
+
+    print(f"Updating esptool version fields to {args.version}")
+    update_tools_dependencies(tmp_json_path, args.version)
+
+    shutil.move(tmp_json_path, json_path)
+    print(f"Done. JSON updated at {json_path}")
+
+if __name__ == "__main__":
+    main()
diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index bbb77f8ef5a..5f5d1f0e08b 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -81,7 +81,7 @@
             {
               "packager": "esp32",
               "name": "esptool_py",
-              "version": "5.0.dev1"
+              "version": "5.0.0"
             },
             {
               "packager": "esp32",
@@ -469,56 +469,56 @@
         },
         {
           "name": "esptool_py",
-          "version": "5.0.dev1",
+          "version": "5.0.0",
           "systems": [
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-linux-aarch64.tar.gz",
-              "archiveFileName": "esptool-v5.0.dev1-linux-aarch64.tar.gz",
-              "checksum": "SHA-256:bfafa7a7723ebbabfd8b6e3ca5ae00bfead0331de923754aeddb43b2c116a078",
-              "size": "58241736"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-linux-aarch64.tar.gz",
+              "archiveFileName": "esptool-v5.0.0-linux-aarch64.tar.gz",
+              "checksum": "SHA-256:2bf239f3ed76141a957cadb205b94414ec6da9ace4e85f285e247d20a92b83e3",
+              "size": "58231895"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-linux-amd64.tar.gz",
-              "archiveFileName": "esptool-v5.0.dev1-linux-amd64.tar.gz",
-              "checksum": "SHA-256:acd0486e96586b99d053a1479acbbbfcae8667227c831cdc53a171f9ccfa27ee",
-              "size": "100740042"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-linux-amd64.tar.gz",
+              "archiveFileName": "esptool-v5.0.0-linux-amd64.tar.gz",
+              "checksum": "SHA-256:3b3835d266ac61f3242758f2fe34e3b33dbe6ee4b5acde005da793356f9f7043",
+              "size": "100783748"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-linux-armv7.tar.gz",
-              "archiveFileName": "esptool-v5.0.dev1-linux-armv7.tar.gz",
-              "checksum": "SHA-256:ea77a38681506761bbb7b0b39c130811ed565667b67ebbdb4d6dcc6cb6e07368",
-              "size": "53451939"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-linux-armv7.tar.gz",
+              "archiveFileName": "esptool-v5.0.0-linux-armv7.tar.gz",
+              "checksum": "SHA-256:e55cd321abecfcf27f72a2bff5d5e19a5365fd400de66d71c5e7218e77556315",
+              "size": "53461760"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-macos-amd64.tar.gz",
-              "archiveFileName": "esptool-v5.0.dev1-macos-amd64.tar.gz",
-              "checksum": "SHA-256:900a8e90731208bee96647e0e207a43612b9452c2120c4fdc0ff4c6be226257b",
-              "size": "59631998"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-macos-amd64.tar.gz",
+              "archiveFileName": "esptool-v5.0.0-macos-amd64.tar.gz",
+              "checksum": "SHA-256:424da2bdf0435257ad81bcb7eae6fd8dd7f675ce5b2ee60032f4ecec4d6a5d45",
+              "size": "59629533"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-macos-arm64.tar.gz",
-              "archiveFileName": "esptool-v5.0.dev1-macos-arm64.tar.gz",
-              "checksum": "SHA-256:3653f4de73cb4fc6a25351eaf663708e91c65ae3265d75bd54ca4315a4350bb4",
-              "size": "56349992"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-macos-arm64.tar.gz",
+              "archiveFileName": "esptool-v5.0.0-macos-arm64.tar.gz",
+              "checksum": "SHA-256:b91dfe1da7b0041376683dec10a91dfb266fbda2fb86ed87c4a034ff7182ee56",
+              "size": "56343104"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-win64.zip",
-              "archiveFileName": "esptool-v5.0.dev1-win64.zip",
-              "checksum": "SHA-256:1e8fd89645daf94f2d4406ec73c9004e617ea921079515f9fd749205eece4d6d",
-              "size": "59102658"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-windows-amd64.zip",
+              "archiveFileName": "esptool-v5.0.0-windows-amd64.zip",
+              "checksum": "SHA-256:2294107f66db6f09b886b337728a981173c9e7eab45a030928a8a5a1370611ca",
+              "size": "59105322"
             },
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-win64.zip",
-              "archiveFileName": "esptool-v5.0.dev1-win64.zip",
-              "checksum": "SHA-256:1e8fd89645daf94f2d4406ec73c9004e617ea921079515f9fd749205eece4d6d",
-              "size": "59102658"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-windows-amd64.zip",
+              "archiveFileName": "esptool-v5.0.0-windows-amd64.zip",
+              "checksum": "SHA-256:2294107f66db6f09b886b337728a981173c9e7eab45a030928a8a5a1370611ca",
+              "size": "59105322"
             }
           ]
         },

From ccc0a69ef88202519c0773ec254ee31cbe2baf82 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Tue, 8 Jul 2025 11:58:36 -0300
Subject: [PATCH 037/105] change(esptool): Upgrade esptool to release v5.0.0
 (#11563)

---
 .github/scripts/package_esptool.sh        | 129 ----------------------
 .github/scripts/update_esptool.py         |   2 +-
 package/package_esp32_index.template.json |  60 +++++-----
 3 files changed, 31 insertions(+), 160 deletions(-)
 delete mode 100755 .github/scripts/package_esptool.sh

diff --git a/.github/scripts/package_esptool.sh b/.github/scripts/package_esptool.sh
deleted file mode 100755
index 32b87b277e9..00000000000
--- a/.github/scripts/package_esptool.sh
+++ /dev/null
@@ -1,129 +0,0 @@
-#!/bin/bash
-
-set -euo pipefail
-
-# Check version argument
-if [[ $# -ne 3 ]]; then
-  echo "Usage: $0 <version> <base_folder> <json_path>"
-  echo "Example: $0 5.0.dev1 /tmp/esptool /tmp/esptool-5.0.dev1.json"
-  exit 1
-fi
-
-VERSION=$1
-BASE_FOLDER=$2
-JSON_PATH=$3
-
-export COPYFILE_DISABLE=1
-
-shopt -s nullglob  # So for loop doesn't run if no matches
-
-# Function to update JSON for a given host
-function update_json_for_host {
-  local host=$1
-  local archive=$2
-
-  # Extract the old url from the JSON for this host, then replace only the filename
-  old_url=$(jq -r --arg host "$host" '
-    .packages[].tools[] | select(.name == "esptool_py") | .systems[] | select(.host == $host) | .url // empty
-  ' "$tmp_json")
-  if [[ -n "$old_url" ]]; then
-    base_url="${old_url%/*}"
-    url="$base_url/$archive"
-  else
-    echo "No old url found for $host"
-    exit 1
-  fi
-
-  archiveFileName="$archive"
-  checksum="SHA-256:$(shasum -a 256 "$archive" | awk '{print $1}')"
-  size=$(stat -f%z "$archive")
-
-  # Use jq to update the JSON
-  jq --arg host "$host" \
-     --arg url "$url" \
-     --arg archiveFileName "$archiveFileName" \
-     --arg checksum "$checksum" \
-     --arg size "$size" \
-     '
-     .packages[].tools[]
-     |= if .name == "esptool_py" then
-          .systems = (
-            ((.systems // []) | map(select(.host != $host))) + [{
-              host: $host,
-              url: $url,
-              archiveFileName: $archiveFileName,
-              checksum: $checksum,
-              size: $size
-            }]
-          )
-        else
-          .
-        end
-     ' "$tmp_json" > "$tmp_json.new" && mv "$tmp_json.new" "$tmp_json"
-}
-
-cd "$BASE_FOLDER"
-
-# Delete all archives before starting
-rm -f esptool-*.tar.gz esptool-*.zip
-
-for dir in esptool-*; do
-  # Check if directory exists and is a directory
-  if [[ ! -d "$dir" ]]; then
-    continue
-  fi
-
-  base="${dir#esptool-}"
-
-  # Add 'linux-' prefix if base doesn't contain linux/macos/win64
-  if [[ "$base" != *linux* && "$base" != *macos* && "$base" != *win64* ]]; then
-    base="linux-${base}"
-  fi
-
-  if [[ "$dir" == esptool-win* ]]; then
-    # Windows zip archive
-    zipfile="esptool-v${VERSION}-${base}.zip"
-    echo "Creating $zipfile from $dir ..."
-    zip -r "$zipfile" "$dir"
-  else
-    # Non-Windows: set permissions and tar.gz archive
-    tarfile="esptool-v${VERSION}-${base}.tar.gz"
-    echo "Setting permissions and creating $tarfile from $dir ..."
-    chmod -R u=rwx,g=rx,o=rx "$dir"
-    tar -cvzf "$tarfile" "$dir"
-  fi
-done
-
-# After the for loop, update the JSON for each archive
-# Create a temporary JSON file to accumulate changes
-tmp_json="${JSON_PATH}.tmp"
-cp "$JSON_PATH" "$tmp_json"
-
-for archive in esptool-v"${VERSION}"-*.tar.gz esptool-v"${VERSION}"-*.zip; do
-  [ -f "$archive" ] || continue
-
-  echo "Updating JSON for $archive"
-
-  # Determine host from archive name
-  case "$archive" in
-    *linux-amd64*)   host="x86_64-pc-linux-gnu" ;;
-    *linux-armv7*)   host="arm-linux-gnueabihf" ;;
-    *linux-aarch64*) host="aarch64-linux-gnu" ;;
-    *macos-amd64*)   host="x86_64-apple-darwin" ;;
-    *macos-arm64*)   host="arm64-apple-darwin" ;;
-    *win64*)         hosts=("x86_64-mingw32" "i686-mingw32") ;;
-    *) echo "Unknown host for $archive"; continue ;;
-  esac
-
-  # For win64, loop over both hosts; otherwise, use a single host
-  if [[ "$archive" == *win64* ]]; then
-    for host in "${hosts[@]}"; do
-      update_json_for_host "$host" "$archive"
-    done
-  else
-    update_json_for_host "$host" "$archive"
-  fi
-done
-
-# After all archives are processed, move the temporary JSON to the final file
-mv "$tmp_json" "$JSON_PATH"
diff --git a/.github/scripts/update_esptool.py b/.github/scripts/update_esptool.py
index dd5de5526c3..d99462fcb8f 100644
--- a/.github/scripts/update_esptool.py
+++ b/.github/scripts/update_esptool.py
@@ -186,7 +186,7 @@ def update_json_from_release(tmp_json_path, version, release_info):
                 continue
 
             asset_url = asset.get("browser_download_url")
-            asset_checksum = asset.get("digest")
+            asset_checksum = asset.get("digest").replace("sha256:", "SHA-256:")
             asset_size = asset.get("size")
             if asset_checksum is None:
                 asset_checksum = ""
diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index a02be509094..9c2c754504e 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -81,7 +81,7 @@
             {
               "packager": "esp32",
               "name": "esptool_py",
-              "version": "5.0.dev1"
+              "version": "5.0.0"
             },
             {
               "packager": "esp32",
@@ -469,56 +469,56 @@
         },
         {
           "name": "esptool_py",
-          "version": "5.0.dev1",
+          "version": "5.0.0",
           "systems": [
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-linux-aarch64.tar.gz",
-              "archiveFileName": "esptool-v5.0.dev1-linux-aarch64.tar.gz",
-              "checksum": "SHA-256:bfafa7a7723ebbabfd8b6e3ca5ae00bfead0331de923754aeddb43b2c116a078",
-              "size": "58241736"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-linux-aarch64.tar.gz",
+              "archiveFileName": "esptool-v5.0.0-linux-aarch64.tar.gz",
+              "checksum": "SHA-256:2bf239f3ed76141a957cadb205b94414ec6da9ace4e85f285e247d20a92b83e3",
+              "size": "58231895"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-linux-amd64.tar.gz",
-              "archiveFileName": "esptool-v5.0.dev1-linux-amd64.tar.gz",
-              "checksum": "SHA-256:acd0486e96586b99d053a1479acbbbfcae8667227c831cdc53a171f9ccfa27ee",
-              "size": "100740042"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-linux-amd64.tar.gz",
+              "archiveFileName": "esptool-v5.0.0-linux-amd64.tar.gz",
+              "checksum": "SHA-256:3b3835d266ac61f3242758f2fe34e3b33dbe6ee4b5acde005da793356f9f7043",
+              "size": "100783748"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-linux-armv7.tar.gz",
-              "archiveFileName": "esptool-v5.0.dev1-linux-armv7.tar.gz",
-              "checksum": "SHA-256:ea77a38681506761bbb7b0b39c130811ed565667b67ebbdb4d6dcc6cb6e07368",
-              "size": "53451939"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-linux-armv7.tar.gz",
+              "archiveFileName": "esptool-v5.0.0-linux-armv7.tar.gz",
+              "checksum": "SHA-256:e55cd321abecfcf27f72a2bff5d5e19a5365fd400de66d71c5e7218e77556315",
+              "size": "53461760"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-macos-amd64.tar.gz",
-              "archiveFileName": "esptool-v5.0.dev1-macos-amd64.tar.gz",
-              "checksum": "SHA-256:900a8e90731208bee96647e0e207a43612b9452c2120c4fdc0ff4c6be226257b",
-              "size": "59631998"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-macos-amd64.tar.gz",
+              "archiveFileName": "esptool-v5.0.0-macos-amd64.tar.gz",
+              "checksum": "SHA-256:424da2bdf0435257ad81bcb7eae6fd8dd7f675ce5b2ee60032f4ecec4d6a5d45",
+              "size": "59629533"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-macos-arm64.tar.gz",
-              "archiveFileName": "esptool-v5.0.dev1-macos-arm64.tar.gz",
-              "checksum": "SHA-256:3653f4de73cb4fc6a25351eaf663708e91c65ae3265d75bd54ca4315a4350bb4",
-              "size": "56349992"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-macos-arm64.tar.gz",
+              "archiveFileName": "esptool-v5.0.0-macos-arm64.tar.gz",
+              "checksum": "SHA-256:b91dfe1da7b0041376683dec10a91dfb266fbda2fb86ed87c4a034ff7182ee56",
+              "size": "56343104"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-win64.zip",
-              "archiveFileName": "esptool-v5.0.dev1-win64.zip",
-              "checksum": "SHA-256:1e8fd89645daf94f2d4406ec73c9004e617ea921079515f9fd749205eece4d6d",
-              "size": "59102658"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-windows-amd64.zip",
+              "archiveFileName": "esptool-v5.0.0-windows-amd64.zip",
+              "checksum": "SHA-256:2294107f66db6f09b886b337728a981173c9e7eab45a030928a8a5a1370611ca",
+              "size": "59105322"
             },
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/arduino-esp32/releases/download/3.2.0/esptool-v5.0.dev1-win64.zip",
-              "archiveFileName": "esptool-v5.0.dev1-win64.zip",
-              "checksum": "SHA-256:1e8fd89645daf94f2d4406ec73c9004e617ea921079515f9fd749205eece4d6d",
-              "size": "59102658"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-windows-amd64.zip",
+              "archiveFileName": "esptool-v5.0.0-windows-amd64.zip",
+              "checksum": "SHA-256:2294107f66db6f09b886b337728a981173c9e7eab45a030928a8a5a1370611ca",
+              "size": "59105322"
             }
           ]
         },

From ee021855a156847dfcf75a9aeb8d585213f09e42 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Wed, 9 Jul 2025 07:24:42 -0300
Subject: [PATCH 038/105] feat(docs_version): Update docs in update-version
 script (#11564)

* feat(docs_version): Update docs in update-version script

* fix(logging): Fix log message

* fix(idf_version): Add error if IDF version is not found
---
 .github/scripts/update-version.sh | 14 ++++++++++++++
 docs/conf_common.py               |  2 +-
 2 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/.github/scripts/update-version.sh b/.github/scripts/update-version.sh
index 9a38b27a57a..622f2fe8ff8 100755
--- a/.github/scripts/update-version.sh
+++ b/.github/scripts/update-version.sh
@@ -1,4 +1,5 @@
 #!/bin/bash
+# Disable shellcheck warning about using 'cat' to read a file.
 # shellcheck disable=SC2002
 
 # For reference: add tools for all boards by replacing one line in each board
@@ -23,7 +24,15 @@ ESP_ARDUINO_VERSION_MINOR="$2"
 ESP_ARDUINO_VERSION_PATCH="$3"
 ESP_ARDUINO_VERSION="$ESP_ARDUINO_VERSION_MAJOR.$ESP_ARDUINO_VERSION_MINOR.$ESP_ARDUINO_VERSION_PATCH"
 
+# Get ESP-IDF version from push.yml (this way we can ensure that the version is correct even if the local libs are not up to date)
+ESP_IDF_VERSION=$(grep "idf_ver:" .github/workflows/push.yml | sed 's/.*release-v\([^"]*\).*/\1/')
+if [ -z "$ESP_IDF_VERSION" ]; then
+    echo "Error: ESP-IDF version not found in push.yml" >&2
+    exit 1
+fi
+
 echo "New Arduino Version: $ESP_ARDUINO_VERSION"
+echo "ESP-IDF Version: $ESP_IDF_VERSION"
 
 echo "Updating platform.txt..."
 cat platform.txt | sed "s/version=.*/version=$ESP_ARDUINO_VERSION/g" > __platform.txt && mv __platform.txt platform.txt
@@ -31,6 +40,11 @@ cat platform.txt | sed "s/version=.*/version=$ESP_ARDUINO_VERSION/g" > __platfor
 echo "Updating package.json..."
 cat package.json | sed "s/.*\"version\":.*/  \"version\": \"$ESP_ARDUINO_VERSION\",/g" > __package.json && mv __package.json package.json
 
+echo "Updating docs/conf_common.py..."
+cat docs/conf_common.py | \
+sed "s/.. |version| replace:: .*/.. |version| replace:: $ESP_ARDUINO_VERSION/g" | \
+sed "s/.. |idf_version| replace:: .*/.. |idf_version| replace:: $ESP_IDF_VERSION/g" > docs/__conf_common.py && mv docs/__conf_common.py docs/conf_common.py
+
 echo "Updating cores/esp32/esp_arduino_version.h..."
 cat cores/esp32/esp_arduino_version.h | \
 sed "s/#define ESP_ARDUINO_VERSION_MAJOR.*/#define ESP_ARDUINO_VERSION_MAJOR $ESP_ARDUINO_VERSION_MAJOR/g" | \
diff --git a/docs/conf_common.py b/docs/conf_common.py
index 6945c0d190d..af1d615f753 100644
--- a/docs/conf_common.py
+++ b/docs/conf_common.py
@@ -4,7 +4,7 @@
 
 # Used for substituting variables in the documentation
 rst_prolog = """
-.. |version| replace:: 3.2.0
+.. |version| replace:: 3.2.1
 .. |idf_version| replace:: 5.4
 """
 

From 87b718a59cbeed010eee2c6a79004e22f71564ac Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Wed, 9 Jul 2025 07:25:16 -0300
Subject: [PATCH 039/105] fix(merge): Fix merging CN Json (#11574)

---
 .github/scripts/merge_packages.py    | 16 ++++++++--------
 .github/scripts/release_append_cn.py |  5 +++--
 2 files changed, 11 insertions(+), 10 deletions(-)

diff --git a/.github/scripts/merge_packages.py b/.github/scripts/merge_packages.py
index 7e4f47ca8b3..8d1f200ec5c 100755
--- a/.github/scripts/merge_packages.py
+++ b/.github/scripts/merge_packages.py
@@ -4,6 +4,7 @@
 # Usage:
 #   python merge_packages.py package_esp8266com_index.json version/new/package_esp8266com_index.json
 # Written by Ivan Grokhotkov, 2015
+# Updated by lucasssvaz to handle Chinese version sorting, 2025
 #
 
 from __future__ import print_function
@@ -36,20 +37,19 @@ def merge_objects(versions, obj):
 
 
 # Normalize ESP release version string (x.x.x) by adding '-rc<MAXINT>' (x.x.x-rc9223372036854775807)
-# to ensure having REL above any RC
+# to ensure having REL above any RC. CN version will be sorted after the official version if they happen
+# to be mixed (normally, CN and non-CN versions should not be mixed)
 # Dummy approach, functional anyway for current ESP package versioning
 # (unlike NormalizedVersion/LooseVersion/StrictVersion & similar crap)
 def pkgVersionNormalized(versionString):
-
-    verStr = str(versionString)
+    verStr = str(versionString).replace("-cn", "")
     verParts = re.split(r"\.|-rc|-alpha", verStr, flags=re.IGNORECASE)
 
     if len(verParts) == 3:
-        if sys.version_info > (3, 0):  # Python 3
-            verStr = str(versionString) + "-rc" + str(sys.maxsize)
-        else:  # Python 2
-            verStr = str(versionString) + "-rc" + str(sys.maxint)
-
+        if "-cn" in str(versionString):
+            verStr = verStr + "-rc" + str(sys.maxsize // 2)
+        else:
+            verStr = verStr + "-rc" + str(sys.maxsize)
     elif len(verParts) != 4:
         print("pkgVersionNormalized WARNING: unexpected version format: {0})".format(verStr), file=sys.stderr)
 
diff --git a/.github/scripts/release_append_cn.py b/.github/scripts/release_append_cn.py
index b29fe0c31ba..2342834bb7e 100755
--- a/.github/scripts/release_append_cn.py
+++ b/.github/scripts/release_append_cn.py
@@ -17,8 +17,9 @@
 
 def append_cn_to_versions(obj):
     if isinstance(obj, dict):
-        # dfu-util comes from arduino.cc and not from the Chinese mirrors, so we skip it
-        if obj.get("name") == "dfu-util":
+        # Skip tools that are not from the esp32 package
+        packager = obj.get("packager")
+        if packager is not None and packager != "esp32":
             return
 
         for key, value in obj.items():

From 4ee17dea045b2b4f8bd5965bdde6e9110b612026 Mon Sep 17 00:00:00 2001
From: Sugar Glider <rodrigo.garcia@espressif.com>
Date: Fri, 11 Jul 2025 11:25:27 -0300
Subject: [PATCH 040/105] feat(matter): new matter lambda function example
 (#11561)

Adds a new Matter Library example using lambda function to creat 6 endpoints using a single callback
---
 .../MatterLambdaSingleCallbackManyEPs.ino     | 112 ++++++++++++++++++
 .../MatterLambdaSingleCallbackManyEPs/ci.json |   7 ++
 libraries/Matter/keywords.txt                 |   6 +
 3 files changed, 125 insertions(+)
 create mode 100644 libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/MatterLambdaSingleCallbackManyEPs.ino
 create mode 100644 libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/ci.json

diff --git a/libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/MatterLambdaSingleCallbackManyEPs.ino b/libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/MatterLambdaSingleCallbackManyEPs.ino
new file mode 100644
index 00000000000..4992771d925
--- /dev/null
+++ b/libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/MatterLambdaSingleCallbackManyEPs.ino
@@ -0,0 +1,112 @@
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+/*
+  This example creates 6 on-off light endpoints that share the same onChangeOnOff() callback code.
+  It uses Lambda Function with an extra Lambda Capture information that links the Endpoint to its individual information.
+  After the Matter example is commissioned, the expected Serial output shall be similar to this:
+
+Matter App Control: 'Room 1' (OnOffLight[0], Endpoint 1, GPIO 2) changed to: OFF
+Matter App Control: 'Room 1' (OnOffLight[0], Endpoint 1, GPIO 2) changed to: ON
+Matter App Control: 'Room 5' (OnOffLight[4], Endpoint 5, GPIO 10) changed to: ON
+Matter App Control: 'Room 2' (OnOffLight[1], Endpoint 2, GPIO 4) changed to: ON
+Matter App Control: 'Room 4' (OnOffLight[3], Endpoint 4, GPIO 8) changed to: ON
+Matter App Control: 'Room 6' (OnOffLight[5], Endpoint 6, GPIO 12) changed to: ON
+Matter App Control: 'Room 3' (OnOffLight[2], Endpoint 3, GPIO 6) changed to: ON
+Matter App Control: 'Room 5' (OnOffLight[4], Endpoint 5, GPIO 10) changed to: OFF
+*/
+
+// Matter Manager
+#include <Matter.h>
+#include <WiFi.h>
+
+// WiFi is manually set and started
+const char *ssid = "your-ssid";          // Change this to your WiFi SSID
+const char *password = "your-password";  // Change this to your WiFi password
+
+//number of On-Off Lights:
+const uint8_t MAX_LIGHT_NUMBER = 6;
+
+// array of OnOffLight endpoints
+MatterOnOffLight OnOffLight[MAX_LIGHT_NUMBER];
+
+// all pins, one for each on-off light
+uint8_t lightPins[MAX_LIGHT_NUMBER] = {2, 4, 6, 8, 10, 12};  // must replace it by the real pin for the target SoC and application
+
+// friendly OnOffLights names used for printing a message in the callback
+const char *lightName[MAX_LIGHT_NUMBER] = {
+  "Room 1", "Room 2", "Room 3", "Room 4", "Room 5", "Room 6",
+};
+
+// simple setup() function
+void setup() {
+  Serial.begin(115200);  // callback will just print a message in the console
+
+  // We start by connecting to a WiFi network
+  Serial.print("Connecting to ");
+  Serial.println(ssid);
+  // Manually connect to WiFi
+  WiFi.begin(ssid, password);
+  // Wait for connection
+  while (WiFi.status() != WL_CONNECTED) {
+    delay(500);
+    Serial.print(".");
+  }
+  Serial.println("\r\nWiFi connected");
+  Serial.println("IP address: ");
+  Serial.println(WiFi.localIP());
+  delay(500);
+
+  // setup all the OnOff Light endpoint and their lambda callback functions
+  for (uint8_t i = 0; i < MAX_LIGHT_NUMBER; i++) {
+    pinMode(lightPins[i], OUTPUT);  // set the GPIO function
+    OnOffLight[i].begin(false);     // off
+
+    // inline lambda function using capture array index -> it will just print a message in the console
+    OnOffLight[i].onChangeOnOff([i](bool state) -> bool {
+      // Display message with the specific light name and details
+      Serial.printf(
+        "Matter App Control: '%s' (OnOffLight[%d], Endpoint %d, GPIO %d) changed to: %s\r\n", lightName[i], i, OnOffLight[i].getEndPointId(), lightPins[i],
+        state ? "ON" : "OFF"
+      );
+
+      return true;
+    });
+  }
+  // last step, starting Matter Stack
+  Matter.begin();
+}
+
+void loop() {
+  // Check Matter Plugin Commissioning state, which may change during execution of loop()
+  if (!Matter.isDeviceCommissioned()) {
+    Serial.println("");
+    Serial.println("Matter Node is not commissioned yet.");
+    Serial.println("Initiate the device discovery in your Matter environment.");
+    Serial.println("Commission it to your Matter hub with the manual pairing code or QR code");
+    Serial.printf("Manual pairing code: %s\r\n", Matter.getManualPairingCode().c_str());
+    Serial.printf("QR code URL: %s\r\n", Matter.getOnboardingQRCodeUrl().c_str());
+    // waits for Matter Plugin Commissioning.
+    uint32_t timeCount = 0;
+    while (!Matter.isDeviceCommissioned()) {
+      delay(100);
+      if ((timeCount++ % 50) == 0) {  // 50*100ms = 5 sec
+        Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
+      }
+    }
+    Serial.println("Matter Node is commissioned and connected to the WiFi network. Ready for use.");
+  }
+
+  delay(500);
+}
diff --git a/libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/ci.json b/libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/ci.json
new file mode 100644
index 00000000000..556a8a9ee6b
--- /dev/null
+++ b/libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/ci.json
@@ -0,0 +1,7 @@
+{
+  "fqbn_append": "PartitionScheme=huge_app",
+  "requires": [
+    "CONFIG_SOC_WIFI_SUPPORTED=y",
+    "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
+  ]
+}
diff --git a/libraries/Matter/keywords.txt b/libraries/Matter/keywords.txt
index 68aaebb1d4d..edba06083bd 100644
--- a/libraries/Matter/keywords.txt
+++ b/libraries/Matter/keywords.txt
@@ -36,8 +36,10 @@ EndPointSpeedCB	KEYWORD1
 EndPointOnOffCB	KEYWORD1
 EndPointBrightnessCB	KEYWORD1
 EndPointRGBColorCB	KEYWORD1
+EndPointIdentifyCB	KEYWORD1
 matterEvent_t	KEYWORD1
 matterEventCB	KEYWORD1
+attrOperation_t	KEYWORD1
 
 #######################################
 # Methods and Functions (KEYWORD2)
@@ -111,6 +113,10 @@ onChangeLocalTemperature	KEYWORD2
 onChangeCoolingSetpoint	KEYWORD2
 onChangeHeatingSetpoint	KEYWORD2
 onEvent	KEYWORD2
+setEndPointId	KEYWORD2
+getEndPointId	KEYWORD2
+onIdentify	KEYWORD2
+endpointIdentifyCB	KEYWORD2
 
 #######################################
 # Constants (LITERAL1)

From c6a3bcb014c7fff53e6c1c41fec50e3ec4de8514 Mon Sep 17 00:00:00 2001
From: Sugar Glider <rodrigo.garcia@espressif.com>
Date: Sat, 12 Jul 2025 00:11:41 -0300
Subject: [PATCH 041/105] feat(matter): removing wifi requirement for H2 and C5
 (#11581)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This PR removes WiFi provisioning support from CI and examples (shifting to Thread/BLE provisioning), updates the CI configs for all Matter examples to drop the WiFi requirement, and adds new API keywords and a fresh “LambdaSingleCallbackManyEPs” example.

- Deleted the WiFiProvWithinMatter example (its .ino and ci.json) since BLE is now used for provisioning.
- Stripped "CONFIG_SOC_WIFI_SUPPORTED=y" from the CI JSON of existing examples to test Thread-only builds.
- Updated keywords.txt with new Matter API identifiers and introduced a new “LambdaSingleCallbackManyEPs” example with CI and source
---
 .../Matter/examples/MatterColorLight/ci.json  |  11 +-
 .../examples/MatterCommissionTest/ci.json     |   1 -
 .../examples/MatterComposedLights/ci.json     |   1 -
 .../examples/MatterContactSensor/ci.json      |   1 -
 .../examples/MatterDimmableLight/ci.json      |   1 -
 .../examples/MatterEnhancedColorLight/ci.json |   9 +-
 .../Matter/examples/MatterEvents/ci.json      |   1 -
 libraries/Matter/examples/MatterFan/ci.json   |   9 +-
 .../examples/MatterHumiditySensor/ci.json     |   1 -
 .../MatterLambdaSingleCallbackManyEPs.ino     | 126 +++++++++++++++
 .../MatterLambdaSingleCallbackManyEPs/ci.json |   6 +
 .../Matter/examples/MatterMinimum/ci.json     |   1 -
 .../examples/MatterOccupancySensor/ci.json    |   1 -
 .../Matter/examples/MatterOnIdentify/ci.json  |   1 -
 .../Matter/examples/MatterOnOffLight/ci.json  |   1 -
 .../Matter/examples/MatterOnOffPlugin/ci.json |   1 -
 .../examples/MatterPressureSensor/ci.json     |   1 -
 .../Matter/examples/MatterSmartButon/ci.json  |   1 -
 .../examples/MatterTemperatureLight/ci.json   |   1 -
 .../examples/MatterTemperatureSensor/ci.json  |   1 -
 .../Matter/examples/MatterThermostat/ci.json  |   1 -
 .../WiFiProvWithinMatter.ino                  | 152 ------------------
 .../examples/WiFiProvWithinMatter/ci.json     |   7 -
 libraries/Matter/keywords.txt                 |   8 +
 24 files changed, 153 insertions(+), 191 deletions(-)
 create mode 100644 libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/MatterLambdaSingleCallbackManyEPs.ino
 create mode 100644 libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/ci.json
 delete mode 100644 libraries/Matter/examples/WiFiProvWithinMatter/WiFiProvWithinMatter.ino
 delete mode 100644 libraries/Matter/examples/WiFiProvWithinMatter/ci.json

diff --git a/libraries/Matter/examples/MatterColorLight/ci.json b/libraries/Matter/examples/MatterColorLight/ci.json
index d5f63487506..90b393f9156 100644
--- a/libraries/Matter/examples/MatterColorLight/ci.json
+++ b/libraries/Matter/examples/MatterColorLight/ci.json
@@ -1,7 +1,6 @@
 {
-    "fqbn_append": "PartitionScheme=huge_app",
-    "requires": [
-      "CONFIG_SOC_WIFI_SUPPORTED=y",
-      "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
-    ]
-  }
+  "fqbn_append": "PartitionScheme=huge_app",
+  "requires": [
+    "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
+  ]
+}
diff --git a/libraries/Matter/examples/MatterCommissionTest/ci.json b/libraries/Matter/examples/MatterCommissionTest/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterCommissionTest/ci.json
+++ b/libraries/Matter/examples/MatterCommissionTest/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterComposedLights/ci.json b/libraries/Matter/examples/MatterComposedLights/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterComposedLights/ci.json
+++ b/libraries/Matter/examples/MatterComposedLights/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterContactSensor/ci.json b/libraries/Matter/examples/MatterContactSensor/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterContactSensor/ci.json
+++ b/libraries/Matter/examples/MatterContactSensor/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterDimmableLight/ci.json b/libraries/Matter/examples/MatterDimmableLight/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterDimmableLight/ci.json
+++ b/libraries/Matter/examples/MatterDimmableLight/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterEnhancedColorLight/ci.json b/libraries/Matter/examples/MatterEnhancedColorLight/ci.json
index 0665800b12b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterEnhancedColorLight/ci.json
+++ b/libraries/Matter/examples/MatterEnhancedColorLight/ci.json
@@ -1,7 +1,6 @@
 {
-    "fqbn_append": "PartitionScheme=huge_app",
-    "requires": [
-      "CONFIG_SOC_WIFI_SUPPORTED=y",
-      "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
-    ]
+  "fqbn_append": "PartitionScheme=huge_app",
+  "requires": [
+    "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
+  ]
 }
diff --git a/libraries/Matter/examples/MatterEvents/ci.json b/libraries/Matter/examples/MatterEvents/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterEvents/ci.json
+++ b/libraries/Matter/examples/MatterEvents/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterFan/ci.json b/libraries/Matter/examples/MatterFan/ci.json
index 0665800b12b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterFan/ci.json
+++ b/libraries/Matter/examples/MatterFan/ci.json
@@ -1,7 +1,6 @@
 {
-    "fqbn_append": "PartitionScheme=huge_app",
-    "requires": [
-      "CONFIG_SOC_WIFI_SUPPORTED=y",
-      "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
-    ]
+  "fqbn_append": "PartitionScheme=huge_app",
+  "requires": [
+    "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
+  ]
 }
diff --git a/libraries/Matter/examples/MatterHumiditySensor/ci.json b/libraries/Matter/examples/MatterHumiditySensor/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterHumiditySensor/ci.json
+++ b/libraries/Matter/examples/MatterHumiditySensor/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/MatterLambdaSingleCallbackManyEPs.ino b/libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/MatterLambdaSingleCallbackManyEPs.ino
new file mode 100644
index 00000000000..c60cadd784f
--- /dev/null
+++ b/libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/MatterLambdaSingleCallbackManyEPs.ino
@@ -0,0 +1,126 @@
+// Copyright 2025 Espressif Systems (Shanghai) PTE LTD
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+/*
+  This example create 6 on-off light endpoint that share the same onChangeOnOff() callback code.
+  It uses Lambda Function with an extra Lambda Capture information that links the Endpoint to its individual information.
+  After the Matter example is commissioned, the expected Serial output shall be similar to this:
+
+Matter App Control: 'Room 1' (OnOffLight[0], Endpoint 1, GPIO 2) changed to: OFF
+Matter App Control: 'Room 1' (OnOffLight[0], Endpoint 1, GPIO 2) changed to: ON
+Matter App Control: 'Room 5' (OnOffLight[4], Endpoint 5, GPIO 10) changed to: ON
+Matter App Control: 'Room 2' (OnOffLight[1], Endpoint 2, GPIO 4) changed to: ON
+Matter App Control: 'Room 4' (OnOffLight[3], Endpoint 4, GPIO 8) changed to: ON
+Matter App Control: 'Room 6' (OnOffLight[5], Endpoint 6, GPIO 12) changed to: ON
+Matter App Control: 'Room 3' (OnOffLight[2], Endpoint 3, GPIO 6) changed to: ON
+Matter App Control: 'Room 5' (OnOffLight[4], Endpoint 5, GPIO 10) changed to: OFF
+*/
+
+// Matter Manager
+#include <Matter.h>
+#include <Preferences.h>
+#if !CONFIG_ENABLE_CHIPOBLE
+// if the device can be commissioned using BLE, WiFi is not used - save flash space
+#include <WiFi.h>
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+// WiFi is manually set and started
+const char *ssid = "your-ssid";          // Change this to your WiFi SSID
+const char *password = "your-password";  // Change this to your WiFi password
+#endif
+
+//number of On-Off Lights:
+const uint8_t MAX_LIGHT_NUMBER = 6;
+
+// array of OnOffLight endpoints
+MatterOnOffLight OnOffLight[MAX_LIGHT_NUMBER];
+
+// all pins, one for each on-off light
+uint8_t lightPins[MAX_LIGHT_NUMBER] = {2, 4, 6, 8, 10, 12};  // must replace it by the real pin for the target SoC and application
+
+// friendly OnOffLights names used for printing a message in the callback
+const char *lightName[MAX_LIGHT_NUMBER] = {
+  "Room 1", "Room 2", "Room 3", "Room 4", "Room 5", "Room 6",
+};
+
+// simple setup() function
+void setup() {
+  Serial.begin(115200);  // callback will just print a message in the console
+
+// CONFIG_ENABLE_CHIPOBLE is enabled when BLE is used to commission the Matter Network
+#if !CONFIG_ENABLE_CHIPOBLE
+  // We start by connecting to a WiFi network
+  Serial.print("Connecting to ");
+  Serial.println(ssid);
+  // Manually connect to WiFi
+  WiFi.begin(ssid, password);
+  // Wait for connection
+  while (WiFi.status() != WL_CONNECTED) {
+    delay(500);
+    Serial.print(".");
+  }
+  Serial.println("\r\nWiFi connected");
+  Serial.println("IP address: ");
+  Serial.println(WiFi.localIP());
+  delay(500);
+#endif
+
+  // setup all the OnOff Light endpoint and their lambda callback functions
+  for (uint8_t i = 0; i < MAX_LIGHT_NUMBER; i++) {
+    pinMode(lightPins[i], OUTPUT);  // set the GPIO function
+    OnOffLight[i].begin(false);     // off
+
+    // inline lambda function using capture array index -> it will just print a message in the console
+    OnOffLight[i].onChangeOnOff([i](bool state) -> bool {
+      // Display message with the specific light name and details
+      Serial.printf(
+        "Matter App Control: '%s' (OnOffLight[%d], Endpoint %d, GPIO %d) changed to: %s\r\n", lightName[i], i, OnOffLight[i].getEndPointId(), lightPins[i],
+        state ? "ON" : "OFF"
+      );
+
+      return true;
+    });
+  }
+  // last step, starting Matter Stack
+  Matter.begin();
+}
+
+void loop() {
+  // Check Matter Plugin Commissioning state, which may change during execution of loop()
+  if (!Matter.isDeviceCommissioned()) {
+    Serial.println("");
+    Serial.println("Matter Node is not commissioned yet.");
+    Serial.println("Initiate the device discovery in your Matter environment.");
+    Serial.println("Commission it to your Matter hub with the manual pairing code or QR code");
+    Serial.printf("Manual pairing code: %s\r\n", Matter.getManualPairingCode().c_str());
+    Serial.printf("QR code URL: %s\r\n", Matter.getOnboardingQRCodeUrl().c_str());
+    // waits for Matter Plugin Commissioning.
+    uint32_t timeCount = 0;
+    while (!Matter.isDeviceCommissioned()) {
+      delay(100);
+      if ((timeCount++ % 50) == 0) {  // 50*100ms = 5 sec
+        Serial.println("Matter Node not commissioned yet. Waiting for commissioning.");
+      }
+    }
+  } else {
+    if (Matter.isDeviceConnected()) {
+      Serial.println("Matter Node is commissioned and connected to the network. Ready for use.");
+    } else {
+      Serial.println("Matter Node is commissioned. Waiting for the network connection.");
+    }
+    // wait 3 seconds for the network connection
+    delay(3000);
+  }
+
+  delay(100);
+}
diff --git a/libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/ci.json b/libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/ci.json
new file mode 100644
index 00000000000..90b393f9156
--- /dev/null
+++ b/libraries/Matter/examples/MatterLambdaSingleCallbackManyEPs/ci.json
@@ -0,0 +1,6 @@
+{
+  "fqbn_append": "PartitionScheme=huge_app",
+  "requires": [
+    "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
+  ]
+}
diff --git a/libraries/Matter/examples/MatterMinimum/ci.json b/libraries/Matter/examples/MatterMinimum/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterMinimum/ci.json
+++ b/libraries/Matter/examples/MatterMinimum/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterOccupancySensor/ci.json b/libraries/Matter/examples/MatterOccupancySensor/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterOccupancySensor/ci.json
+++ b/libraries/Matter/examples/MatterOccupancySensor/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterOnIdentify/ci.json b/libraries/Matter/examples/MatterOnIdentify/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterOnIdentify/ci.json
+++ b/libraries/Matter/examples/MatterOnIdentify/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterOnOffLight/ci.json b/libraries/Matter/examples/MatterOnOffLight/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterOnOffLight/ci.json
+++ b/libraries/Matter/examples/MatterOnOffLight/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterOnOffPlugin/ci.json b/libraries/Matter/examples/MatterOnOffPlugin/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterOnOffPlugin/ci.json
+++ b/libraries/Matter/examples/MatterOnOffPlugin/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterPressureSensor/ci.json b/libraries/Matter/examples/MatterPressureSensor/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterPressureSensor/ci.json
+++ b/libraries/Matter/examples/MatterPressureSensor/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterSmartButon/ci.json b/libraries/Matter/examples/MatterSmartButon/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterSmartButon/ci.json
+++ b/libraries/Matter/examples/MatterSmartButon/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterTemperatureLight/ci.json b/libraries/Matter/examples/MatterTemperatureLight/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterTemperatureLight/ci.json
+++ b/libraries/Matter/examples/MatterTemperatureLight/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterTemperatureSensor/ci.json b/libraries/Matter/examples/MatterTemperatureSensor/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterTemperatureSensor/ci.json
+++ b/libraries/Matter/examples/MatterTemperatureSensor/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/MatterThermostat/ci.json b/libraries/Matter/examples/MatterThermostat/ci.json
index 556a8a9ee6b..90b393f9156 100644
--- a/libraries/Matter/examples/MatterThermostat/ci.json
+++ b/libraries/Matter/examples/MatterThermostat/ci.json
@@ -1,7 +1,6 @@
 {
   "fqbn_append": "PartitionScheme=huge_app",
   "requires": [
-    "CONFIG_SOC_WIFI_SUPPORTED=y",
     "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
   ]
 }
diff --git a/libraries/Matter/examples/WiFiProvWithinMatter/WiFiProvWithinMatter.ino b/libraries/Matter/examples/WiFiProvWithinMatter/WiFiProvWithinMatter.ino
deleted file mode 100644
index 3434217624d..00000000000
--- a/libraries/Matter/examples/WiFiProvWithinMatter/WiFiProvWithinMatter.ino
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
-  Please read README.md file in this folder, or on the web:
-  https://github.com/espressif/arduino-esp32/tree/master/libraries/WiFiProv/examples/WiFiProv
-
-  Note: This sketch takes up a lot of space for the app and may not be able to flash with default setting on some chips.
-  If you see Error like this: "Sketch too big"
-  In Arduino IDE go to: Tools > Partition scheme > chose anything that has more than 1.4MB APP
-   - for example "No OTA (2MB APP/2MB SPIFFS)"
-
-  This example demonstrates that it is possible to provision WiFi using BLE or Software AP using
-  the ESP BLE Prov APP or ESP SoftAP Provisioning APP from Android Play or/and iOS APP Store
-
-  Once the WiFi is provisioned, Matter will start its process as usual.
-
-  This same Example could be used for any other WiFi Provisioning method.
-*/
-
-// Matter Manager
-#include <Matter.h>
-#include <WiFiProv.h>
-#include <WiFi.h>
-
-#if !CONFIG_BLUEDROID_ENABLED
-#define USE_SOFT_AP  // ESP32-S2 has no BLE, therefore, it shall use SoftAP Provisioning
-#endif
-//#define USE_SOFT_AP // Uncomment if you want to enforce using the Soft AP method instead of BLE
-
-const char *pop = "abcd1234";           // Proof of possession - otherwise called a PIN - string provided by the device, entered by the user in the phone app
-const char *service_name = "PROV_123";  // Name of your device (the Espressif apps expects by default device name starting with "Prov_")
-const char *service_key = NULL;         // Password used for SofAP method (NULL = no password needed)
-bool reset_provisioned = true;          // When true the library will automatically delete previously provisioned data.
-
-// List of Matter Endpoints for this Node
-// Single On/Off Light Endpoint - at least one per node
-MatterOnOffLight OnOffLight;
-
-// Light GPIO that can be controlled by Matter APP
-#ifdef LED_BUILTIN
-const uint8_t ledPin = LED_BUILTIN;
-#else
-const uint8_t ledPin = 2;  // Set your pin here if your board has not defined LED_BUILTIN
-#endif
-
-// set your board USER BUTTON pin here - decommissioning button
-const uint8_t buttonPin = BOOT_PIN;  // Set your pin here. Using BOOT Button.
-
-// Button control - decommision the Matter Node
-uint32_t button_time_stamp = 0;                // debouncing control
-bool button_state = false;                     // false = released | true = pressed
-const uint32_t decommissioningTimeout = 5000;  // keep the button pressed for 5s, or longer, to decommission
-
-// Matter Protocol Endpoint (On/OFF Light) Callback
-bool matterCB(bool state) {
-  digitalWrite(ledPin, state ? HIGH : LOW);
-  // This callback must return the success state to Matter core
-  return true;
-}
-
-void setup() {
-  // Initialize the USER BUTTON (Boot button) that will be used to decommission the Matter Node
-  pinMode(buttonPin, INPUT_PULLUP);
-
-  Serial.begin(115200);
-  // Initialize the LED GPIO
-  pinMode(ledPin, OUTPUT);
-
-  WiFi.begin();  // no SSID/PWD - get it from the Provisioning APP or from NVS (last successful connection)
-
-  // BLE Provisioning using the ESP SoftAP Prov works fine for any BLE SoC, including ESP32, ESP32S3 and ESP32C3.
-#if CONFIG_BLUEDROID_ENABLED && !defined(USE_SOFT_AP)
-  Serial.println("Begin Provisioning using BLE");
-  // Sample uuid that user can pass during provisioning using BLE
-  uint8_t uuid[16] = {0xb4, 0xdf, 0x5a, 0x1c, 0x3f, 0x6b, 0xf4, 0xbf, 0xea, 0x4a, 0x82, 0x03, 0x04, 0x90, 0x1a, 0x02};
-  WiFiProv.beginProvision(
-    NETWORK_PROV_SCHEME_BLE, NETWORK_PROV_SCHEME_HANDLER_FREE_BLE, NETWORK_PROV_SECURITY_1, pop, service_name, service_key, uuid, reset_provisioned
-  );
-  Serial.println("You may use this BLE QRCode:");
-  WiFiProv.printQR(service_name, pop, "ble");
-#else
-  Serial.println("Begin Provisioning using Soft AP");
-  WiFiProv.beginProvision(NETWORK_PROV_SCHEME_SOFTAP, NETWORK_PROV_SCHEME_HANDLER_NONE, NETWORK_PROV_SECURITY_1, pop, service_name, service_key);
-  Serial.println("You may use this WiFi QRCode:");
-  WiFiProv.printQR(service_name, pop, "softap");
-#endif
-
-  // Wait for WiFi connection
-  uint32_t counter = 0;
-  while (WiFi.status() != WL_CONNECTED) {
-    // resets the device after 10 minutes
-    if (counter > 2 * 60 * 10) {
-      Serial.println("\r\n================================================");
-      Serial.println("Already 10 minutes past. The device will reboot.");
-      Serial.println("================================================\r\n");
-      Serial.flush();  // wait until the Serial has sent the whole message.
-      ESP.restart();
-    }
-    // WiFi searching feedback
-    Serial.print(".");
-    delay(500);
-    // adds a new line every 30 seconds
-    counter++;
-    if (!(counter % 60)) {
-      Serial.println();
-    }
-  }
-
-  // WiFi shall be connected by now
-  Serial.println();
-
-  // Initialize at least one Matter EndPoint
-  OnOffLight.begin();
-
-  // Associate a callback to the Matter Controller
-  OnOffLight.onChange(matterCB);
-
-  // Matter beginning - Last step, after all EndPoints are initialized
-  Matter.begin();
-
-  while (!Matter.isDeviceCommissioned()) {
-    Serial.println("Matter Node is not commissioned yet.");
-    Serial.println("Initiate the device discovery in your Matter environment.");
-    Serial.println("Commission it to your Matter hub with the manual pairing code or QR code");
-    Serial.printf("Manual pairing code: %s\r\n", Matter.getManualPairingCode().c_str());
-    Serial.printf("QR code URL: %s\r\n", Matter.getOnboardingQRCodeUrl().c_str());
-    Serial.println();
-    // waits 30 seconds for Matter Commissioning, keeping it blocked until done
-    delay(30000);
-  }
-}
-
-void loop() {
-  // Check if the button has been pressed
-  if (digitalRead(buttonPin) == LOW && !button_state) {
-    // deals with button debouncing
-    button_time_stamp = millis();  // record the time while the button is pressed.
-    button_state = true;           // pressed.
-  }
-
-  if (digitalRead(buttonPin) == HIGH && button_state) {
-    button_state = false;  // released
-  }
-
-  // Onboard User Button is kept pressed for longer than 5 seconds in order to decommission matter node
-  uint32_t time_diff = millis() - button_time_stamp;
-  if (button_state && time_diff > decommissioningTimeout) {
-    Serial.println("Decommissioning the Light Matter Accessory. It shall be commissioned again.");
-    Matter.decommission();
-    button_time_stamp = millis();  // avoid running decommissining again, reboot takes a second or so
-  }
-
-  delay(500);
-}
diff --git a/libraries/Matter/examples/WiFiProvWithinMatter/ci.json b/libraries/Matter/examples/WiFiProvWithinMatter/ci.json
deleted file mode 100644
index 0665800b12b..00000000000
--- a/libraries/Matter/examples/WiFiProvWithinMatter/ci.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
-    "fqbn_append": "PartitionScheme=huge_app",
-    "requires": [
-      "CONFIG_SOC_WIFI_SUPPORTED=y",
-      "CONFIG_ESP_MATTER_ENABLE_DATA_MODEL=y"
-    ]
-}
diff --git a/libraries/Matter/keywords.txt b/libraries/Matter/keywords.txt
index 68aaebb1d4d..6c2e092e417 100644
--- a/libraries/Matter/keywords.txt
+++ b/libraries/Matter/keywords.txt
@@ -36,8 +36,10 @@ EndPointSpeedCB	KEYWORD1
 EndPointOnOffCB	KEYWORD1
 EndPointBrightnessCB	KEYWORD1
 EndPointRGBColorCB	KEYWORD1
+EndPointIdentifyCB	KEYWORD1
 matterEvent_t	KEYWORD1
 matterEventCB	KEYWORD1
+attrOperation_t	KEYWORD1
 
 #######################################
 # Methods and Functions (KEYWORD2)
@@ -111,6 +113,12 @@ onChangeLocalTemperature	KEYWORD2
 onChangeCoolingSetpoint	KEYWORD2
 onChangeHeatingSetpoint	KEYWORD2
 onEvent	KEYWORD2
+setEndPointId	KEYWORD2
+getEndPointId	KEYWORD2
+getSecondaryNetworkEndPointId	KEYWORD2
+createSecondaryNetworkInterface	KEYWORD2
+onIdentify	KEYWORD2
+endpointIdentifyCB	KEYWORD2
 
 #######################################
 # Constants (LITERAL1)

From 0a45a0614244002f82fe7f006effeda7c8075469 Mon Sep 17 00:00:00 2001
From: Sugar Glider <rodrigo.garcia@espressif.com>
Date: Sat, 12 Jul 2025 02:12:36 -0300
Subject: [PATCH 042/105] feat(wire):  std::functional Wire slave callback
 functions (#11582)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This PR enhances the Wire library to support std::function–based callbacks for I2C slave mode, enabling the use of lambdas and captured contexts.

- Replaces raw function pointers in TwoWire and HardwareI2C with std::function for onRequest and onReceive
- Updates constructors, method signatures, and default initializations to use std::function
- Adds new example sketch, CI config, and documentation updates demonstrating the functional callback API
---
 cores/esp32/HardwareI2C.h                     |   6 +-
 docs/en/api/i2c.rst                           | 135 +++++++++++++++++-
 .../WireSlaveFunctionalCallback.ino           |  37 +++++
 .../WireSlaveFunctionalCallback/ci.json       |   5 +
 libraries/Wire/src/Wire.cpp                   |   6 +-
 libraries/Wire/src/Wire.h                     |  12 +-
 6 files changed, 184 insertions(+), 17 deletions(-)
 create mode 100644 libraries/Wire/examples/WireSlaveFunctionalCallback/WireSlaveFunctionalCallback.ino
 create mode 100644 libraries/Wire/examples/WireSlaveFunctionalCallback/ci.json

diff --git a/cores/esp32/HardwareI2C.h b/cores/esp32/HardwareI2C.h
index 65b7e2036b2..c44f34e1ee7 100644
--- a/cores/esp32/HardwareI2C.h
+++ b/cores/esp32/HardwareI2C.h
@@ -20,6 +20,7 @@
 
 #include <inttypes.h>
 #include "Stream.h"
+#include <functional>
 
 class HardwareI2C : public Stream {
 public:
@@ -36,6 +37,7 @@ class HardwareI2C : public Stream {
   virtual size_t requestFrom(uint8_t address, size_t len, bool stopBit) = 0;
   virtual size_t requestFrom(uint8_t address, size_t len) = 0;
 
-  virtual void onReceive(void (*)(int)) = 0;
-  virtual void onRequest(void (*)(void)) = 0;
+  // Update base class to use std::function
+  virtual void onReceive(const std::function<void(int)> &) = 0;
+  virtual void onRequest(const std::function<void()> &) = 0;
 };
diff --git a/docs/en/api/i2c.rst b/docs/en/api/i2c.rst
index eac04b76a23..06d4d1953a6 100644
--- a/docs/en/api/i2c.rst
+++ b/docs/en/api/i2c.rst
@@ -347,20 +347,147 @@ This function will return ``true`` if the peripheral was initialized correctly.
 onReceive
 ^^^^^^^^^
 
-The ``onReceive`` function is used to define the callback for the data received from the master.
+The ``onReceive`` function is used to define the callback for data received from the master device.
 
 .. code-block:: arduino
 
-    void onReceive( void (*)(int) );
+    void onReceive(const std::function<void(int)>& callback);
+
+**Function Signature:**
+
+The callback function must have the signature ``void(int numBytes)`` where ``numBytes`` indicates how many bytes were received from the master.
+
+**Usage Examples:**
+
+.. code-block:: arduino
+
+    // Method 1: Regular function
+    void handleReceive(int numBytes) {
+        Serial.printf("Received %d bytes: ", numBytes);
+        while (Wire.available()) {
+            char c = Wire.read();
+            Serial.print(c);
+        }
+        Serial.println();
+    }
+    Wire.onReceive(handleReceive);
+
+    // Method 2: Lambda function
+    Wire.onReceive([](int numBytes) {
+        Serial.printf("Master sent %d bytes\n", numBytes);
+        while (Wire.available()) {
+            uint8_t data = Wire.read();
+            // Process received data
+            Serial.printf("Data: 0x%02X\n", data);
+        }
+    });
+
+    // Method 3: Lambda with capture (for accessing variables)
+    int deviceId = 42;
+    Wire.onReceive([deviceId](int numBytes) {
+        Serial.printf("Device %d received %d bytes\n", deviceId, numBytes);
+        // Process data...
+    });
+
+    // Method 4: Using std::function variable
+    std::function<void(int)> receiveHandler = [](int bytes) {
+        Serial.printf("Handling %d received bytes\n", bytes);
+    };
+    Wire.onReceive(receiveHandler);
+
+    // Method 5: Class member function (using lambda wrapper)
+    class I2CDevice {
+    private:
+        int deviceAddress;
+    public:
+        I2CDevice(int addr) : deviceAddress(addr) {}
+
+        void handleReceive(int numBytes) {
+            Serial.printf("Device 0x%02X received %d bytes\n", deviceAddress, numBytes);
+        }
+
+        void setup() {
+            Wire.onReceive([this](int bytes) {
+                this->handleReceive(bytes);
+            });
+        }
+    };
+
+.. note::
+    The ``onReceive`` callback is triggered when the I2C master sends data to this slave device.
+    Use ``Wire.available()`` and ``Wire.read()`` inside the callback to retrieve the received data.
 
 onRequest
 ^^^^^^^^^
 
-The ``onRequest`` function is used to define the callback for the data to be send to the master.
+The ``onRequest`` function is used to define the callback for responding to master read requests.
+
+.. code-block:: arduino
+
+    void onRequest(const std::function<void()>& callback);
+
+**Function Signature:**
+
+The callback function must have the signature ``void()`` with no parameters. This callback is triggered when the master requests data from this slave device.
+
+**Usage Examples:**
 
 .. code-block:: arduino
 
-    void onRequest( void (*)(void) );
+    // Method 1: Regular function
+    void handleRequest() {
+        static int counter = 0;
+        Wire.printf("Response #%d", counter++);
+    }
+    Wire.onRequest(handleRequest);
+
+    // Method 2: Lambda function
+    Wire.onRequest([]() {
+        // Send sensor data to master
+        int sensorValue = analogRead(A0);
+        Wire.write(sensorValue >> 8);    // High byte
+        Wire.write(sensorValue & 0xFF);  // Low byte
+    });
+
+    // Method 3: Lambda with capture (for accessing variables)
+    int deviceStatus = 1;
+    String deviceName = "Sensor1";
+    Wire.onRequest([&deviceStatus, &deviceName]() {
+        Wire.write(deviceStatus);
+        Wire.write(deviceName.c_str(), deviceName.length());
+    });
+
+    // Method 4: Using std::function variable
+    std::function<void()> requestHandler = []() {
+        Wire.write("Hello Master!");
+    };
+    Wire.onRequest(requestHandler);
+
+    // Method 5: Class member function (using lambda wrapper)
+    class TemperatureSensor {
+    private:
+        float temperature;
+    public:
+        void updateTemperature() {
+            temperature = 25.5; // Read from actual sensor
+        }
+
+        void sendTemperature() {
+            // Convert float to bytes and send
+            uint8_t* tempBytes = (uint8_t*)&temperature;
+            Wire.write(tempBytes, sizeof(float));
+        }
+
+        void setup() {
+            Wire.onRequest([this]() {
+                this->sendTemperature();
+            });
+        }
+    };
+
+.. note::
+    The ``onRequest`` callback is triggered when the I2C master requests data from this slave device.
+    Use ``Wire.write()`` inside the callback to send response data back to the master.
 
 slaveWrite
 ^^^^^^^^^^
diff --git a/libraries/Wire/examples/WireSlaveFunctionalCallback/WireSlaveFunctionalCallback.ino b/libraries/Wire/examples/WireSlaveFunctionalCallback/WireSlaveFunctionalCallback.ino
new file mode 100644
index 00000000000..a18fd2f023e
--- /dev/null
+++ b/libraries/Wire/examples/WireSlaveFunctionalCallback/WireSlaveFunctionalCallback.ino
@@ -0,0 +1,37 @@
+// This example demonstrates the use of functional callbacks with the Wire library
+// for I2C slave communication. It shows how to handle requests and data reception
+
+#include "Wire.h"
+
+#define I2C_DEV_ADDR 0x55
+
+uint32_t i = 0;
+
+void setup() {
+  Serial.begin(115200);
+  Serial.setDebugOutput(true);
+
+  Wire.onRequest([]() {
+    Wire.print(i++);
+    Wire.print(" Packets.");
+    Serial.println("onRequest");
+  });
+
+  Wire.onReceive([](int len) {
+    Serial.printf("onReceive[%d]: ", len);
+    while (Wire.available()) {
+      Serial.write(Wire.read());
+    }
+    Serial.println();
+  });
+
+  Wire.begin((uint8_t)I2C_DEV_ADDR);
+
+#if CONFIG_IDF_TARGET_ESP32
+  char message[64];
+  snprintf(message, 64, "%lu Packets.", i++);
+  Wire.slaveWrite((uint8_t *)message, strlen(message));
+#endif
+}
+
+void loop() {}
diff --git a/libraries/Wire/examples/WireSlaveFunctionalCallback/ci.json b/libraries/Wire/examples/WireSlaveFunctionalCallback/ci.json
new file mode 100644
index 00000000000..3c877975d62
--- /dev/null
+++ b/libraries/Wire/examples/WireSlaveFunctionalCallback/ci.json
@@ -0,0 +1,5 @@
+{
+  "requires": [
+    "CONFIG_SOC_I2C_SUPPORT_SLAVE=y"
+  ]
+}
diff --git a/libraries/Wire/src/Wire.cpp b/libraries/Wire/src/Wire.cpp
index 34c814b5117..cda098d2d5b 100644
--- a/libraries/Wire/src/Wire.cpp
+++ b/libraries/Wire/src/Wire.cpp
@@ -48,7 +48,7 @@ TwoWire::TwoWire(uint8_t bus_num)
 #endif
 #if SOC_I2C_SUPPORT_SLAVE
     ,
-    is_slave(false), user_onRequest(NULL), user_onReceive(NULL)
+    is_slave(false), user_onRequest(nullptr), user_onReceive(nullptr)
 #endif /* SOC_I2C_SUPPORT_SLAVE */
 {
 }
@@ -596,14 +596,14 @@ void TwoWire::flush() {
   //i2cFlush(num); // cleanup
 }
 
-void TwoWire::onReceive(void (*function)(int)) {
+void TwoWire::onReceive(const std::function<void(int)> &function) {
 #if SOC_I2C_SUPPORT_SLAVE
   user_onReceive = function;
 #endif
 }
 
 // sets function called on slave read
-void TwoWire::onRequest(void (*function)(void)) {
+void TwoWire::onRequest(const std::function<void()> &function) {
 #if SOC_I2C_SUPPORT_SLAVE
   user_onRequest = function;
 #endif
diff --git a/libraries/Wire/src/Wire.h b/libraries/Wire/src/Wire.h
index b84aa5b2131..9cebdfaa304 100644
--- a/libraries/Wire/src/Wire.h
+++ b/libraries/Wire/src/Wire.h
@@ -48,10 +48,6 @@
 #ifndef I2C_BUFFER_LENGTH
 #define I2C_BUFFER_LENGTH 128  // Default size, if none is set using Wire::setBuffersize(size_t)
 #endif
-#if SOC_I2C_SUPPORT_SLAVE
-typedef void (*user_onRequest)(void);
-typedef void (*user_onReceive)(uint8_t *, int);
-#endif /* SOC_I2C_SUPPORT_SLAVE */
 
 class TwoWire : public HardwareI2C {
 protected:
@@ -77,8 +73,8 @@ class TwoWire : public HardwareI2C {
 private:
 #if SOC_I2C_SUPPORT_SLAVE
   bool is_slave;
-  void (*user_onRequest)(void);
-  void (*user_onReceive)(int);
+  std::function<void()> user_onRequest;
+  std::function<void(int)> user_onReceive;
   static void onRequestService(uint8_t, void *);
   static void onReceiveService(uint8_t, uint8_t *, size_t, bool, void *);
 #endif /* SOC_I2C_SUPPORT_SLAVE */
@@ -116,8 +112,8 @@ class TwoWire : public HardwareI2C {
   size_t requestFrom(uint8_t address, size_t len, bool stopBit) override;
   size_t requestFrom(uint8_t address, size_t len) override;
 
-  void onReceive(void (*)(int)) override;
-  void onRequest(void (*)(void)) override;
+  void onReceive(const std::function<void(int)> &) override;
+  void onRequest(const std::function<void()> &) override;
 
   //call setPins() first, so that begin() can be called without arguments from libraries
   bool setPins(int sda, int scl);

From 1f0d4b5dc0d6008583ac9527907325b9f2506caa Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Mon, 14 Jul 2025 13:17:56 -0300
Subject: [PATCH 043/105] ci(gitlab): Initial GitLab setup (#11577)

* ci(gitlab): Initial GitLab setup

* fix(version): Add to version update script

* ci(pre-commit): Apply automatic fixes

---------

Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 .github/CODEOWNERS                |  1 +
 .github/scripts/update-version.sh |  5 +++++
 .gitlab-ci.yml                    | 25 +++++++++++++++++++++++++
 .gitlab/workflows/common.yml      | 26 ++++++++++++++++++++++++++
 .gitlab/workflows/sample.yml      |  6 ++++++
 5 files changed, 63 insertions(+)
 create mode 100644 .gitlab-ci.yml
 create mode 100644 .gitlab/workflows/common.yml
 create mode 100644 .gitlab/workflows/sample.yml

diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 75a2b46d619..64d241ba20a 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -11,6 +11,7 @@
 
 # CI
 /.github/ @lucasssvaz @me-no-dev @P-R-O-C-H-Y
+/.gitlab/ @lucasssvaz
 /tests/ @lucasssvaz @P-R-O-C-H-Y
 
 # Tools
diff --git a/.github/scripts/update-version.sh b/.github/scripts/update-version.sh
index 622f2fe8ff8..59a95d01105 100755
--- a/.github/scripts/update-version.sh
+++ b/.github/scripts/update-version.sh
@@ -45,6 +45,11 @@ cat docs/conf_common.py | \
 sed "s/.. |version| replace:: .*/.. |version| replace:: $ESP_ARDUINO_VERSION/g" | \
 sed "s/.. |idf_version| replace:: .*/.. |idf_version| replace:: $ESP_IDF_VERSION/g" > docs/__conf_common.py && mv docs/__conf_common.py docs/conf_common.py
 
+echo "Updating .gitlab/workflows/common.yml..."
+cat .gitlab/workflows/common.yml | \
+sed "s/ESP_IDF_VERSION:.*/ESP_IDF_VERSION: \"$ESP_IDF_VERSION\"/g" | \
+sed "s/ESP_ARDUINO_VERSION:.*/ESP_ARDUINO_VERSION: \"$ESP_ARDUINO_VERSION\"/g" > .gitlab/workflows/__common.yml && mv .gitlab/workflows/__common.yml .gitlab/workflows/common.yml
+
 echo "Updating cores/esp32/esp_arduino_version.h..."
 cat cores/esp32/esp_arduino_version.h | \
 sed "s/#define ESP_ARDUINO_VERSION_MAJOR.*/#define ESP_ARDUINO_VERSION_MAJOR $ESP_ARDUINO_VERSION_MAJOR/g" | \
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
new file mode 100644
index 00000000000..89a45022bc2
--- /dev/null
+++ b/.gitlab-ci.yml
@@ -0,0 +1,25 @@
+workflow:
+  rules:
+    # Disable those non-protected push triggered pipelines
+    - if: '$CI_COMMIT_REF_NAME != "master" && $CI_COMMIT_BRANCH !~ /^release\/v/ && $CI_COMMIT_TAG !~ /^\d+\.\d+(\.\d+)?($|-)/ && $CI_PIPELINE_SOURCE == "push"'
+      when: never
+    # when running merged result pipelines, CI_COMMIT_SHA represents the temp commit it created.
+    # Please use PIPELINE_COMMIT_SHA at all places that require a commit sha of the original commit.
+    - if: $CI_OPEN_MERGE_REQUESTS != null
+      variables:
+        PIPELINE_COMMIT_SHA: $CI_MERGE_REQUEST_SOURCE_BRANCH_SHA
+        IS_MR_PIPELINE: 1
+    - if: $CI_OPEN_MERGE_REQUESTS == null
+      variables:
+        PIPELINE_COMMIT_SHA: $CI_COMMIT_SHA
+        IS_MR_PIPELINE: 0
+    - if: '$CI_PIPELINE_SOURCE == "schedule"'
+      variables:
+        IS_SCHEDULED_RUN: "true"
+    - when: always
+
+# Place the default settings in `.gitlab/workflows/common.yml` instead
+
+include:
+  - ".gitlab/workflows/common.yml"
+  - ".gitlab/workflows/sample.yml"
diff --git a/.gitlab/workflows/common.yml b/.gitlab/workflows/common.yml
new file mode 100644
index 00000000000..9086da018ab
--- /dev/null
+++ b/.gitlab/workflows/common.yml
@@ -0,0 +1,26 @@
+#####################
+# Default Variables #
+#####################
+
+stages:
+  - pre_check
+  - build
+  - test
+  - result
+
+variables:
+  ESP_IDF_VERSION: "5.4"
+  ESP_ARDUINO_VERSION: "3.2.1"
+
+#############
+# `default` #
+#############
+
+default:
+  retry:
+    max: 2
+    when:
+      # In case of a runner failure we could hop to another one, or a network error could go away.
+      - runner_system_failure
+      # Job execution timeout may be caused by a network issue.
+      - job_execution_timeout
diff --git a/.gitlab/workflows/sample.yml b/.gitlab/workflows/sample.yml
new file mode 100644
index 00000000000..32b6fce042d
--- /dev/null
+++ b/.gitlab/workflows/sample.yml
@@ -0,0 +1,6 @@
+hello-world:
+  stage: test
+  script:
+    - echo "Hello, World from GitLab CI!"
+  rules:
+    - if: $CI_PIPELINE_SOURCE == "push"

From 82d56bc679dfcd8de2fb06596ff4c4bcca8e6247 Mon Sep 17 00:00:00 2001
From: Sugar Glider <rodrigo.garcia@espressif.com>
Date: Wed, 16 Jul 2025 05:51:31 -0300
Subject: [PATCH 044/105] feat(gpio): new functional interrupt lambda example
 (#11589)

* feat(gpio): new functional interrupt lambda example

* fix(readme): schematic diagram allignment

* fix(example): uses volatile for ISR variables

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix(example): uses volatile for ISR variables

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix(example): uses volatile data type also for the pointers

* fix(readme): clear documentation

* feat(example): improves ISR execution time

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* feat(gpio): simplifies the example and documentation

* feat(gpio): uses IRAM lambda and fixes volatile operation

* fix(doc): fixing documentation apresentation

* ci(pre-commit): Apply automatic fixes

* fix(ci): Update README.md

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
---
 .../FunctionalInterruptLambda.ino             | 157 ++++++++++++++++++
 .../GPIO/FunctionalInterruptLambda/README.md  | 147 ++++++++++++++++
 2 files changed, 304 insertions(+)
 create mode 100644 libraries/ESP32/examples/GPIO/FunctionalInterruptLambda/FunctionalInterruptLambda.ino
 create mode 100644 libraries/ESP32/examples/GPIO/FunctionalInterruptLambda/README.md

diff --git a/libraries/ESP32/examples/GPIO/FunctionalInterruptLambda/FunctionalInterruptLambda.ino b/libraries/ESP32/examples/GPIO/FunctionalInterruptLambda/FunctionalInterruptLambda.ino
new file mode 100644
index 00000000000..57d35383f17
--- /dev/null
+++ b/libraries/ESP32/examples/GPIO/FunctionalInterruptLambda/FunctionalInterruptLambda.ino
@@ -0,0 +1,157 @@
+/*
+   SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD
+
+   SPDX-License-Identifier: Apache-2.0
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+   ESP32 Lambda FunctionalInterrupt Example
+   ========================================
+
+   This example demonstrates how to use lambda functions with FunctionalInterrupt
+   for GPIO pin interrupt callbacks on ESP32. It shows CHANGE mode detection
+   with LED toggle functionality and proper debouncing.
+
+   Hardware Setup:
+   - Use BOOT Button or connect a button between BUTTON_PIN and GND (with internal pullup)
+   - Use Builtin Board LED or connect an LED with resistor to GPIO 2 (LED_PIN)
+
+   Features Demonstrated:
+   1. CHANGE mode lambda to detect both RISING and FALLING edges
+   2. LED toggle on button press (FALLING edge)
+   3. Edge type detection using digitalRead() within ISR
+   4. Hardware debouncing with configurable timeout
+
+   IMPORTANT NOTE ABOUT ESP32 INTERRUPT BEHAVIOR:
+   - Only ONE interrupt handler can be attached per GPIO pin at a time
+   - Calling attachInterrupt() on a pin that already has an interrupt will override the previous one
+   - This applies regardless of edge type (RISING, FALLING, CHANGE)
+   - If you need both RISING and FALLING detection on the same pin, use CHANGE mode
+     and determine the edge type within your handler by reading the pin state
+*/
+
+#include <Arduino.h>
+#include <FunctionalInterrupt.h>
+
+// Pin definitions
+#define BUTTON_PIN BOOT_PIN  // BOOT BUTTON - change as needed
+#ifdef LED_BUILTIN
+#define LED_PIN LED_BUILTIN
+#else
+#warning Using LED_PIN = GPIO 2 as default - change as needed
+#define LED_PIN 2  // change as needed
+#endif
+
+// Global variables for interrupt handling (volatile for ISR safety)
+volatile uint32_t buttonPressCount = 0;
+volatile uint32_t buttonReleaseCount = 0;
+volatile bool buttonPressed = false;
+volatile bool buttonReleased = false;
+volatile bool ledState = false;
+volatile bool ledStateChanged = false;  // Flag to indicate LED needs updating
+
+// Debouncing variables (volatile for ISR safety)
+volatile unsigned long lastButtonInterruptTime = 0;
+const unsigned long DEBOUNCE_DELAY_MS = 50;  // 50ms debounce delay
+
+// State-based debouncing to prevent hysteresis issues
+volatile bool lastButtonState = HIGH;  // Track last stable state (HIGH = released)
+
+// Global lambda function (declared at file scope) - ISR in IRAM
+IRAM_ATTR std::function<void()> changeModeLambda = []() {
+  // Simple debouncing: check if enough time has passed since last interrupt
+  unsigned long currentTime = millis();
+  if (currentTime - lastButtonInterruptTime < DEBOUNCE_DELAY_MS) {
+    return;  // Ignore this interrupt due to bouncing
+  }
+
+  // Read current pin state to determine edge type
+  bool currentState = digitalRead(BUTTON_PIN);
+
+  // State-based debouncing: only process if state actually changed
+  if (currentState == lastButtonState) {
+    return;  // No real state change, ignore (hysteresis/noise)
+  }
+
+  // Update timing and state
+  lastButtonInterruptTime = currentTime;
+  lastButtonState = currentState;
+
+  if (currentState == LOW) {
+    // FALLING edge detected (button pressed) - set flag for main loop
+    // volatile variables require use of temporary value transfer
+    uint32_t temp = buttonPressCount + 1;
+    buttonPressCount = temp;
+    buttonPressed = true;
+    ledStateChanged = true;  // Signal main loop to toggle LED
+  } else {
+    // RISING edge detected (button released) - set flag for main loop
+    // volatile variables require use of temporary value transfer
+    uint32_t temp = buttonReleaseCount + 1;
+    buttonReleaseCount = temp;
+    buttonReleased = true;
+  }
+};
+
+void setup() {
+  Serial.begin(115200);
+  delay(1000);  // Allow serial monitor to connect
+
+  Serial.println("ESP32 Lambda FunctionalInterrupt Example");
+  Serial.println("========================================");
+
+  // Configure pins
+  pinMode(BUTTON_PIN, INPUT_PULLUP);
+  pinMode(LED_PIN, OUTPUT);
+  digitalWrite(LED_PIN, LOW);
+
+  // CHANGE mode lambda to handle both RISING and FALLING edges
+  // This toggles the LED on button press (FALLING edge)
+  Serial.println("Setting up CHANGE mode lambda for LED toggle");
+
+  // Use the global lambda function
+  attachInterrupt(BUTTON_PIN, changeModeLambda, CHANGE);
+
+  Serial.println();
+  Serial.printf("Lambda interrupt configured on Pin %d (CHANGE mode)\r\n", BUTTON_PIN);
+  Serial.printf("Debounce delay: %lu ms\r\n", DEBOUNCE_DELAY_MS);
+  Serial.println();
+  Serial.println("Press the button to toggle the LED!");
+  Serial.println("Button press (FALLING edge) will toggle the LED.");
+  Serial.println("Button release (RISING edge) will be detected and reported.");
+  Serial.println("Button includes debouncing to prevent mechanical bounce issues.");
+  Serial.println();
+}
+
+void loop() {
+  // Handle LED state changes (ISR-safe approach)
+  if (ledStateChanged) {
+    ledStateChanged = false;
+    ledState = !ledState;  // Toggle LED state in main loop
+    digitalWrite(LED_PIN, ledState);
+  }
+
+  // Check for button presses
+  if (buttonPressed) {
+    buttonPressed = false;
+    Serial.printf("==> Button PRESSED! Count: %lu, LED: %s (FALLING edge)\r\n", buttonPressCount, ledState ? "ON" : "OFF");
+  }
+
+  // Check for button releases
+  if (buttonReleased) {
+    buttonReleased = false;
+    Serial.printf("==> Button RELEASED! Count: %lu (RISING edge)\r\n", buttonReleaseCount);
+  }
+
+  delay(10);
+}
diff --git a/libraries/ESP32/examples/GPIO/FunctionalInterruptLambda/README.md b/libraries/ESP32/examples/GPIO/FunctionalInterruptLambda/README.md
new file mode 100644
index 00000000000..9488c317fde
--- /dev/null
+++ b/libraries/ESP32/examples/GPIO/FunctionalInterruptLambda/README.md
@@ -0,0 +1,147 @@
+# ESP32 Lambda FunctionalInterrupt Example
+
+This example demonstrates how to use lambda functions with FunctionalInterrupt for GPIO pin interrupt callbacks on ESP32. It shows CHANGE mode detection with LED toggle functionality and proper debouncing.
+
+## Features Demonstrated
+
+1. **CHANGE mode lambda** to detect both RISING and FALLING edges
+2. **LED toggle on button press** (FALLING edge)
+3. **Edge type detection** using digitalRead() within ISR
+4. **Hardware debouncing** with configurable timeout
+5. **IRAM_ATTR lambda declaration** for optimal ISR performance in RAM
+
+## Hardware Setup
+
+- Use BOOT Button or connect a button between BUTTON_PIN and GND (with internal pullup)
+- Use Builtin Board LED (no special hardware setup) or connect an LED with resistor to GPIO assigned as LED_PIN.\
+  Some boards have an RGB LED that needs no special hardware setup to work as a simple white on/off LED.
+
+```
+ESP32 Board          Button/LED
+-----------          ---------
+BOOT_PIN ------------ [BUTTON] ---- GND
+LED_PIN --------------- [LED] ----- GND
+                          ¦
+                        [330O] (*) Only needed when using an external LED attached to the GPIO.
+                          ¦
+                         3V3
+```
+
+## Important ESP32 Interrupt Behavior
+
+**CRITICAL:** Only ONE interrupt handler can be attached per GPIO pin at a time on ESP32.
+
+- Calling `attachInterrupt()` on a pin that already has an interrupt will **override** the previous one
+- This applies regardless of edge type (RISING, FALLING, CHANGE)
+- If you need both RISING and FALLING detection on the same pin, use **CHANGE mode** and determine the edge type within your handler by reading the pin state
+
+## Code Overview
+
+This example demonstrates a simple CHANGE mode lambda interrupt that:
+
+- **Detects both button press and release** using a single interrupt handler
+- **Toggles LED only on button press** (FALLING edge)
+- **Reports both press and release events** to Serial output
+- **Uses proper debouncing** to prevent switch bounce issues
+- **Implements minimal lambda captures** for simplicity
+
+## Lambda Function Pattern
+
+### CHANGE Mode Lambda with IRAM Declaration
+```cpp
+// Global lambda declared with IRAM_ATTR for optimal ISR performance
+IRAM_ATTR std::function<void()> changeModeLambda = []() {
+    // Debouncing check
+    unsigned long currentTime = millis();
+    if (currentTime - lastButtonInterruptTime < DEBOUNCE_DELAY_MS) {
+        return; // Ignore bouncing
+    }
+
+    // Determine edge type
+    bool currentState = digitalRead(BUTTON_PIN);
+    if (currentState == lastButtonState) {
+        return; // No real state change
+    }
+
+    // Update state and handle edges
+    lastButtonInterruptTime = currentTime;
+    lastButtonState = currentState;
+
+    if (currentState == LOW) {
+        // Button pressed (FALLING edge)
+        buttonPressCount++;
+        buttonPressed = true;
+        ledStateChanged = true;  // Signal LED toggle
+    } else {
+        // Button released (RISING edge)  
+        buttonReleaseCount++;
+        buttonReleased = true;
+    }
+};
+
+attachInterrupt(BUTTON_PIN, changeModeLambda, CHANGE);
+```
+
+## Key Concepts
+
+### Edge Detection in CHANGE Mode
+```cpp
+if (digitalRead(pin) == LOW) {
+  // FALLING edge detected (button pressed)
+} else {
+  // RISING edge detected (button released)
+}
+```
+
+### Debouncing Strategy
+This example implements dual-layer debouncing:
+1. **Time-based**: Ignores interrupts within 50 ms of previous one
+2. **State-based**: Only processes actual state changes
+
+### Main Loop Processing
+```cpp
+void loop() {
+  // Handle LED changes safely outside ISR
+  if (ledStateChanged) {
+    ledStateChanged = false;
+    ledState = !ledState;
+    digitalWrite(LED_PIN, ledState);
+  }
+
+  // Report button events
+  if (buttonPressed) {
+    // Handle press event
+  }
+  if (buttonReleased) {
+    // Handle release event  
+  }
+}
+```
+
+## Expected Output
+
+```
+ESP32 Lambda FunctionalInterrupt Example
+========================================
+Setting up CHANGE mode lambda for LED toggle
+
+Lambda interrupt configured on Pin 0 (CHANGE mode)
+Debounce delay: 50 ms
+
+Press the button to toggle the LED!
+Button press (FALLING edge) will toggle the LED.
+Button release (RISING edge) will be detected and reported.
+Button includes debouncing to prevent mechanical bounce issues.
+
+==> Button PRESSED! Count: 1, LED: ON (FALLING edge)
+==> Button RELEASED! Count: 1 (RISING edge)
+==> Button PRESSED! Count: 2, LED: OFF (FALLING edge)
+==> Button RELEASED! Count: 2 (RISING edge)
+```
+
+## Pin Configuration
+
+The example uses these default pins:
+
+- `BUTTON_PIN`: BOOT_PIN (automatically assigned by the Arduino Core)
+- `LED_PIN`: LED_BUILTIN (may not be available for your board - please verify it)

From ce7ef9c2ba61deff89d86913a966d33c070fb3a4 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Wed, 16 Jul 2025 13:42:07 +0300
Subject: [PATCH 045/105] IDF release/v5.5 cf8dad07 (#11601)

IDF release/v5.5 cf8dad07
---
 package/package_esp32_index.template.json | 68 +++++++++++------------
 1 file changed, 34 insertions(+), 34 deletions(-)

diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index 9c2c754504e..6e2dd0ab337 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-release_v5.5-adb3f2a5-v1"
+              "version": "idf-release_v5.5-cf8dad07-v1"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-release_v5.5-adb3f2a5-v1",
+          "version": "idf-release_v5.5-cf8dad07-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
-              "size": "430508851"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
+              "size": "430423461"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
-              "size": "430508851"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
+              "size": "430423461"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
-              "size": "430508851"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
+              "size": "430423461"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
-              "size": "430508851"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
+              "size": "430423461"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
-              "size": "430508851"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
+              "size": "430423461"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
-              "size": "430508851"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
+              "size": "430423461"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
-              "size": "430508851"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
+              "size": "430423461"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-adb3f2a5-v1.zip",
-              "checksum": "SHA-256:c7bdda06e7ddae51880fc0e1c76114a8e766a9d682e3645e7794f7126b895a94",
-              "size": "430508851"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
+              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
+              "size": "430423461"
             }
           ]
         },

From ac05f18720e83d1e9deee24db7ab13718219b4d6 Mon Sep 17 00:00:00 2001
From: "pre-commit-ci-lite[bot]"
 <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Date: Wed, 16 Jul 2025 12:12:43 +0000
Subject: [PATCH 046/105] ci(pre-commit): Apply automatic fixes

---
 cores/esp32/esp32-hal-cpu.c | 3 ++-
 libraries/SPI/src/SPI.cpp   | 3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/cores/esp32/esp32-hal-cpu.c b/cores/esp32/esp32-hal-cpu.c
index d6bc6b0f191..e9113da4219 100644
--- a/cores/esp32/esp32-hal-cpu.c
+++ b/cores/esp32/esp32-hal-cpu.c
@@ -19,7 +19,8 @@
 #include "esp_attr.h"
 #include "esp_log.h"
 #include "soc/rtc.h"
-#if !defined(CONFIG_IDF_TARGET_ESP32C2) && !defined(CONFIG_IDF_TARGET_ESP32C6) && !defined(CONFIG_IDF_TARGET_ESP32H2) && !defined(CONFIG_IDF_TARGET_ESP32P4) && !defined(CONFIG_IDF_TARGET_ESP32C5)
+#if !defined(CONFIG_IDF_TARGET_ESP32C2) && !defined(CONFIG_IDF_TARGET_ESP32C6) && !defined(CONFIG_IDF_TARGET_ESP32H2) && !defined(CONFIG_IDF_TARGET_ESP32P4) \
+  && !defined(CONFIG_IDF_TARGET_ESP32C5)
 #include "soc/rtc_cntl_reg.h"
 #include "soc/syscon_reg.h"
 #endif
diff --git a/libraries/SPI/src/SPI.cpp b/libraries/SPI/src/SPI.cpp
index 0492065b798..6229f887553 100644
--- a/libraries/SPI/src/SPI.cpp
+++ b/libraries/SPI/src/SPI.cpp
@@ -84,7 +84,8 @@ bool SPIClass::begin(int8_t sck, int8_t miso, int8_t mosi, int8_t ss) {
     _miso = (_spi_num == FSPI) ? MISO : -1;
     _mosi = (_spi_num == FSPI) ? MOSI : -1;
     _ss = (_spi_num == FSPI) ? SS : -1;
-#elif CONFIG_IDF_TARGET_ESP32C2 || CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 || CONFIG_IDF_TARGET_ESP32C5
+#elif CONFIG_IDF_TARGET_ESP32C2 || CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32C6 || CONFIG_IDF_TARGET_ESP32H2 || CONFIG_IDF_TARGET_ESP32P4 \
+  || CONFIG_IDF_TARGET_ESP32C5
     _sck = SCK;
     _miso = MISO;
     _mosi = MOSI;

From 6015fd73e0d9d065c80fc79ef0f35d3273a217de Mon Sep 17 00:00:00 2001
From: Sugar Glider <rodrigo.garcia@espressif.com>
Date: Wed, 16 Jul 2025 13:53:36 -0300
Subject: [PATCH 047/105] feat(openthread): native API extension (#11598)

* feat(openthread): native API extension

* fix(openthread): wrong return type and parameter

* fix(openthread): wrong field reference

* fix(openthread): CR/LF fix

* feat(openthread): print leader RLOC information

* feat(openthread): code improvements

* ci(pre-commit): Apply automatic fixes

---------

Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 .../LeaderNode/LeaderNode.ino                 |  85 +++-
 .../RouterNode/RouterNode.ino                 |  61 ++-
 libraries/OpenThread/keywords.txt             |  18 +
 libraries/OpenThread/src/OThread.cpp          | 363 +++++++++++++++++-
 libraries/OpenThread/src/OThread.h            |  63 ++-
 5 files changed, 565 insertions(+), 25 deletions(-)

diff --git a/libraries/OpenThread/examples/Native/SimpleThreadNetwork/LeaderNode/LeaderNode.ino b/libraries/OpenThread/examples/Native/SimpleThreadNetwork/LeaderNode/LeaderNode.ino
index dfea9776838..b3c4091e1dc 100644
--- a/libraries/OpenThread/examples/Native/SimpleThreadNetwork/LeaderNode/LeaderNode.ino
+++ b/libraries/OpenThread/examples/Native/SimpleThreadNetwork/LeaderNode/LeaderNode.ino
@@ -3,6 +3,9 @@
 OpenThread threadLeaderNode;
 DataSet dataset;
 
+// Track last known device role for state change detection
+ot_device_role_t lastKnownRole = OT_ROLE_DISABLED;
+
 void setup() {
   Serial.begin(115200);
 
@@ -27,8 +30,84 @@ void setup() {
 }
 
 void loop() {
-  // Print network information every 5 seconds
-  Serial.println("==============================================");
-  threadLeaderNode.otPrintNetworkInformation(Serial);
+  // Get current device role
+  ot_device_role_t currentRole = threadLeaderNode.otGetDeviceRole();
+
+  // Only print network information when not detached
+  if (currentRole != OT_ROLE_DETACHED && currentRole != OT_ROLE_DISABLED) {
+    Serial.println("==============================================");
+    Serial.println("OpenThread Network Information:");
+
+    // Basic network information
+    Serial.printf("Role: %s\r\n", threadLeaderNode.otGetStringDeviceRole());
+    Serial.printf("RLOC16: 0x%04x\r\n", threadLeaderNode.getRloc16());
+    Serial.printf("Network Name: %s\r\n", threadLeaderNode.getNetworkName().c_str());
+    Serial.printf("Channel: %d\r\n", threadLeaderNode.getChannel());
+    Serial.printf("PAN ID: 0x%04x\r\n", threadLeaderNode.getPanId());
+
+    // Extended PAN ID
+    const uint8_t *extPanId = threadLeaderNode.getExtendedPanId();
+    if (extPanId) {
+      Serial.print("Extended PAN ID: ");
+      for (int i = 0; i < OT_EXT_PAN_ID_SIZE; i++) {
+        Serial.printf("%02x", extPanId[i]);
+      }
+      Serial.println();
+    }
+
+    // Network Key
+    const uint8_t *networkKey = threadLeaderNode.getNetworkKey();
+    if (networkKey) {
+      Serial.print("Network Key: ");
+      for (int i = 0; i < OT_NETWORK_KEY_SIZE; i++) {
+        Serial.printf("%02x", networkKey[i]);
+      }
+      Serial.println();
+    }
+
+    // Mesh Local EID
+    IPAddress meshLocalEid = threadLeaderNode.getMeshLocalEid();
+    Serial.printf("Mesh Local EID: %s\r\n", meshLocalEid.toString().c_str());
+
+    // Leader RLOC
+    IPAddress leaderRloc = threadLeaderNode.getLeaderRloc();
+    Serial.printf("Leader RLOC: %s\r\n", leaderRloc.toString().c_str());
+
+    // Node RLOC
+    IPAddress nodeRloc = threadLeaderNode.getRloc();
+    Serial.printf("Node RLOC: %s\r\n", nodeRloc.toString().c_str());
+
+    // Demonstrate address listing with two different methods:
+    // Method 1: Unicast addresses using counting API (individual access)
+    Serial.println("\r\n--- Unicast Addresses (Using Count + Index API) ---");
+    size_t unicastCount = threadLeaderNode.getUnicastAddressCount();
+    for (size_t i = 0; i < unicastCount; i++) {
+      IPAddress addr = threadLeaderNode.getUnicastAddress(i);
+      Serial.printf("  [%zu]: %s\r\n", i, addr.toString().c_str());
+    }
+
+    // Method 2: Multicast addresses using std::vector (bulk access)
+    Serial.println("\r\n--- Multicast Addresses (Using std::vector API) ---");
+    std::vector<IPAddress> allMulticast = threadLeaderNode.getAllMulticastAddresses();
+    for (size_t i = 0; i < allMulticast.size(); i++) {
+      Serial.printf("  [%zu]: %s\r\n", i, allMulticast[i].toString().c_str());
+    }
+
+    // Check for role change and clear cache if needed (only when active)
+    if (currentRole != lastKnownRole) {
+      Serial.printf(
+        "Role changed from %s to %s - clearing address cache\r\n", (lastKnownRole < 5) ? otRoleString[lastKnownRole] : "Unknown",
+        threadLeaderNode.otGetStringDeviceRole()
+      );
+      threadLeaderNode.clearAllAddressCache();
+      lastKnownRole = currentRole;
+    }
+  } else {
+    Serial.printf("Thread Node Status: %s - Waiting for thread network start...\r\n", threadLeaderNode.otGetStringDeviceRole());
+
+    // Update role tracking even when detached/disabled, but don't clear cache
+    lastKnownRole = currentRole;
+  }
+
   delay(5000);
 }
diff --git a/libraries/OpenThread/examples/Native/SimpleThreadNetwork/RouterNode/RouterNode.ino b/libraries/OpenThread/examples/Native/SimpleThreadNetwork/RouterNode/RouterNode.ino
index 5ffa535ad51..a8959792f5b 100644
--- a/libraries/OpenThread/examples/Native/SimpleThreadNetwork/RouterNode/RouterNode.ino
+++ b/libraries/OpenThread/examples/Native/SimpleThreadNetwork/RouterNode/RouterNode.ino
@@ -22,8 +22,63 @@ void setup() {
 }
 
 void loop() {
-  // Print network information every 5 seconds
-  Serial.println("==============================================");
-  threadChildNode.otPrintNetworkInformation(Serial);
+  // Get current device role
+  ot_device_role_t currentRole = threadChildNode.otGetDeviceRole();
+
+  // Only print detailed network information when node is active
+  if (currentRole != OT_ROLE_DETACHED && currentRole != OT_ROLE_DISABLED) {
+    Serial.println("==============================================");
+    Serial.println("OpenThread Network Information (Active Dataset):");
+
+    // Get and display the current active dataset
+    const DataSet &activeDataset = threadChildNode.getCurrentDataSet();
+
+    Serial.printf("Role: %s\r\n", threadChildNode.otGetStringDeviceRole());
+    Serial.printf("RLOC16: 0x%04x\r\n", threadChildNode.getRloc16());
+
+    // Dataset information
+    Serial.printf("Network Name: %s\r\n", activeDataset.getNetworkName());
+    Serial.printf("Channel: %d\r\n", activeDataset.getChannel());
+    Serial.printf("PAN ID: 0x%04x\r\n", activeDataset.getPanId());
+
+    // Extended PAN ID from dataset
+    const uint8_t *extPanId = activeDataset.getExtendedPanId();
+    if (extPanId) {
+      Serial.print("Extended PAN ID: ");
+      for (int i = 0; i < OT_EXT_PAN_ID_SIZE; i++) {
+        Serial.printf("%02x", extPanId[i]);
+      }
+      Serial.println();
+    }
+
+    // Network Key from dataset
+    const uint8_t *networkKey = activeDataset.getNetworkKey();
+    if (networkKey) {
+      Serial.print("Network Key: ");
+      for (int i = 0; i < OT_NETWORK_KEY_SIZE; i++) {
+        Serial.printf("%02x", networkKey[i]);
+      }
+      Serial.println();
+    }
+
+    // Additional runtime information
+    IPAddress meshLocalEid = threadChildNode.getMeshLocalEid();
+    Serial.printf("Mesh Local EID: %s\r\n", meshLocalEid.toString().c_str());
+
+    IPAddress nodeRloc = threadChildNode.getRloc();
+    Serial.printf("Node RLOC: %s\r\n", nodeRloc.toString().c_str());
+
+    IPAddress leaderRloc = threadChildNode.getLeaderRloc();
+    Serial.printf("Leader RLOC: %s\r\n", leaderRloc.toString().c_str());
+
+    Serial.println();
+
+  } else {
+    Serial.println("==============================================");
+    Serial.printf("Thread Node Status: %s - Waiting for thread network start...\r\n", threadChildNode.otGetStringDeviceRole());
+
+    Serial.println();
+  }
+
   delay(5000);
 }
diff --git a/libraries/OpenThread/keywords.txt b/libraries/OpenThread/keywords.txt
index b62c2c23ddc..99821ce401c 100644
--- a/libraries/OpenThread/keywords.txt
+++ b/libraries/OpenThread/keywords.txt
@@ -13,6 +13,7 @@ OpenThread	KEYWORD1
 DataSet	KEYWORD1
 ot_cmd_return_t	KEYWORD1
 ot_device_role_t	KEYWORD1
+OnReceiveCb_t	KEYWORD1
 
 #######################################
 # Methods and Functions (KEYWORD2)
@@ -59,6 +60,23 @@ stop	KEYWORD2
 networkInterfaceUp	KEYWORD2
 networkInterfaceDown	KEYWORD2
 commitDataSet	KEYWORD2
+getInstance	KEYWORD2
+getCurrentDataSet	KEYWORD2
+getMeshLocalPrefix	KEYWORD2
+getMeshLocalEid	KEYWORD2
+getLeaderRloc	KEYWORD2
+getRloc	KEYWORD2
+getRloc16	KEYWORD2
+getUnicastAddressCount	KEYWORD2
+getUnicastAddress	KEYWORD2
+getAllUnicastAddresses	KEYWORD2
+getMulticastAddressCount	KEYWORD2
+getMulticastAddress	KEYWORD2
+getAllMulticastAddresses	KEYWORD2
+clearUnicastAddressCache	KEYWORD2
+clearMulticastAddressCache	KEYWORD2
+clearAllAddressCache	KEYWORD2
+end	KEYWORD2
 
 #######################################
 # Constants (LITERAL1)
diff --git a/libraries/OpenThread/src/OThread.cpp b/libraries/OpenThread/src/OThread.cpp
index 7714d870cce..87b748d104d 100644
--- a/libraries/OpenThread/src/OThread.cpp
+++ b/libraries/OpenThread/src/OThread.cpp
@@ -2,6 +2,8 @@
 #if SOC_IEEE802154_SUPPORTED
 #if CONFIG_OPENTHREAD_ENABLED
 
+#include "IPAddress.h"
+#include <vector>
 #include "esp_err.h"
 #include "esp_event.h"
 #include "esp_netif.h"
@@ -132,16 +134,29 @@ const otOperationalDataset &DataSet::getDataset() const {
 }
 
 void DataSet::setNetworkName(const char *name) {
-  strncpy(mDataset.mNetworkName.m8, name, sizeof(mDataset.mNetworkName.m8));
+  if (!name) {
+    log_w("Network name is null");
+    return;
+  }
+  // char m8[OT_NETWORK_KEY_SIZE + 1] bytes space by definition
+  strncpy(mDataset.mNetworkName.m8, name, OT_NETWORK_KEY_SIZE);
   mDataset.mComponents.mIsNetworkNamePresent = true;
 }
 
 void DataSet::setExtendedPanId(const uint8_t *extPanId) {
+  if (!extPanId) {
+    log_w("Extended PAN ID is null");
+    return;
+  }
   memcpy(mDataset.mExtendedPanId.m8, extPanId, OT_EXT_PAN_ID_SIZE);
   mDataset.mComponents.mIsExtendedPanIdPresent = true;
 }
 
 void DataSet::setNetworkKey(const uint8_t *key) {
+  if (!key) {
+    log_w("Network key is null");
+    return;
+  }
   memcpy(mDataset.mNetworkKey.m8, key, OT_NETWORK_KEY_SIZE);
   mDataset.mComponents.mIsNetworkKeyPresent = true;
 }
@@ -181,10 +196,18 @@ void DataSet::apply(otInstance *instance) {
 }
 
 // OpenThread Implementation
-bool OpenThread::otStarted = false;
+bool OpenThread::otStarted;
+otInstance *OpenThread::mInstance;
+DataSet OpenThread::mCurrentDataset;
+otNetworkKey OpenThread::mNetworkKey;
 
-otInstance *OpenThread::mInstance = nullptr;
-OpenThread::OpenThread() {}
+OpenThread::OpenThread() {
+  // static initialization (node data and stack starting information)
+  otStarted = false;
+  mCurrentDataset.clear();                       // Initialize the current dataset
+  memset(&mNetworkKey, 0, sizeof(mNetworkKey));  // Initialize the network key
+  mInstance = nullptr;
+}
 
 OpenThread::~OpenThread() {
   end();
@@ -214,13 +237,7 @@ void OpenThread::begin(bool OThreadAutoStart) {
     return;
   }
   log_d("OpenThread task created successfully");
-  // get the OpenThread instance that will be used for all operations
-  mInstance = esp_openthread_get_instance();
-  if (!mInstance) {
-    log_e("Error: Failed to initialize OpenThread instance");
-    end();
-    return;
-  }
+
   // starts Thread with default dataset from NVS or from IDF default settings
   if (OThreadAutoStart) {
     otOperationalDatasetTlvs dataset;
@@ -238,23 +255,46 @@ void OpenThread::begin(bool OThreadAutoStart) {
       log_i("AUTO start OpenThread done");
     }
   }
+
+  // get the OpenThread instance that will be used for all operations
+  mInstance = esp_openthread_get_instance();
+  if (!mInstance) {
+    log_e("Error: Failed to initialize OpenThread instance");
+    end();
+    return;
+  }
+
   otStarted = true;
 }
 
 void OpenThread::end() {
+  if (!otStarted) {
+    log_w("OpenThread already stopped");
+    return;
+  }
+
   if (s_ot_task != NULL) {
     vTaskDelete(s_ot_task);
     s_ot_task = NULL;
-    // Clean up
-    esp_openthread_deinit();
-    esp_openthread_netif_glue_deinit();
-#if CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM
-    ot_lwip_netif = NULL;
-#endif
+  }
+
+  // Clean up in reverse order of initialization
+  if (openthread_netif != NULL) {
     esp_netif_destroy(openthread_netif);
-    esp_vfs_eventfd_unregister();
+    openthread_netif = NULL;
   }
+
+  esp_openthread_netif_glue_deinit();
+  esp_openthread_deinit();
+  esp_vfs_eventfd_unregister();
+
+#if CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM
+  ot_lwip_netif = NULL;
+#endif
+
+  mInstance = nullptr;
   otStarted = false;
+  log_d("OpenThread ended successfully");
 }
 
 void OpenThread::start() {
@@ -262,6 +302,7 @@ void OpenThread::start() {
     log_w("Error: OpenThread instance not initialized");
     return;
   }
+  clearAllAddressCache();  // Clear cache when starting network
   otThreadSetEnabled(mInstance, true);
   log_d("Thread network started");
 }
@@ -271,6 +312,7 @@ void OpenThread::stop() {
     log_w("Error: OpenThread instance not initialized");
     return;
   }
+  clearAllAddressCache();  // Clear cache when stopping network
   otThreadSetEnabled(mInstance, false);
   log_d("Thread network stopped");
 }
@@ -285,6 +327,7 @@ void OpenThread::networkInterfaceUp() {
   if (error != OT_ERROR_NONE) {
     log_e("Error: Failed to enable Thread interface (error code: %d)\n", error);
   }
+  clearAllAddressCache();  // Clear cache when interface comes up
   log_d("OpenThread Network Interface is up");
 }
 
@@ -312,6 +355,7 @@ void OpenThread::commitDataSet(const DataSet &dataset) {
     log_e("Error: Failed to commit dataset (error code: %d)\n", error);
     return;
   }
+  clearAllAddressCache();  // Clear cache when dataset changes
   log_d("Dataset committed successfully");
 }
 
@@ -360,6 +404,289 @@ void OpenThread::otPrintNetworkInformation(Stream &output) {
   output.println();
 }
 
+// Get the Node Network Name
+String OpenThread::getNetworkName() const {
+  if (!mInstance) {
+    log_w("Error: OpenThread instance not initialized");
+    return String();  // Return empty String, not nullptr
+  }
+  const char *networkName = otThreadGetNetworkName(mInstance);
+  return networkName ? String(networkName) : String();
+}
+
+// Get the Node Extended PAN ID
+const uint8_t *OpenThread::getExtendedPanId() const {
+  if (!mInstance) {
+    log_w("Error: OpenThread instance not initialized");
+    return nullptr;
+  }
+  const otExtendedPanId *extPanId = otThreadGetExtendedPanId(mInstance);
+  return extPanId ? extPanId->m8 : nullptr;
+}
+
+// Get the Node Network Key
+const uint8_t *OpenThread::getNetworkKey() const {
+  if (!mInstance) {
+    log_w("Error: OpenThread instance not initialized");
+    return nullptr;
+  }
+  otThreadGetNetworkKey(mInstance, &mNetworkKey);
+  return mNetworkKey.m8;
+}
+
+// Get the Node Channel
+uint8_t OpenThread::getChannel() const {
+  if (!mInstance) {
+    log_w("Error: OpenThread instance not initialized");
+    return 0;
+  }
+  return otLinkGetChannel(mInstance);
+}
+
+// Get the Node PAN ID
+uint16_t OpenThread::getPanId() const {
+  if (!mInstance) {
+    log_w("Error: OpenThread instance not initialized");
+    return 0;
+  }
+  return otLinkGetPanId(mInstance);
+}
+
+// Get the OpenThread instance
+otInstance *OpenThread::getInstance() {
+  if (!mInstance) {
+    log_w("Error: OpenThread instance not initialized");
+    return nullptr;
+  }
+  return mInstance;
+}
+
+// Get the current dataset
+const DataSet &OpenThread::getCurrentDataSet() const {
+
+  if (!mInstance) {
+    log_w("Error: OpenThread instance not initialized");
+    mCurrentDataset.clear();
+    return mCurrentDataset;
+  }
+
+  otOperationalDataset dataset;
+  otError error = otDatasetGetActive(mInstance, &dataset);
+
+  if (error == OT_ERROR_NONE) {
+    mCurrentDataset.clear();
+
+    if (dataset.mComponents.mIsNetworkNamePresent) {
+      mCurrentDataset.setNetworkName(dataset.mNetworkName.m8);
+    }
+    if (dataset.mComponents.mIsExtendedPanIdPresent) {
+      mCurrentDataset.setExtendedPanId(dataset.mExtendedPanId.m8);
+    }
+    if (dataset.mComponents.mIsNetworkKeyPresent) {
+      mCurrentDataset.setNetworkKey(dataset.mNetworkKey.m8);
+    }
+    if (dataset.mComponents.mIsChannelPresent) {
+      mCurrentDataset.setChannel(dataset.mChannel);
+    }
+    if (dataset.mComponents.mIsPanIdPresent) {
+      mCurrentDataset.setPanId(dataset.mPanId);
+    }
+  } else {
+    log_w("Failed to get active dataset (error: %d)", error);
+    mCurrentDataset.clear();
+  }
+
+  return mCurrentDataset;
+}
+
+// Get the Mesh Local Prefix
+const otMeshLocalPrefix *OpenThread::getMeshLocalPrefix() const {
+  if (!mInstance) {
+    log_w("Error: OpenThread instance not initialized");
+    return nullptr;
+  }
+  return otThreadGetMeshLocalPrefix(mInstance);
+}
+
+// Get the Mesh-Local EID
+IPAddress OpenThread::getMeshLocalEid() const {
+  if (!mInstance) {
+    log_w("Error: OpenThread instance not initialized");
+    return IPAddress(IPv6);  // Return empty IPv6 address
+  }
+  const otIp6Address *otAddr = otThreadGetMeshLocalEid(mInstance);
+  if (!otAddr) {
+    log_w("Failed to get Mesh Local EID");
+    return IPAddress(IPv6);
+  }
+  return IPAddress(IPv6, otAddr->mFields.m8);
+}
+
+// Get the Thread Leader RLOC
+IPAddress OpenThread::getLeaderRloc() const {
+  if (!mInstance) {
+    log_w("Error: OpenThread instance not initialized");
+    return IPAddress(IPv6);  // Return empty IPv6 address
+  }
+  otIp6Address otAddr;
+  otError error = otThreadGetLeaderRloc(mInstance, &otAddr);
+  if (error != OT_ERROR_NONE) {
+    log_w("Failed to get Leader RLOC");
+    return IPAddress(IPv6);
+  }
+  return IPAddress(IPv6, otAddr.mFields.m8);
+}
+
+// Get the Node RLOC
+IPAddress OpenThread::getRloc() const {
+  if (!mInstance) {
+    log_w("Error: OpenThread instance not initialized");
+    return IPAddress(IPv6);  // Return empty IPv6 address
+  }
+  const otIp6Address *otAddr = otThreadGetRloc(mInstance);
+  if (!otAddr) {
+    log_w("Failed to get Node RLOC");
+    return IPAddress(IPv6);
+  }
+  return IPAddress(IPv6, otAddr->mFields.m8);
+}
+
+// Get the RLOC16 ID
+uint16_t OpenThread::getRloc16() const {
+  if (!mInstance) {
+    log_w("Error: OpenThread instance not initialized");
+    return 0;
+  }
+  return otThreadGetRloc16(mInstance);
+}
+
+// Populate unicast address cache from OpenThread
+void OpenThread::populateUnicastAddressCache() const {
+  if (!mInstance) {
+    return;
+  }
+
+  // Clear existing cache
+  mCachedUnicastAddresses.clear();
+
+  // Populate unicast addresses cache
+  const otNetifAddress *addr = otIp6GetUnicastAddresses(mInstance);
+  while (addr != nullptr) {
+    mCachedUnicastAddresses.push_back(IPAddress(IPv6, addr->mAddress.mFields.m8));
+    addr = addr->mNext;
+  }
+
+  log_d("Populated unicast address cache with %zu addresses", mCachedUnicastAddresses.size());
+}
+
+// Populate multicast address cache from OpenThread
+void OpenThread::populateMulticastAddressCache() const {
+  if (!mInstance) {
+    return;
+  }
+
+  // Clear existing cache
+  mCachedMulticastAddresses.clear();
+
+  // Populate multicast addresses cache
+  const otNetifMulticastAddress *mAddr = otIp6GetMulticastAddresses(mInstance);
+  while (mAddr != nullptr) {
+    mCachedMulticastAddresses.push_back(IPAddress(IPv6, mAddr->mAddress.mFields.m8));
+    mAddr = mAddr->mNext;
+  }
+
+  log_d("Populated multicast address cache with %zu addresses", mCachedMulticastAddresses.size());
+}
+
+// Clear unicast address cache
+void OpenThread::clearUnicastAddressCache() const {
+  mCachedUnicastAddresses.clear();
+  log_d("Cleared unicast address cache");
+}
+
+// Clear multicast address cache
+void OpenThread::clearMulticastAddressCache() const {
+  mCachedMulticastAddresses.clear();
+  log_d("Cleared multicast address cache");
+}
+
+// Clear all address caches
+void OpenThread::clearAllAddressCache() const {
+  mCachedUnicastAddresses.clear();
+  mCachedMulticastAddresses.clear();
+  log_d("Cleared all address caches");
+}
+
+// Get count of unicast addresses
+size_t OpenThread::getUnicastAddressCount() const {
+  // Populate cache if empty
+  if (mCachedUnicastAddresses.empty()) {
+    populateUnicastAddressCache();
+  }
+
+  return mCachedUnicastAddresses.size();
+}
+
+// Get unicast address by index
+IPAddress OpenThread::getUnicastAddress(size_t index) const {
+  // Populate cache if empty
+  if (mCachedUnicastAddresses.empty()) {
+    populateUnicastAddressCache();
+  }
+
+  if (index >= mCachedUnicastAddresses.size()) {
+    log_w("Unicast address index %zu out of range (max: %zu)", index, mCachedUnicastAddresses.size());
+    return IPAddress(IPv6);
+  }
+
+  return mCachedUnicastAddresses[index];
+}
+
+// Get all unicast addresses
+std::vector<IPAddress> OpenThread::getAllUnicastAddresses() const {
+  // Populate cache if empty
+  if (mCachedUnicastAddresses.empty()) {
+    populateUnicastAddressCache();
+  }
+
+  return mCachedUnicastAddresses;  // Return copy of cached vector
+}
+
+// Get count of multicast addresses
+size_t OpenThread::getMulticastAddressCount() const {
+  // Populate cache if empty
+  if (mCachedMulticastAddresses.empty()) {
+    populateMulticastAddressCache();
+  }
+
+  return mCachedMulticastAddresses.size();
+}
+
+// Get multicast address by index
+IPAddress OpenThread::getMulticastAddress(size_t index) const {
+  // Populate cache if empty
+  if (mCachedMulticastAddresses.empty()) {
+    populateMulticastAddressCache();
+  }
+
+  if (index >= mCachedMulticastAddresses.size()) {
+    log_w("Multicast address index %zu out of range (max: %zu)", index, mCachedMulticastAddresses.size());
+    return IPAddress(IPv6);
+  }
+
+  return mCachedMulticastAddresses[index];
+}
+
+// Get all multicast addresses
+std::vector<IPAddress> OpenThread::getAllMulticastAddresses() const {
+  // Populate cache if empty
+  if (mCachedMulticastAddresses.empty()) {
+    populateMulticastAddressCache();
+  }
+
+  return mCachedMulticastAddresses;  // Return copy of cached vector
+}
+
 OpenThread OThread;
 
 #endif /* CONFIG_OPENTHREAD_ENABLED */
diff --git a/libraries/OpenThread/src/OThread.h b/libraries/OpenThread/src/OThread.h
index 359d581bb9d..6e21b854574 100644
--- a/libraries/OpenThread/src/OThread.h
+++ b/libraries/OpenThread/src/OThread.h
@@ -25,6 +25,8 @@
 #include <openthread/dataset_ftd.h>
 #include <esp_openthread.h>
 #include <Arduino.h>
+#include "IPAddress.h"
+#include <vector>
 
 typedef enum {
   OT_ROLE_DISABLED = 0,  ///< The Thread stack is disabled.
@@ -96,9 +98,68 @@ class OpenThread {
   // Set the dataset
   void commitDataSet(const DataSet &dataset);
 
+  // Get the Node Network Name
+  String getNetworkName() const;
+
+  // Get the Node Extended PAN ID
+  const uint8_t *getExtendedPanId() const;
+
+  // Get the Node Network Key
+  const uint8_t *getNetworkKey() const;
+
+  // Get the Node Channel
+  uint8_t getChannel() const;
+
+  // Get the Node PAN ID
+  uint16_t getPanId() const;
+
+  // Get the OpenThread instance
+  otInstance *getInstance();
+
+  // Get the current dataset
+  const DataSet &getCurrentDataSet() const;
+
+  // Get the Mesh Local Prefix
+  const otMeshLocalPrefix *getMeshLocalPrefix() const;
+
+  // Get the Mesh-Local EID
+  IPAddress getMeshLocalEid() const;
+
+  // Get the Thread Leader RLOC
+  IPAddress getLeaderRloc() const;
+
+  // Get the Node RLOC
+  IPAddress getRloc() const;
+
+  // Get the RLOC16 ID
+  uint16_t getRloc16() const;
+
+  // Address management with caching
+  size_t getUnicastAddressCount() const;
+  IPAddress getUnicastAddress(size_t index) const;
+  std::vector<IPAddress> getAllUnicastAddresses() const;
+
+  size_t getMulticastAddressCount() const;
+  IPAddress getMulticastAddress(size_t index) const;
+  std::vector<IPAddress> getAllMulticastAddresses() const;
+
+  // Cache management
+  void clearUnicastAddressCache() const;
+  void clearMulticastAddressCache() const;
+  void clearAllAddressCache() const;
+
 private:
   static otInstance *mInstance;
-  DataSet mCurrentDataSet;
+  static DataSet mCurrentDataset;   // Current dataset being used by the OpenThread instance.
+  static otNetworkKey mNetworkKey;  // Static storage to persist after function return
+
+  // Address caching for performance (user-controlled)
+  mutable std::vector<IPAddress> mCachedUnicastAddresses;
+  mutable std::vector<IPAddress> mCachedMulticastAddresses;
+
+  // Internal cache management
+  void populateUnicastAddressCache() const;
+  void populateMulticastAddressCache() const;
 };
 
 extern OpenThread OThread;

From a69c71f6ad771790ed4716fba063930f804806f6 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Wed, 16 Jul 2025 19:55:53 +0300
Subject: [PATCH 048/105] feat(core): Update core version to 3.3.0

---
 .gitlab/workflows/common.yml                     | 4 ++--
 cores/esp32/esp_arduino_version.h                | 4 ++--
 docs/conf_common.py                              | 4 ++--
 libraries/ArduinoOTA/library.properties          | 2 +-
 libraries/AsyncUDP/library.properties            | 2 +-
 libraries/BLE/library.properties                 | 2 +-
 libraries/BluetoothSerial/library.properties     | 2 +-
 libraries/DNSServer/library.properties           | 2 +-
 libraries/EEPROM/library.properties              | 2 +-
 libraries/ESP32/library.properties               | 2 +-
 libraries/ESP_I2S/library.properties             | 2 +-
 libraries/ESP_NOW/library.properties             | 2 +-
 libraries/ESP_SR/library.properties              | 2 +-
 libraries/ESPmDNS/library.properties             | 2 +-
 libraries/Ethernet/library.properties            | 2 +-
 libraries/FFat/library.properties                | 2 +-
 libraries/FS/library.properties                  | 2 +-
 libraries/HTTPClient/library.properties          | 2 +-
 libraries/HTTPUpdate/library.properties          | 2 +-
 libraries/HTTPUpdateServer/library.properties    | 2 +-
 libraries/Insights/library.properties            | 2 +-
 libraries/LittleFS/library.properties            | 2 +-
 libraries/Matter/library.properties              | 2 +-
 libraries/NetBIOS/library.properties             | 2 +-
 libraries/Network/library.properties             | 2 +-
 libraries/NetworkClientSecure/library.properties | 2 +-
 libraries/OpenThread/library.properties          | 2 +-
 libraries/PPP/library.properties                 | 2 +-
 libraries/Preferences/library.properties         | 2 +-
 libraries/RainMaker/library.properties           | 2 +-
 libraries/SD/library.properties                  | 2 +-
 libraries/SD_MMC/library.properties              | 2 +-
 libraries/SPI/library.properties                 | 2 +-
 libraries/SPIFFS/library.properties              | 2 +-
 libraries/SimpleBLE/library.properties           | 2 +-
 libraries/TFLiteMicro/library.properties         | 2 +-
 libraries/Ticker/library.properties              | 2 +-
 libraries/USB/library.properties                 | 2 +-
 libraries/Update/library.properties              | 2 +-
 libraries/WebServer/library.properties           | 2 +-
 libraries/WiFi/library.properties                | 2 +-
 libraries/WiFiProv/library.properties            | 2 +-
 libraries/Wire/library.properties                | 2 +-
 libraries/Zigbee/library.properties              | 2 +-
 package.json                                     | 2 +-
 platform.txt                                     | 2 +-
 46 files changed, 49 insertions(+), 49 deletions(-)

diff --git a/.gitlab/workflows/common.yml b/.gitlab/workflows/common.yml
index 9086da018ab..611e1d974f4 100644
--- a/.gitlab/workflows/common.yml
+++ b/.gitlab/workflows/common.yml
@@ -9,8 +9,8 @@ stages:
   - result
 
 variables:
-  ESP_IDF_VERSION: "5.4"
-  ESP_ARDUINO_VERSION: "3.2.1"
+  ESP_IDF_VERSION: "5.5"
+  ESP_ARDUINO_VERSION: "3.3.0"
 
 #############
 # `default` #
diff --git a/cores/esp32/esp_arduino_version.h b/cores/esp32/esp_arduino_version.h
index 97bb3ac794b..120377c61f7 100644
--- a/cores/esp32/esp_arduino_version.h
+++ b/cores/esp32/esp_arduino_version.h
@@ -21,9 +21,9 @@ extern "C" {
 /** Major version number (X.x.x) */
 #define ESP_ARDUINO_VERSION_MAJOR 3
 /** Minor version number (x.X.x) */
-#define ESP_ARDUINO_VERSION_MINOR 2
+#define ESP_ARDUINO_VERSION_MINOR 3
 /** Patch version number (x.x.X) */
-#define ESP_ARDUINO_VERSION_PATCH 1
+#define ESP_ARDUINO_VERSION_PATCH 0
 
 /**
  * Macro to convert ARDUINO version number into an integer
diff --git a/docs/conf_common.py b/docs/conf_common.py
index af1d615f753..10d4bd715b2 100644
--- a/docs/conf_common.py
+++ b/docs/conf_common.py
@@ -4,8 +4,8 @@
 
 # Used for substituting variables in the documentation
 rst_prolog = """
-.. |version| replace:: 3.2.1
-.. |idf_version| replace:: 5.4
+.. |version| replace:: 3.3.0
+.. |idf_version| replace:: 5.5
 """
 
 languages = ["en"]
diff --git a/libraries/ArduinoOTA/library.properties b/libraries/ArduinoOTA/library.properties
index 18de5aa2180..3a3f7e111e0 100644
--- a/libraries/ArduinoOTA/library.properties
+++ b/libraries/ArduinoOTA/library.properties
@@ -1,5 +1,5 @@
 name=ArduinoOTA
-version=3.2.1
+version=3.3.0
 author=Ivan Grokhotkov and Hristo Gochkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=Enables Over The Air upgrades, via wifi and espota.py UDP request/TCP download.
diff --git a/libraries/AsyncUDP/library.properties b/libraries/AsyncUDP/library.properties
index c64c60d0421..ddf9f79b6d9 100644
--- a/libraries/AsyncUDP/library.properties
+++ b/libraries/AsyncUDP/library.properties
@@ -1,5 +1,5 @@
 name=ESP32 Async UDP
-version=3.2.1
+version=3.3.0
 author=Me-No-Dev
 maintainer=Me-No-Dev
 sentence=Async UDP Library for ESP32
diff --git a/libraries/BLE/library.properties b/libraries/BLE/library.properties
index 335ab2fc965..c6fae19a4a1 100644
--- a/libraries/BLE/library.properties
+++ b/libraries/BLE/library.properties
@@ -1,5 +1,5 @@
 name=BLE
-version=3.2.1
+version=3.3.0
 author=Neil Kolban <kolban1@kolban.com>
 maintainer=lucasssvaz
 sentence=BLE functions for ESP32
diff --git a/libraries/BluetoothSerial/library.properties b/libraries/BluetoothSerial/library.properties
index 4bc1427e3f8..49211bf3b63 100644
--- a/libraries/BluetoothSerial/library.properties
+++ b/libraries/BluetoothSerial/library.properties
@@ -1,5 +1,5 @@
 name=BluetoothSerial
-version=3.2.1
+version=3.3.0
 author=Evandro Copercini
 maintainer=Evandro Copercini
 sentence=Simple UART to Classical Bluetooth bridge for ESP32
diff --git a/libraries/DNSServer/library.properties b/libraries/DNSServer/library.properties
index 42e4c38dc9d..c193b919d02 100644
--- a/libraries/DNSServer/library.properties
+++ b/libraries/DNSServer/library.properties
@@ -1,5 +1,5 @@
 name=DNSServer
-version=3.2.1
+version=3.3.0
 author=Kristijan Novoselić
 maintainer=Kristijan Novoselić, <kristijan.novoselic@gmail.com>
 sentence=A simple DNS server for ESP32.
diff --git a/libraries/EEPROM/library.properties b/libraries/EEPROM/library.properties
index ee1caae0792..6d69f52a085 100644
--- a/libraries/EEPROM/library.properties
+++ b/libraries/EEPROM/library.properties
@@ -1,5 +1,5 @@
 name=EEPROM
-version=3.2.1
+version=3.3.0
 author=Ivan Grokhotkov
 maintainer=Paolo Becchi <pbecchi@aerobusiness.it>
 sentence=Enables reading and writing data a sequential, addressable FLASH storage
diff --git a/libraries/ESP32/library.properties b/libraries/ESP32/library.properties
index 0815a69ce6b..e664022388d 100644
--- a/libraries/ESP32/library.properties
+++ b/libraries/ESP32/library.properties
@@ -1,5 +1,5 @@
 name=ESP32
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov, Ivan Grokhtkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=ESP32 sketches examples
diff --git a/libraries/ESP_I2S/library.properties b/libraries/ESP_I2S/library.properties
index ff1ad5d59da..b2763f4e7e8 100644
--- a/libraries/ESP_I2S/library.properties
+++ b/libraries/ESP_I2S/library.properties
@@ -1,5 +1,5 @@
 name=ESP_I2S
-version=3.2.1
+version=3.3.0
 author=me-no-dev
 maintainer=me-no-dev
 sentence=Library for ESP I2S communication
diff --git a/libraries/ESP_NOW/library.properties b/libraries/ESP_NOW/library.properties
index 426a9464ace..f8e627dbc03 100644
--- a/libraries/ESP_NOW/library.properties
+++ b/libraries/ESP_NOW/library.properties
@@ -1,5 +1,5 @@
 name=ESP_NOW
-version=3.2.1
+version=3.3.0
 author=me-no-dev
 maintainer=P-R-O-C-H-Y
 sentence=Library for ESP_NOW
diff --git a/libraries/ESP_SR/library.properties b/libraries/ESP_SR/library.properties
index 3b9777bca8f..9d9787b7931 100644
--- a/libraries/ESP_SR/library.properties
+++ b/libraries/ESP_SR/library.properties
@@ -1,5 +1,5 @@
 name=ESP_SR
-version=3.2.1
+version=3.3.0
 author=me-no-dev
 maintainer=me-no-dev
 sentence=Library for ESP Sound Recognition
diff --git a/libraries/ESPmDNS/library.properties b/libraries/ESPmDNS/library.properties
index b99a5f58e5c..062d3b90b51 100644
--- a/libraries/ESPmDNS/library.properties
+++ b/libraries/ESPmDNS/library.properties
@@ -1,5 +1,5 @@
 name=ESPmDNS
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov, Ivan Grokhtkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=ESP32 mDNS Library
diff --git a/libraries/Ethernet/library.properties b/libraries/Ethernet/library.properties
index cd2d8ead018..28f2a8697d9 100644
--- a/libraries/Ethernet/library.properties
+++ b/libraries/Ethernet/library.properties
@@ -1,5 +1,5 @@
 name=Ethernet
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=Enables network connection (local and Internet) using the ESP32 Ethernet.
diff --git a/libraries/FFat/library.properties b/libraries/FFat/library.properties
index 898982536b0..25b8c4e8acd 100644
--- a/libraries/FFat/library.properties
+++ b/libraries/FFat/library.properties
@@ -1,5 +1,5 @@
 name=FFat
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov, Ivan Grokhtkov, Larry Bernstone
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=ESP32 FAT on Flash File System
diff --git a/libraries/FS/library.properties b/libraries/FS/library.properties
index fe86d613bdf..0f05f1134d5 100644
--- a/libraries/FS/library.properties
+++ b/libraries/FS/library.properties
@@ -1,5 +1,5 @@
 name=FS
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov, Ivan Grokhtkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=ESP32 File System
diff --git a/libraries/HTTPClient/library.properties b/libraries/HTTPClient/library.properties
index 76da4c857e1..bb5b0936255 100644
--- a/libraries/HTTPClient/library.properties
+++ b/libraries/HTTPClient/library.properties
@@ -1,5 +1,5 @@
 name=HTTPClient
-version=3.2.1
+version=3.3.0
 author=Markus Sattler
 maintainer=Markus Sattler
 sentence=HTTP Client for ESP32
diff --git a/libraries/HTTPUpdate/library.properties b/libraries/HTTPUpdate/library.properties
index dfe0474c3f3..88466a3a72e 100644
--- a/libraries/HTTPUpdate/library.properties
+++ b/libraries/HTTPUpdate/library.properties
@@ -1,5 +1,5 @@
 name=HTTPUpdate
-version=3.2.1
+version=3.3.0
 author=Markus Sattler
 maintainer=Markus Sattler
 sentence=Http Update for ESP32
diff --git a/libraries/HTTPUpdateServer/library.properties b/libraries/HTTPUpdateServer/library.properties
index 90aa966d27f..c182eeb8d7f 100644
--- a/libraries/HTTPUpdateServer/library.properties
+++ b/libraries/HTTPUpdateServer/library.properties
@@ -1,5 +1,5 @@
 name=HTTPUpdateServer
-version=3.2.1
+version=3.3.0
 author=Hristo Kapanakov
 maintainer=
 sentence=Simple HTTP Update server based on the WebServer
diff --git a/libraries/Insights/library.properties b/libraries/Insights/library.properties
index c1ad9c72ce1..3ef98d25be6 100644
--- a/libraries/Insights/library.properties
+++ b/libraries/Insights/library.properties
@@ -1,5 +1,5 @@
 name=ESP Insights
-version=3.2.1
+version=3.3.0
 author=Sanket Wadekar <sanket.wadekar@espressif.com>
 maintainer=Sanket Wadekar <sanket.wadekar@espressif.com>
 sentence=ESP Insights
diff --git a/libraries/LittleFS/library.properties b/libraries/LittleFS/library.properties
index e00ed49c312..202d8ad4a6d 100644
--- a/libraries/LittleFS/library.properties
+++ b/libraries/LittleFS/library.properties
@@ -1,5 +1,5 @@
 name=LittleFS
-version=3.2.1
+version=3.3.0
 author=
 maintainer=
 sentence=LittleFS for esp32
diff --git a/libraries/Matter/library.properties b/libraries/Matter/library.properties
index b601fce0ff5..0b140bfa169 100644
--- a/libraries/Matter/library.properties
+++ b/libraries/Matter/library.properties
@@ -1,5 +1,5 @@
 name=Matter
-version=3.2.1
+version=3.3.0
 author=Rodrigo Garcia | GitHub @SuGlider
 maintainer=Rodrigo Garcia <Rodrigo.Garcia@espressif.com>
 sentence=Library for supporting Matter environment on ESP32.
diff --git a/libraries/NetBIOS/library.properties b/libraries/NetBIOS/library.properties
index a4bbf93c0ed..71d22d6f363 100644
--- a/libraries/NetBIOS/library.properties
+++ b/libraries/NetBIOS/library.properties
@@ -1,5 +1,5 @@
 name=NetBIOS
-version=3.2.1
+version=3.3.0
 author=Pablo@xpablo.cz
 maintainer=Hristo Gochkov<hristo@espressif.com>
 sentence=Enables NBNS (NetBIOS) name resolution.
diff --git a/libraries/Network/library.properties b/libraries/Network/library.properties
index f2284981704..f7e04f4de3b 100644
--- a/libraries/Network/library.properties
+++ b/libraries/Network/library.properties
@@ -1,5 +1,5 @@
 name=Networking
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=General network management library.
diff --git a/libraries/NetworkClientSecure/library.properties b/libraries/NetworkClientSecure/library.properties
index 31af7a1bc8c..6ebf4c0ec70 100644
--- a/libraries/NetworkClientSecure/library.properties
+++ b/libraries/NetworkClientSecure/library.properties
@@ -1,5 +1,5 @@
 name=NetworkClientSecure
-version=3.2.1
+version=3.3.0
 author=Evandro Luis Copercini
 maintainer=Github Community
 sentence=Enables secure network connection (local and Internet) using the ESP32 built-in WiFi.
diff --git a/libraries/OpenThread/library.properties b/libraries/OpenThread/library.properties
index 2687b1dcd1c..550d4eb1627 100644
--- a/libraries/OpenThread/library.properties
+++ b/libraries/OpenThread/library.properties
@@ -1,5 +1,5 @@
 name=OpenThread
-version=3.2.1
+version=3.3.0
 author=Rodrigo Garcia | GitHub @SuGlider
 maintainer=Rodrigo Garcia <Rodrigo.Garcia@espressif.com>
 sentence=Library for OpenThread Network on ESP32.
diff --git a/libraries/PPP/library.properties b/libraries/PPP/library.properties
index c39647cbe56..537708b1261 100644
--- a/libraries/PPP/library.properties
+++ b/libraries/PPP/library.properties
@@ -1,5 +1,5 @@
 name=PPP
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=Enables network connection using GSM Modem.
diff --git a/libraries/Preferences/library.properties b/libraries/Preferences/library.properties
index 6e0d38348c0..0a7e678aa6c 100644
--- a/libraries/Preferences/library.properties
+++ b/libraries/Preferences/library.properties
@@ -1,5 +1,5 @@
 name=Preferences
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=Provides friendly access to ESP32's Non-Volatile Storage
diff --git a/libraries/RainMaker/library.properties b/libraries/RainMaker/library.properties
index 71b4082a0a7..1d72a8faff5 100644
--- a/libraries/RainMaker/library.properties
+++ b/libraries/RainMaker/library.properties
@@ -1,5 +1,5 @@
 name=ESP RainMaker
-version=3.2.1
+version=3.3.0
 author=Sweety Mhaiske <switi.mhaiske@espressif.com>
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=ESP RainMaker Support
diff --git a/libraries/SD/library.properties b/libraries/SD/library.properties
index cc51196ed54..9d868dce799 100644
--- a/libraries/SD/library.properties
+++ b/libraries/SD/library.properties
@@ -1,5 +1,5 @@
 name=SD
-version=3.2.1
+version=3.3.0
 author=Arduino, SparkFun
 maintainer=Arduino <info@arduino.cc>
 sentence=Enables reading and writing on SD cards. For all Arduino boards.
diff --git a/libraries/SD_MMC/library.properties b/libraries/SD_MMC/library.properties
index 590eb8ebc52..f96ee4377c2 100644
--- a/libraries/SD_MMC/library.properties
+++ b/libraries/SD_MMC/library.properties
@@ -1,5 +1,5 @@
 name=SD_MMC
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov, Ivan Grokhtkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=ESP32 SDMMC File System
diff --git a/libraries/SPI/library.properties b/libraries/SPI/library.properties
index 724137030d1..3403d1c5d4f 100644
--- a/libraries/SPI/library.properties
+++ b/libraries/SPI/library.properties
@@ -1,5 +1,5 @@
 name=SPI
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=Enables the communication with devices that use the Serial Peripheral Interface (SPI) Bus. For all Arduino boards, BUT Arduino DUE.
diff --git a/libraries/SPIFFS/library.properties b/libraries/SPIFFS/library.properties
index fc4601e512c..486ec1b4ce6 100644
--- a/libraries/SPIFFS/library.properties
+++ b/libraries/SPIFFS/library.properties
@@ -1,5 +1,5 @@
 name=SPIFFS
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov, Ivan Grokhtkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=ESP32 SPIFFS File System
diff --git a/libraries/SimpleBLE/library.properties b/libraries/SimpleBLE/library.properties
index 768449ee1c4..a7f12207afe 100644
--- a/libraries/SimpleBLE/library.properties
+++ b/libraries/SimpleBLE/library.properties
@@ -1,5 +1,5 @@
 name=SimpleBLE
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=Provides really simple BLE advertizer with just on and off
diff --git a/libraries/TFLiteMicro/library.properties b/libraries/TFLiteMicro/library.properties
index 6ad0c32c7d5..d2dc127f5ab 100644
--- a/libraries/TFLiteMicro/library.properties
+++ b/libraries/TFLiteMicro/library.properties
@@ -1,5 +1,5 @@
 name=TFLite Micro
-version=3.2.1
+version=3.3.0
 author=Sanket Wadekar
 maintainer=Sanket Wadekar
 sentence=TensorFlow Lite for Microcontrollers
diff --git a/libraries/Ticker/library.properties b/libraries/Ticker/library.properties
index 8a2af554906..8795deb22ce 100644
--- a/libraries/Ticker/library.properties
+++ b/libraries/Ticker/library.properties
@@ -1,5 +1,5 @@
 name=Ticker
-version=3.2.1
+version=3.3.0
 author=Bert Melis
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=Allows to call functions with a given interval.
diff --git a/libraries/USB/library.properties b/libraries/USB/library.properties
index 677d736a635..4c2c032545e 100644
--- a/libraries/USB/library.properties
+++ b/libraries/USB/library.properties
@@ -1,5 +1,5 @@
 name=USB
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=ESP32S2 USB Library
diff --git a/libraries/Update/library.properties b/libraries/Update/library.properties
index 4c756397aba..5fd633ec358 100644
--- a/libraries/Update/library.properties
+++ b/libraries/Update/library.properties
@@ -1,5 +1,5 @@
 name=Update
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=ESP32 Sketch Update Library
diff --git a/libraries/WebServer/library.properties b/libraries/WebServer/library.properties
index bf6c26c65e7..913dd00e036 100644
--- a/libraries/WebServer/library.properties
+++ b/libraries/WebServer/library.properties
@@ -1,5 +1,5 @@
 name=WebServer
-version=3.2.1
+version=3.3.0
 author=Ivan Grokhotkov
 maintainer=Ivan Grokhtkov <ivan@esp8266.com>
 sentence=Simple web server library
diff --git a/libraries/WiFi/library.properties b/libraries/WiFi/library.properties
index a282570ff8a..82ccb32b702 100644
--- a/libraries/WiFi/library.properties
+++ b/libraries/WiFi/library.properties
@@ -1,5 +1,5 @@
 name=WiFi
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=Enables network connection (local and Internet) using the ESP32 built-in WiFi.
diff --git a/libraries/WiFiProv/library.properties b/libraries/WiFiProv/library.properties
index 1cc8e4b0f91..1b19186c40b 100644
--- a/libraries/WiFiProv/library.properties
+++ b/libraries/WiFiProv/library.properties
@@ -1,5 +1,5 @@
 name=WiFiProv
-version=3.2.1
+version=3.3.0
 author=Switi Mhaiske <sweetymhaiske@gmail.com>
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=Enables provisioning.
diff --git a/libraries/Wire/library.properties b/libraries/Wire/library.properties
index 22cc7f26d86..182e98790bc 100644
--- a/libraries/Wire/library.properties
+++ b/libraries/Wire/library.properties
@@ -1,5 +1,5 @@
 name=Wire
-version=3.2.1
+version=3.3.0
 author=Hristo Gochkov
 maintainer=Hristo Gochkov <hristo@espressif.com>
 sentence=Allows the communication between devices or sensors connected via Two Wire Interface Bus. For esp8266 boards.
diff --git a/libraries/Zigbee/library.properties b/libraries/Zigbee/library.properties
index d9587f49fd5..dab96b82a61 100644
--- a/libraries/Zigbee/library.properties
+++ b/libraries/Zigbee/library.properties
@@ -1,5 +1,5 @@
 name=Zigbee
-version=3.2.1
+version=3.3.0
 author=P-R-O-C-H-Y
 maintainer=Jan Procházka <jan.prochazka@espressif.com>
 sentence=Enables zigbee connection with the ESP32
diff --git a/package.json b/package.json
index 85a15ab3615..4c3e4725a9d 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
 {
   "name": "framework-arduinoespressif32",
-  "version": "3.2.1",
+  "version": "3.3.0",
   "description": "Arduino Wiring-based Framework for the Espressif ESP32, ESP32-P4, ESP32-S and ESP32-C series of SoCs",
   "keywords": [
     "framework",
diff --git a/platform.txt b/platform.txt
index 9e98650ca62..82560190c8f 100644
--- a/platform.txt
+++ b/platform.txt
@@ -1,5 +1,5 @@
 name=ESP32 Arduino
-version=3.2.1
+version=3.3.0
 
 tools.esp32-arduino-libs.path={runtime.platform.path}/tools/esp32-arduino-libs
 tools.esp32-arduino-libs.path.windows={runtime.platform.path}\tools\esp32-arduino-libs

From 98d309f84a997138e018174c05232e91836e681f Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Fri, 18 Jul 2025 10:44:01 +0300
Subject: [PATCH 049/105] feat(ci): Enable builds on IDF 5.3, 5.4 and 5.5

---
 .github/workflows/push.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml
index 68148fbcff7..f2f2c0b5ca1 100644
--- a/.github/workflows/push.yml
+++ b/.github/workflows/push.yml
@@ -248,7 +248,7 @@ jobs:
         # See https://hub.docker.com/r/espressif/idf/tags and
         # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/tools/idf-docker-image.html
         # for details.
-        idf_ver: ["release-v5.5"]
+        idf_ver: ["release-v5.3","release-v5.4","release-v5.5"]
         idf_target:
           [
             "esp32",

From 6cb518448793f0d42b81cf6e8d02662a8846c4fc Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Fri, 18 Jul 2025 11:12:22 +0300
Subject: [PATCH 050/105] fix(build): Fix build for IDF 5.3.3+ and older
 releases

---
 cores/esp32/esp32-hal-i2c-slave.c | 8 ++++++--
 cores/esp32/esp32-hal-ledc.c      | 3 +++
 2 files changed, 9 insertions(+), 2 deletions(-)

diff --git a/cores/esp32/esp32-hal-i2c-slave.c b/cores/esp32/esp32-hal-i2c-slave.c
index e616934958e..6d69418e787 100644
--- a/cores/esp32/esp32-hal-i2c-slave.c
+++ b/cores/esp32/esp32-hal-i2c-slave.c
@@ -338,7 +338,9 @@ esp_err_t i2cSlaveInit(uint8_t num, int sda, int scl, uint16_t slaveID, uint32_t
   }
 #endif  // !defined(CONFIG_IDF_TARGET_ESP32P4)
 
-#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
+#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)) \
+  || (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 2) && ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 5, 0)) \
+  || (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 3) && ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 4, 0))
   i2c_ll_set_mode(i2c->dev, I2C_BUS_MODE_SLAVE);
   i2c_ll_enable_pins_open_drain(i2c->dev, true);
   i2c_ll_enable_fifo_mode(i2c->dev, true);
@@ -366,7 +368,9 @@ esp_err_t i2cSlaveInit(uint8_t num, int sda, int scl, uint16_t slaveID, uint32_t
 
   i2c_ll_disable_intr_mask(i2c->dev, I2C_LL_INTR_MASK);
   i2c_ll_clear_intr_mask(i2c->dev, I2C_LL_INTR_MASK);
-#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
+#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)) \
+  || (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 2) && ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 5, 0)) \
+  || (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 3) && ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 4, 0))
   i2c_ll_enable_fifo_mode(i2c->dev, true);
 #else
   i2c_ll_slave_set_fifo_mode(i2c->dev, true);
diff --git a/cores/esp32/esp32-hal-ledc.c b/cores/esp32/esp32-hal-ledc.c
index 18b722f80a2..ffb24db4599 100644
--- a/cores/esp32/esp32-hal-ledc.c
+++ b/cores/esp32/esp32-hal-ledc.c
@@ -88,6 +88,9 @@ static bool find_free_timer(uint8_t speed_mode, uint8_t *timer_num) {
     }
   }
 
+#ifndef SOC_LEDC_TIMER_NUM
+#define SOC_LEDC_TIMER_NUM 4
+#endif
   // Find first unused timer
   for (uint8_t i = 0; i < SOC_LEDC_TIMER_NUM; i++) {
     if (!(used_timers & (1 << i))) {

From 346e7f41386bef558d56a6113d433f824667a278 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Fri, 18 Jul 2025 11:18:13 +0300
Subject: [PATCH 051/105] fix(build): Enable I2C FIFO mode only on IDF 5.5+

---
 cores/esp32/esp32-hal-i2c-slave.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/cores/esp32/esp32-hal-i2c-slave.c b/cores/esp32/esp32-hal-i2c-slave.c
index 6d69418e787..2a357b3a747 100644
--- a/cores/esp32/esp32-hal-i2c-slave.c
+++ b/cores/esp32/esp32-hal-i2c-slave.c
@@ -368,9 +368,7 @@ esp_err_t i2cSlaveInit(uint8_t num, int sda, int scl, uint16_t slaveID, uint32_t
 
   i2c_ll_disable_intr_mask(i2c->dev, I2C_LL_INTR_MASK);
   i2c_ll_clear_intr_mask(i2c->dev, I2C_LL_INTR_MASK);
-#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)) \
-  || (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 2) && ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 5, 0)) \
-  || (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 3) && ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 4, 0))
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
   i2c_ll_enable_fifo_mode(i2c->dev, true);
 #else
   i2c_ll_slave_set_fifo_mode(i2c->dev, true);

From 530c1a43fe9425061c396486d744110ce6ca6f83 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Fri, 18 Jul 2025 11:19:50 +0300
Subject: [PATCH 052/105] fix(build): Enable I2C FIFO mode only on IDF 5.4.2+

---
 cores/esp32/esp32-hal-i2c-slave.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/cores/esp32/esp32-hal-i2c-slave.c b/cores/esp32/esp32-hal-i2c-slave.c
index 2a357b3a747..c8e59653a8f 100644
--- a/cores/esp32/esp32-hal-i2c-slave.c
+++ b/cores/esp32/esp32-hal-i2c-slave.c
@@ -368,7 +368,7 @@ esp_err_t i2cSlaveInit(uint8_t num, int sda, int scl, uint16_t slaveID, uint32_t
 
   i2c_ll_disable_intr_mask(i2c->dev, I2C_LL_INTR_MASK);
   i2c_ll_clear_intr_mask(i2c->dev, I2C_LL_INTR_MASK);
-#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 2)
   i2c_ll_enable_fifo_mode(i2c->dev, true);
 #else
   i2c_ll_slave_set_fifo_mode(i2c->dev, true);

From 000336bad0446d3b8ded72b1d92e5edc407f8f69 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Fri, 18 Jul 2025 11:25:36 +0300
Subject: [PATCH 053/105] fix(build): Enable I2C FIFO mode only on IDF 5.4.2+

---
 cores/esp32/esp32-hal-i2c-slave.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/cores/esp32/esp32-hal-i2c-slave.c b/cores/esp32/esp32-hal-i2c-slave.c
index c8e59653a8f..79c994869e2 100644
--- a/cores/esp32/esp32-hal-i2c-slave.c
+++ b/cores/esp32/esp32-hal-i2c-slave.c
@@ -343,7 +343,11 @@ esp_err_t i2cSlaveInit(uint8_t num, int sda, int scl, uint16_t slaveID, uint32_t
   || (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 3) && ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 4, 0))
   i2c_ll_set_mode(i2c->dev, I2C_BUS_MODE_SLAVE);
   i2c_ll_enable_pins_open_drain(i2c->dev, true);
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 2)
   i2c_ll_enable_fifo_mode(i2c->dev, true);
+#else
+  i2c_ll_slave_set_fifo_mode(i2c->dev, true);
+#endif
 #else
   i2c_ll_slave_init(i2c->dev);
   i2c_ll_slave_set_fifo_mode(i2c->dev, true);

From 211a0ce1438ad7108ded0299238876f22036d946 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Fri, 18 Jul 2025 09:15:48 -0300
Subject: [PATCH 054/105] fix(ci): Fix artifact names

---
 .github/workflows/push.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml
index f2f2c0b5ca1..1523b7231be 100644
--- a/.github/workflows/push.yml
+++ b/.github/workflows/push.yml
@@ -283,7 +283,7 @@ jobs:
         uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
         if: always()
         with:
-          name: sdkconfig-${{ matrix.idf_target }}
+          name: sdkconfig-${{ matrix.idf_ver }}-${{ matrix.idf_target }}
           path: ./components/arduino-esp32/idf_component_examples/**/sdkconfig
 
   # Save artifacts to gh-pages

From 3ad17de6aa6f74f7d01bff4197f9f7a7481b2bb4 Mon Sep 17 00:00:00 2001
From: Sugar Glider <rodrigo.garcia@espressif.com>
Date: Fri, 18 Jul 2025 13:02:55 -0300
Subject: [PATCH 055/105] fix(build): make core compatible with IDF 5.3
 (#11607)

* fix(uart): make it compatible with IDF 5.3

* fix(ci): Fix artifact names

* fix(build): Fix ESP_NOW and WiFi for IDF 5.3

* fix(build): Fix NetworkClient for IDF 5.3

* fix(build): Fix WiFi for IDF 5.3

* fix(build): Fix WiFi Captive Portal for IDF 5.3

---------

Co-authored-by: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Co-authored-by: me-no-dev <hristo@espressif.com>
---
 cores/esp32/esp32-hal-uart.c                  | 11 +++++++++++
 libraries/ESP_NOW/src/ESP32_NOW.cpp           |  4 ++++
 libraries/Network/src/NetworkClient.cpp       |  8 +++-----
 libraries/WiFi/examples/WiFiScan/WiFiScan.ino |  2 ++
 libraries/WiFi/src/AP.cpp                     |  2 ++
 libraries/WiFi/src/WiFiAP.h                   |  2 ++
 libraries/WiFi/src/WiFiGeneric.cpp            |  2 ++
 libraries/WiFi/src/WiFiGeneric.h              |  2 ++
 8 files changed, 28 insertions(+), 5 deletions(-)

diff --git a/cores/esp32/esp32-hal-uart.c b/cores/esp32/esp32-hal-uart.c
index 6e5a22da9f8..8bd446a8eb8 100644
--- a/cores/esp32/esp32-hal-uart.c
+++ b/cores/esp32/esp32-hal-uart.c
@@ -389,7 +389,12 @@ static esp_err_t _uartInternalSetPin(uart_port_t uart_num, int tx_io_num, int rx
 #endif
     if (tx_rx_same_io || !_uartTrySetIomuxPin(uart_num, rx_io_num, SOC_UART_RX_PIN_IDX)) {
       if (uart_num < SOC_UART_HP_NUM) {
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
         gpio_input_enable(rx_io_num);
+#else
+        gpio_func_sel(rx_io_num, PIN_FUNC_GPIO);
+        gpio_ll_input_enable(&GPIO, rx_io_num);
+#endif
         esp_rom_gpio_connect_in_signal(rx_io_num, UART_PERIPH_SIGNAL(uart_num, SOC_UART_RX_PIN_IDX), 0);
       }
 #if SOC_LP_GPIO_MATRIX_SUPPORTED
@@ -422,8 +427,14 @@ static esp_err_t _uartInternalSetPin(uart_port_t uart_num, int tx_io_num, int rx
 
   if (cts_io_num >= 0 && !_uartTrySetIomuxPin(uart_num, cts_io_num, SOC_UART_CTS_PIN_IDX)) {
     if (uart_num < SOC_UART_HP_NUM) {
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
       gpio_pullup_en(cts_io_num);
       gpio_input_enable(cts_io_num);
+#else
+      gpio_func_sel(cts_io_num, PIN_FUNC_GPIO);
+      gpio_set_pull_mode(cts_io_num, GPIO_PULLUP_ONLY);
+      gpio_set_direction(cts_io_num, GPIO_MODE_INPUT);
+#endif
       esp_rom_gpio_connect_in_signal(cts_io_num, UART_PERIPH_SIGNAL(uart_num, SOC_UART_CTS_PIN_IDX), 0);
     }
 #if SOC_LP_GPIO_MATRIX_SUPPORTED
diff --git a/libraries/ESP_NOW/src/ESP32_NOW.cpp b/libraries/ESP_NOW/src/ESP32_NOW.cpp
index d461fe1473d..e61160a16dd 100644
--- a/libraries/ESP_NOW/src/ESP32_NOW.cpp
+++ b/libraries/ESP_NOW/src/ESP32_NOW.cpp
@@ -9,6 +9,10 @@
 #include "esp32-hal.h"
 #include "esp_wifi.h"
 
+#ifndef ESP_NOW_MAX_DATA_LEN_V2
+#define ESP_NOW_MAX_DATA_LEN_V2 1470
+#endif
+
 static void (*new_cb)(const esp_now_recv_info_t *info, const uint8_t *data, int len, void *arg) = nullptr;
 static void *new_arg = nullptr;  // * tx_arg = nullptr, * rx_arg = nullptr,
 static bool _esp_now_has_begun = false;
diff --git a/libraries/Network/src/NetworkClient.cpp b/libraries/Network/src/NetworkClient.cpp
index 89411a42453..355cbc6c361 100644
--- a/libraries/Network/src/NetworkClient.cpp
+++ b/libraries/Network/src/NetworkClient.cpp
@@ -23,11 +23,9 @@
 #include <lwip/netdb.h>
 #include <errno.h>
 
-// It is already defined in IDF as:
-//#define IN6_IS_ADDR_V4MAPPED(a)     ip6_addr_isipv4mappedipv6((ip6_addr_t*)(a))
-//#define ip6_addr_isipv4mappedipv6(ip6addr) (((ip6addr)->addr[0] == 0) && ((ip6addr)->addr[1] == 0) && (((ip6addr)->addr[2]) == PP_HTONL(0x0000FFFFUL)))
-// Keeping as a memory of the change.
-//#define _IN6_IS_ADDR_V4MAPPED(a) ((((__const uint32_t *)(a))[0] == 0) && (((__const uint32_t *)(a))[1] == 0) && (((__const uint32_t *)(a))[2] == htonl(0xffff)))
+#ifndef IN6_IS_ADDR_V4MAPPED
+#define IN6_IS_ADDR_V4MAPPED(a) ((((__const uint32_t *)(a))[0] == 0) && (((__const uint32_t *)(a))[1] == 0) && (((__const uint32_t *)(a))[2] == htonl(0xffff)))
+#endif
 
 #define WIFI_CLIENT_DEF_CONN_TIMEOUT_MS (3000)
 #define WIFI_CLIENT_MAX_WRITE_RETRY     (10)
diff --git a/libraries/WiFi/examples/WiFiScan/WiFiScan.ino b/libraries/WiFi/examples/WiFiScan/WiFiScan.ino
index 98733adb0bb..d840959dcb2 100644
--- a/libraries/WiFi/examples/WiFiScan/WiFiScan.ino
+++ b/libraries/WiFi/examples/WiFiScan/WiFiScan.ino
@@ -58,7 +58,9 @@ void loop() {
   Serial.println("-------------------------------------");
   Serial.println("Default wifi band mode scan:");
   Serial.println("-------------------------------------");
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 2)
   WiFi.setBandMode(WIFI_BAND_MODE_AUTO);
+#endif
   ScanWiFi();
 #if CONFIG_SOC_WIFI_SUPPORT_5G
   // Wait a bit before scanning again.
diff --git a/libraries/WiFi/src/AP.cpp b/libraries/WiFi/src/AP.cpp
index a649c3898cb..00c3a1e3733 100644
--- a/libraries/WiFi/src/AP.cpp
+++ b/libraries/WiFi/src/AP.cpp
@@ -305,6 +305,7 @@ bool APClass::enableNAPT(bool enable) {
   return true;
 }
 
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 2)
 bool APClass::enableDhcpCaptivePortal() {
   esp_err_t err = ESP_OK;
   static char captiveportal_uri[32] = {
@@ -343,6 +344,7 @@ bool APClass::enableDhcpCaptivePortal() {
 
   return true;
 }
+#endif
 
 String APClass::SSID(void) const {
   if (!started()) {
diff --git a/libraries/WiFi/src/WiFiAP.h b/libraries/WiFi/src/WiFiAP.h
index 2b7ce469801..67cc0f988d3 100644
--- a/libraries/WiFi/src/WiFiAP.h
+++ b/libraries/WiFi/src/WiFiAP.h
@@ -53,7 +53,9 @@ class APClass : public NetworkInterface {
 
   bool bandwidth(wifi_bandwidth_t bandwidth);
   bool enableNAPT(bool enable = true);
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 2)
   bool enableDhcpCaptivePortal();
+#endif
 
   String SSID(void) const;
   uint8_t stationCount();
diff --git a/libraries/WiFi/src/WiFiGeneric.cpp b/libraries/WiFi/src/WiFiGeneric.cpp
index 171bd293738..66f8908af77 100644
--- a/libraries/WiFi/src/WiFiGeneric.cpp
+++ b/libraries/WiFi/src/WiFiGeneric.cpp
@@ -781,6 +781,7 @@ wifi_ps_type_t WiFiGenericClass::getSleep() {
   return _sleepEnabled;
 }
 
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 2)
 /**
  * control wifi band mode
  * @param band_mode enum possible band modes
@@ -843,6 +844,7 @@ wifi_band_mode_t WiFiGenericClass::getBandMode() {
   return WIFI_BAND_MODE_2G_ONLY;
 #endif
 }
+#endif
 
 /**
  * get the current active wifi band
diff --git a/libraries/WiFi/src/WiFiGeneric.h b/libraries/WiFi/src/WiFiGeneric.h
index ebeecb51e16..cdc1519d30b 100644
--- a/libraries/WiFi/src/WiFiGeneric.h
+++ b/libraries/WiFi/src/WiFiGeneric.h
@@ -116,8 +116,10 @@ class WiFiGenericClass {
   bool setTxPower(wifi_power_t power);
   wifi_power_t getTxPower();
 
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 2)
   bool setBandMode(wifi_band_mode_t band_mode);
   wifi_band_mode_t getBandMode();
+#endif
   wifi_band_t getBand();
 
   bool initiateFTM(uint8_t frm_count = 16, uint16_t burst_period = 2, uint8_t channel = 1, const uint8_t *mac = NULL);

From 9641de1b12c3ae4980fc1c6b9a2f939a0b6d4934 Mon Sep 17 00:00:00 2001
From: Paula Scharf <paulascharf@gmx.de>
Date: Thu, 3 Jul 2025 15:22:07 +0200
Subject: [PATCH 056/105] feat(board): add senseBox Eye board

---
 boards.txt                                    | 190 ++++++++++++++++++
 variants/sensebox_eye/bootloader-tinyuf2.bin  | Bin 0 -> 22352 bytes
 .../sensebox_eye/partitions-16MB-tinyuf2.csv  |  10 +
 variants/sensebox_eye/pins_arduino.h          |  90 +++++++++
 variants/sensebox_eye/tinyuf2.bin             | Bin 0 -> 186912 bytes
 variants/sensebox_eye/variant.cpp             |  71 +++++++
 6 files changed, 361 insertions(+)
 create mode 100644 variants/sensebox_eye/bootloader-tinyuf2.bin
 create mode 100644 variants/sensebox_eye/partitions-16MB-tinyuf2.csv
 create mode 100644 variants/sensebox_eye/pins_arduino.h
 create mode 100644 variants/sensebox_eye/tinyuf2.bin
 create mode 100644 variants/sensebox_eye/variant.cpp

diff --git a/boards.txt b/boards.txt
index ac2b1a336e4..2363fe2a63b 100644
--- a/boards.txt
+++ b/boards.txt
@@ -41309,6 +41309,196 @@ sensebox_mcu_esp32s2.menu.EraseFlash.none.upload.erase_cmd=
 sensebox_mcu_esp32s2.menu.EraseFlash.all=Enabled
 sensebox_mcu_esp32s2.menu.EraseFlash.all.upload.erase_cmd=-e
 
+##############################################################
+# senseBox Eye
+
+sensebox_eye.name=senseBox Eye
+senseBox_eye.vid.0=0x303A
+senseBox_eye.pid.0=0x82D1
+senseBox_eye.vid.1=0x303A
+senseBox_eye.pid.1=0x82D2
+senseBox_eye.vid.2=0x303A
+senseBox_eye.pid.2=0x82D3
+
+sensebox_eye.bootloader.tool=esptool_py
+sensebox_eye.bootloader.tool.default=esptool_py
+
+sensebox_eye.upload.tool=esptool_py
+sensebox_eye.upload.tool.default=esptool_py
+sensebox_eye.upload.tool.network=esp_ota
+
+sensebox_eye.upload.maximum_size=1310720
+sensebox_eye.upload.maximum_data_size=327680
+sensebox_eye.upload.flags=
+sensebox_eye.upload.extra_flags=
+sensebox_eye.upload.use_1200bps_touch=true
+sensebox_eye.upload.wait_for_upload_port=true
+
+sensebox_eye.serial.disableDTR=true
+sensebox_eye.serial.disableRTS=true
+
+sensebox_eye.build.tarch=xtensa
+sensebox_eye.build.bootloader_addr=0x0
+sensebox_eye.build.target=esp32s3
+sensebox_eye.build.mcu=esp32s3
+sensebox_eye.build.core=esp32
+sensebox_eye.build.variant=sensebox_eye
+sensebox_eye.build.board=sensebox_eye
+
+sensebox_eye.build.usb_mode=0
+sensebox_eye.build.cdc_on_boot=1
+sensebox_eye.build.msc_on_boot=1
+sensebox_eye.build.dfu_on_boot=0
+sensebox_eye.build.f_cpu=240000000L
+sensebox_eye.build.flash_size=16MB (128Mb)
+sensebox_eye.build.flash_freq=80m
+sensebox_eye.build.flash_mode=dio
+sensebox_eye.build.boot=qio
+sensebox_eye.build.boot_freq=80m
+sensebox_eye.build.partitions=default_16MB
+sensebox_eye.build.defines=
+sensebox_eye.build.loop_core=
+sensebox_eye.build.event_core=
+sensebox_eye.build.psram_type=qspi
+sensebox_eye.build.memory_type={build.boot}_{build.psram_type}
+
+sensebox_eye.menu.JTAGAdapter.default=Disabled
+sensebox_eye.menu.JTAGAdapter.default.build.copy_jtag_files=0
+sensebox_eye.menu.JTAGAdapter.builtin=Integrated USB JTAG
+sensebox_eye.menu.JTAGAdapter.builtin.build.openocdscript=esp32s3-builtin.cfg
+sensebox_eye.menu.JTAGAdapter.builtin.build.copy_jtag_files=1
+sensebox_eye.menu.JTAGAdapter.external=FTDI Adapter
+sensebox_eye.menu.JTAGAdapter.external.build.openocdscript=esp32s3-ftdi.cfg
+sensebox_eye.menu.JTAGAdapter.external.build.copy_jtag_files=1
+sensebox_eye.menu.JTAGAdapter.bridge=ESP USB Bridge
+sensebox_eye.menu.JTAGAdapter.bridge.build.openocdscript=esp32s3-bridge.cfg
+sensebox_eye.menu.JTAGAdapter.bridge.build.copy_jtag_files=1
+
+sensebox_eye.menu.PSRAM.disabled=Disabled
+sensebox_eye.menu.PSRAM.disabled.build.defines=
+sensebox_eye.menu.PSRAM.disabled.build.psram_type=qspi
+sensebox_eye.menu.PSRAM.opi=OPI PSRAM
+sensebox_eye.menu.PSRAM.opi.build.defines=-DBOARD_HAS_PSRAM
+sensebox_eye.menu.PSRAM.opi.build.psram_type=opi
+
+sensebox_eye.menu.FlashMode.qio=QIO 80MHz
+sensebox_eye.menu.FlashMode.qio.build.flash_mode=dio
+sensebox_eye.menu.FlashMode.qio.build.boot=qio
+sensebox_eye.menu.FlashMode.qio.build.boot_freq=80m
+sensebox_eye.menu.FlashMode.qio.build.flash_freq=80m
+sensebox_eye.menu.FlashMode.dio=DIO 80MHz
+sensebox_eye.menu.FlashMode.dio.build.flash_mode=dio
+sensebox_eye.menu.FlashMode.dio.build.boot=dio
+sensebox_eye.menu.FlashMode.dio.build.boot_freq=80m
+sensebox_eye.menu.FlashMode.dio.build.flash_freq=80m
+
+sensebox_eye.menu.FlashSize.16M=16MB (128Mb)
+sensebox_eye.menu.FlashSize.16M.build.flash_size=16MB
+
+sensebox_eye.menu.LoopCore.1=Core 1
+sensebox_eye.menu.LoopCore.1.build.loop_core=-DARDUINO_RUNNING_CORE=1
+sensebox_eye.menu.LoopCore.0=Core 0
+sensebox_eye.menu.LoopCore.0.build.loop_core=-DARDUINO_RUNNING_CORE=0
+
+sensebox_eye.menu.EventsCore.1=Core 1
+sensebox_eye.menu.EventsCore.1.build.event_core=-DARDUINO_EVENT_RUNNING_CORE=1
+sensebox_eye.menu.EventsCore.0=Core 0
+sensebox_eye.menu.EventsCore.0.build.event_core=-DARDUINO_EVENT_RUNNING_CORE=0
+
+sensebox_eye.menu.USBMode.hwcdc=Hardware CDC and JTAG
+sensebox_eye.menu.USBMode.hwcdc.build.usb_mode=1
+sensebox_eye.menu.USBMode.default=USB-OTG (TinyUSB)
+sensebox_eye.menu.USBMode.default.build.usb_mode=0
+
+sensebox_eye.menu.CDCOnBoot.default=Enabled
+sensebox_eye.menu.CDCOnBoot.default.build.cdc_on_boot=1
+sensebox_eye.menu.CDCOnBoot.cdc=Disabled
+sensebox_eye.menu.CDCOnBoot.cdc.build.cdc_on_boot=0
+
+sensebox_eye.menu.MSCOnBoot.default=Disabled
+sensebox_eye.menu.MSCOnBoot.default.build.msc_on_boot=0
+sensebox_eye.menu.MSCOnBoot.msc=Enabled (Requires USB-OTG Mode)
+sensebox_eye.menu.MSCOnBoot.msc.build.msc_on_boot=1
+
+sensebox_eye.menu.DFUOnBoot.default=Disabled
+sensebox_eye.menu.DFUOnBoot.default.build.dfu_on_boot=0
+sensebox_eye.menu.DFUOnBoot.dfu=Enabled (Requires USB-OTG Mode)
+sensebox_eye.menu.DFUOnBoot.dfu.build.dfu_on_boot=1
+
+sensebox_eye.menu.UploadMode.default=UART0 / Hardware CDC
+sensebox_eye.menu.UploadMode.default.upload.use_1200bps_touch=false
+sensebox_eye.menu.UploadMode.default.upload.wait_for_upload_port=false
+sensebox_eye.menu.UploadMode.cdc=USB-OTG CDC (TinyUSB)
+sensebox_eye.menu.UploadMode.cdc.upload.use_1200bps_touch=true
+sensebox_eye.menu.UploadMode.cdc.upload.wait_for_upload_port=true
+
+sensebox_eye.menu.PartitionScheme.default_16MB=Default (6.25MB APP/3.43MB SPIFFS)
+sensebox_eye.menu.PartitionScheme.default_16MB.build.partitions=default_16MB
+sensebox_eye.menu.PartitionScheme.default_16MB.upload.maximum_size=6553600
+sensebox_eye.menu.PartitionScheme.large_spiffs=Large SPIFFS (4.5MB APP/6.93MB SPIFFS)
+sensebox_eye.menu.PartitionScheme.large_spiffs.build.partitions=large_spiffs_16MB
+sensebox_eye.menu.PartitionScheme.large_spiffs.upload.maximum_size=4718592
+sensebox_eye.menu.PartitionScheme.app3M_fat9M_16MB=FFAT (3MB APP/9MB FATFS)
+sensebox_eye.menu.PartitionScheme.app3M_fat9M_16MB.build.partitions=app3M_fat9M_16MB
+sensebox_eye.menu.PartitionScheme.app3M_fat9M_16MB.upload.maximum_size=3145728
+sensebox_eye.menu.PartitionScheme.fatflash=Large FFAT (2MB APP/12.5MB FATFS)
+sensebox_eye.menu.PartitionScheme.fatflash.build.partitions=ffat
+sensebox_eye.menu.PartitionScheme.fatflash.upload.maximum_size=2097152
+sensebox_eye.menu.PartitionScheme.tinyuf2=TinyUF2 Compatibility (2MB APP/12MB FFAT)
+sensebox_eye.menu.PartitionScheme.tinyuf2.build.custom_bootloader=bootloader_tinyuf2
+sensebox_eye.menu.PartitionScheme.tinyuf2.build.custom_partitions=partitions_tinyuf2
+sensebox_eye.menu.PartitionScheme.tinyuf2.upload.maximum_size=2097152
+sensebox_eye.menu.PartitionScheme.tinyuf2.upload.extra_flags=0x410000 "{runtime.platform.path}/variants/{build.variant}/tinyuf2.bin"
+sensebox_eye.menu.PartitionScheme.gen4esp32scheme4=Huge App (16MB APP)
+sensebox_eye.menu.PartitionScheme.gen4esp32scheme4.build.custom_partitions=gen4esp32_16MBapp
+sensebox_eye.menu.PartitionScheme.gen4esp32scheme4.upload.maximum_size=16646144
+
+sensebox_eye.menu.CPUFreq.240=240MHz (WiFi)
+sensebox_eye.menu.CPUFreq.240.build.f_cpu=240000000L
+sensebox_eye.menu.CPUFreq.160=160MHz (WiFi)
+sensebox_eye.menu.CPUFreq.160.build.f_cpu=160000000L
+sensebox_eye.menu.CPUFreq.80=80MHz (WiFi)
+sensebox_eye.menu.CPUFreq.80.build.f_cpu=80000000L
+sensebox_eye.menu.CPUFreq.40=40MHz
+sensebox_eye.menu.CPUFreq.40.build.f_cpu=40000000L
+sensebox_eye.menu.CPUFreq.20=20MHz
+sensebox_eye.menu.CPUFreq.20.build.f_cpu=20000000L
+sensebox_eye.menu.CPUFreq.10=10MHz
+sensebox_eye.menu.CPUFreq.10.build.f_cpu=10000000L
+
+sensebox_eye.menu.UploadSpeed.921600=921600
+sensebox_eye.menu.UploadSpeed.921600.upload.speed=921600
+sensebox_eye.menu.UploadSpeed.115200=115200
+sensebox_eye.menu.UploadSpeed.115200.upload.speed=115200
+sensebox_eye.menu.UploadSpeed.256000.windows=256000
+sensebox_eye.menu.UploadSpeed.256000.upload.speed=256000
+sensebox_eye.menu.UploadSpeed.230400.windows.upload.speed=256000
+sensebox_eye.menu.UploadSpeed.230400=230400
+sensebox_eye.menu.UploadSpeed.230400.upload.speed=230400
+sensebox_eye.menu.UploadSpeed.460800.linux=460800
+sensebox_eye.menu.UploadSpeed.460800.macosx=460800
+sensebox_eye.menu.UploadSpeed.460800.upload.speed=460800
+sensebox_eye.menu.UploadSpeed.512000.windows=512000
+sensebox_eye.menu.UploadSpeed.512000.upload.speed=512000
+
+sensebox_eye.menu.DebugLevel.none=None
+sensebox_eye.menu.DebugLevel.none.build.code_debug=0
+sensebox_eye.menu.DebugLevel.error=Error
+sensebox_eye.menu.DebugLevel.error.build.code_debug=1
+sensebox_eye.menu.DebugLevel.warn=Warn
+sensebox_eye.menu.DebugLevel.warn.build.code_debug=2
+sensebox_eye.menu.DebugLevel.info=Info
+sensebox_eye.menu.DebugLevel.info.build.code_debug=3
+sensebox_eye.menu.DebugLevel.debug=Debug
+sensebox_eye.menu.DebugLevel.debug.build.code_debug=4
+sensebox_eye.menu.DebugLevel.verbose=Verbose
+sensebox_eye.menu.DebugLevel.verbose.build.code_debug=5
+
+sensebox_eye.menu.EraseFlash.none=Disabled
+sensebox_eye.menu.EraseFlash.none.upload.erase_cmd=
+sensebox_eye.menu.EraseFlash.all=Enabled
+sensebox_eye.menu.EraseFlash.all.upload.erase_cmd=-e
+
 ##############################################################
 
 nano_nora.name=Arduino Nano ESP32
diff --git a/variants/sensebox_eye/bootloader-tinyuf2.bin b/variants/sensebox_eye/bootloader-tinyuf2.bin
new file mode 100644
index 0000000000000000000000000000000000000000..c7676c718f2383a78785da38dcffde52ca67eab0
GIT binary patch
diff --git a/variants/sensebox_eye/partitions-16MB-tinyuf2.csv b/variants/sensebox_eye/partitions-16MB-tinyuf2.csv
new file mode 100644
index 00000000000..960f3fbbd71
--- /dev/null
+++ b/variants/sensebox_eye/partitions-16MB-tinyuf2.csv
@@ -0,0 +1,10 @@
+# ESP-IDF Partition Table
+# Name,   Type, SubType, Offset,  Size, Flags
+# bootloader.bin,,          0x1000, 32K
+# partition table,          0x8000, 4K
+nvs,      data, nvs,      0x9000,  20K,
+otadata,  data, ota,      0xe000,  8K,
+ota_0,    0,    ota_0,   0x10000,  2048K,
+ota_1,    0,    ota_1,  0x210000,  2048K,
+uf2,      app,  factory,0x410000,  256K,
+ffat,     data, fat,    0x450000,  11968K,
\ No newline at end of file
diff --git a/variants/sensebox_eye/pins_arduino.h b/variants/sensebox_eye/pins_arduino.h
new file mode 100644
index 00000000000..583cb38283e
--- /dev/null
+++ b/variants/sensebox_eye/pins_arduino.h
@@ -0,0 +1,90 @@
+#ifndef Pins_Arduino_h
+#define Pins_Arduino_h
+
+#include <stdint.h>
+
+#define USB_VID          0x303A
+#define USB_PID          0x81B8
+#define USB_MANUFACTURER "senseBox"
+#define USB_PRODUCT      "Eye ESP32S3"
+#define USB_SERIAL       ""  // Empty string for MAC address
+
+// Default USB FirmwareMSC Settings
+#define USB_FW_MSC_VENDOR_ID        "senseBox"        // max 8 chars
+#define USB_FW_MSC_PRODUCT_ID       "Eye ESP32S3"  // max 16 chars
+#define USB_FW_MSC_PRODUCT_REVISION "1.00"            // max 4 chars
+#define USB_FW_MSC_VOLUME_NAME      "senseBox"        // max 11 chars
+#define USB_FW_MSC_SERIAL_NUMBER    0x00000000
+
+#define PIN_RGB_LED 45  // RGB LED
+#define RGBLED_PIN  45  // RGB LED
+#define PIN_LED   45
+#define RGBLED_NUM  1  // number of RGB LEDs
+
+// Default I2C QWIIC-Ports
+static const uint8_t SDA = 2;
+static const uint8_t SCL = 1;
+#define PIN_QWIIC_SDA 2
+#define PIN_QWIIC_SCL 1
+
+// IO Pins
+#define PIN_IO14   14
+static const uint8_t A14 = PIN_IO14; // Analog
+static const uint8_t D14 = PIN_IO14; // Digital
+static const uint8_t T14 = PIN_IO14; // Touch
+#define PIN_IO48   48
+static const uint8_t A48 = PIN_IO48; // Analog
+static const uint8_t D48 = PIN_IO48; // Digital
+static const uint8_t T48 = PIN_IO48; // Touch
+
+// Button
+#define PIN_BUTTON 47
+
+// UART Port
+static const uint8_t TX = 43;
+static const uint8_t RX = 44;
+#define PIN_UART_TXD    43
+#define PIN_UART_RXD    44
+#define PIN_UART_ENABLE 26
+
+// SD-Card
+#define MISO      40
+#define MOSI      38
+#define SCK       39
+#define SS        41
+#define SD_ENABLE 3
+
+#define PIN_SD_MISO   40
+#define PIN_SD_MOSI   38
+#define PIN_SD_SCLK   39
+#define PIN_SD_CS     41
+#define PIN_SD_ENABLE 3
+
+// USB
+#define PIN_USB_DM 19
+#define PIN_USB_DP 20
+
+// Camera
+#define PWDN_GPIO_NUM  46
+#define RESET_GPIO_NUM -1
+#define XCLK_GPIO_NUM  15
+#define SIOD_GPIO_NUM  4
+#define SIOC_GPIO_NUM  5
+
+#define Y9_GPIO_NUM    16
+#define Y8_GPIO_NUM    17
+#define Y7_GPIO_NUM    18
+#define Y6_GPIO_NUM    12
+#define Y5_GPIO_NUM    10
+#define Y4_GPIO_NUM    8
+#define Y3_GPIO_NUM    9
+#define Y2_GPIO_NUM    11
+#define VSYNC_GPIO_NUM 6
+#define HREF_GPIO_NUM  7
+#define PCLK_GPIO_NUM  13
+
+// LoRa
+#define LORA_TX 43
+#define LORA_RX 44
+
+#endif /* Pins_Arduino_h */
\ No newline at end of file
diff --git a/variants/sensebox_eye/tinyuf2.bin b/variants/sensebox_eye/tinyuf2.bin
new file mode 100644
index 0000000000000000000000000000000000000000..6b0fb1bcd0417ce9175fc75bf09b49f7516ab078
GIT binary patch
diff --git a/variants/sensebox_eye/variant.cpp b/variants/sensebox_eye/variant.cpp
new file mode 100644
index 00000000000..42269d11357
--- /dev/null
+++ b/variants/sensebox_eye/variant.cpp
@@ -0,0 +1,71 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2021 Ha Thach (tinyusb.org) for Adafruit Industries
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "esp32-hal-gpio.h"
+#include "pins_arduino.h"
+#include "driver/rmt_tx.h"
+#include "esp_log.h"
+
+extern "C" {
+
+void initVariant(void) {
+  rmt_channel_handle_t led_chan = NULL;
+  rmt_tx_channel_config_t tx_chan_config = {};
+  tx_chan_config.clk_src = RMT_CLK_SRC_DEFAULT;
+  tx_chan_config.resolution_hz = 10 * 1000 * 1000;
+  tx_chan_config.mem_block_symbols = 64;
+  tx_chan_config.trans_queue_depth = 4;
+  tx_chan_config.gpio_num = (gpio_num_t)PIN_LED;
+  tx_chan_config.flags.invert_out = false;
+  tx_chan_config.flags.with_dma = false;
+  ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &led_chan));
+
+  // WS2812 encoder config (available in `esp-rmt`)
+  rmt_encoder_handle_t ws2812_encoder = NULL;
+  rmt_bytes_encoder_config_t bytes_encoder_config = {
+    .bit0 = { .duration0 = 4, .level0 = 1, .duration1 = 9, .level1 = 0 },
+    .bit1 = { .duration0 = 8, .level0 = 1, .duration1 = 5, .level1 = 0 },
+    .flags = { .msb_first = true }
+  };
+  ESP_ERROR_CHECK(rmt_new_bytes_encoder(&bytes_encoder_config, &ws2812_encoder));
+
+  ESP_ERROR_CHECK(rmt_enable(led_chan));
+
+  // WS2812 GRB data (green pixel)
+  uint8_t pixel[3] = { 0x10, 0x00, 0x00 }; // green
+  rmt_transmit_config_t tx_config = {
+    .loop_count = 0
+  };
+  ESP_ERROR_CHECK(rmt_transmit(led_chan, ws2812_encoder, pixel, sizeof(pixel), &tx_config));
+  rmt_tx_wait_all_done(led_chan, portMAX_DELAY);
+
+  // Wait a moment
+  delay(50);
+
+  // Turn LED off
+  uint8_t pixel_off[3] = { 0x00, 0x00, 0x00 };
+  ESP_ERROR_CHECK(rmt_transmit(led_chan, ws2812_encoder, pixel_off, sizeof(pixel_off), &tx_config));
+  rmt_tx_wait_all_done(led_chan, portMAX_DELAY);
+}
+}

From 6a33f0bfc137a664111e5bbce62c05511f9727a2 Mon Sep 17 00:00:00 2001
From: Paula Scharf <paulascharf@gmx.de>
Date: Wed, 9 Jul 2025 16:52:51 +0200
Subject: [PATCH 057/105] fix(board): add APOTA description comments

---
 variants/sensebox_mcu_esp32s2/APOTA.ino | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/variants/sensebox_mcu_esp32s2/APOTA.ino b/variants/sensebox_mcu_esp32s2/APOTA.ino
index 5f683752abc..afb741499b2 100644
--- a/variants/sensebox_mcu_esp32s2/APOTA.ino
+++ b/variants/sensebox_mcu_esp32s2/APOTA.ino
@@ -1,3 +1,7 @@
+// APOTA is a arduino fallback sketch that is written to OTA1_Partition. 
+// APOTA opens an access point which waits to receive a .binfile on /sketch. 
+// After succesful upload, the file is written to OTA0_Partition and the microcontroller reboots to the newly uploaded sketch.
+
 #define DISPLAY_ENABLED
 
 #include <WiFi.h>

From 76210797ed11288bfd3c6c27122f0103562196d3 Mon Sep 17 00:00:00 2001
From: Paula Scharf <paulascharf@gmx.de>
Date: Wed, 9 Jul 2025 16:53:33 +0200
Subject: [PATCH 058/105] fix(board): add APOTA to senseBox Eye

---
 boards.txt                        |   2 +-
 variants/sensebox_eye/APOTA.bin   | Bin 0 -> 976464 bytes
 variants/sensebox_eye/APOTA.ino   | 287 ++++++++++++++++++++++++++++++
 variants/sensebox_eye/variant.cpp |  65 +++++--
 4 files changed, 343 insertions(+), 11 deletions(-)
 create mode 100644 variants/sensebox_eye/APOTA.bin
 create mode 100644 variants/sensebox_eye/APOTA.ino

diff --git a/boards.txt b/boards.txt
index 2363fe2a63b..faa7f94a994 100644
--- a/boards.txt
+++ b/boards.txt
@@ -41448,7 +41448,7 @@ sensebox_eye.menu.PartitionScheme.tinyuf2=TinyUF2 Compatibility (2MB APP/12MB FF
 sensebox_eye.menu.PartitionScheme.tinyuf2.build.custom_bootloader=bootloader_tinyuf2
 sensebox_eye.menu.PartitionScheme.tinyuf2.build.custom_partitions=partitions_tinyuf2
 sensebox_eye.menu.PartitionScheme.tinyuf2.upload.maximum_size=2097152
-sensebox_eye.menu.PartitionScheme.tinyuf2.upload.extra_flags=0x410000 "{runtime.platform.path}/variants/{build.variant}/tinyuf2.bin"
+sensebox_eye.menu.PartitionScheme.tinyuf2.upload.extra_flags=0x410000 "{runtime.platform.path}/variants/{build.variant}/tinyuf2.bin" 0x210000 "{runtime.platform.path}/variants/{build.variant}/APOTA.bin"
 sensebox_eye.menu.PartitionScheme.gen4esp32scheme4=Huge App (16MB APP)
 sensebox_eye.menu.PartitionScheme.gen4esp32scheme4.build.custom_partitions=gen4esp32_16MBapp
 sensebox_eye.menu.PartitionScheme.gen4esp32scheme4.upload.maximum_size=16646144
diff --git a/variants/sensebox_eye/APOTA.bin b/variants/sensebox_eye/APOTA.bin
new file mode 100644
index 0000000000000000000000000000000000000000..571336d378a9aaee97e074142d0e73cad85eacc9
GIT binary patch
diff --git a/variants/sensebox_eye/APOTA.ino b/variants/sensebox_eye/APOTA.ino
new file mode 100644
index 00000000000..afb741499b2
--- /dev/null
+++ b/variants/sensebox_eye/APOTA.ino
@@ -0,0 +1,287 @@
+// APOTA is a arduino fallback sketch that is written to OTA1_Partition. 
+// APOTA opens an access point which waits to receive a .binfile on /sketch. 
+// After succesful upload, the file is written to OTA0_Partition and the microcontroller reboots to the newly uploaded sketch.
+
+#define DISPLAY_ENABLED
+
+#include <WiFi.h>
+#include <WebServer.h>
+#include <ESPmDNS.h>
+#include <WiFiAP.h>
+#include <Update.h>
+#include <Wire.h>
+#ifdef DISPLAY_ENABLED
+#define SCREEN_WIDTH  128
+#define SCREEN_HEIGHT 64
+#define OLED_RESET    -1
+#include <Adafruit_GFX.h>
+#include <Adafruit_SSD1306.h>
+Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
+#include <Adafruit_NeoPixel.h>
+Adafruit_NeoPixel rgb_led_1 = Adafruit_NeoPixel(1, 1, NEO_GRB + NEO_KHZ800);
+
+#endif
+#include "esp_partition.h"
+#include "esp_ota_ops.h"
+#include "esp_system.h"
+
+String ssid;
+uint8_t mac[6];
+
+// Create an instance of the server
+WebServer server(80);
+bool displayEnabled;
+
+const int BUTTON_PIN = 0;                       // GPIO for the button
+volatile unsigned long lastPressTime = 0;       // Time of last button press
+volatile bool doublePressDetected = false;      // Flag for double press
+const unsigned long doublePressInterval = 500;  // Max. time (in ms) between two presses for double press
+volatile int pressCount = 0;                    // Counts the button presses
+
+const unsigned char epd_bitmap_wifi[] PROGMEM = {
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x01, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x07, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x1f, 0xe0, 0xff, 0x00, 0x00,
+  0x00, 0x3f, 0x00, 0x0f, 0x80, 0x00, 0x00, 0x7c, 0x00, 0x03, 0xe0, 0x00, 0x00, 0xf0, 0x00, 0x01, 0xf0, 0x00, 0x01, 0xe0, 0x00, 0x00, 0x78, 0x00,
+  0x03, 0xc0, 0x00, 0x00, 0x38, 0x00, 0x07, 0x80, 0x00, 0x00, 0x1c, 0x00, 0x0f, 0x00, 0x06, 0x00, 0x0e, 0x00, 0x0e, 0x00, 0x7f, 0xe0, 0x0e, 0x00,
+  0x0c, 0x01, 0xff, 0xf0, 0x06, 0x00, 0x00, 0x07, 0xff, 0xfc, 0x02, 0x00, 0x00, 0x0f, 0x80, 0x3e, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x0f, 0x00, 0x00,
+  0x00, 0x1c, 0x00, 0x07, 0x80, 0x00, 0x00, 0x38, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x70, 0x00, 0x01, 0xc0, 0x00, 0x00, 0x70, 0x00, 0x00, 0xc0, 0x00,
+  0x00, 0x20, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xc0, 0x00, 0x00, 0x00, 0x00, 0xff, 0xe0, 0x00, 0x00,
+  0x00, 0x01, 0xe0, 0xf0, 0x00, 0x00, 0x00, 0x01, 0xc0, 0x78, 0x00, 0x00, 0x00, 0x03, 0x80, 0x38, 0x00, 0x00, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+};
+
+// 'checkmark', 44x44px
+const unsigned char epd_bitmap_checkmark[] PROGMEM = {
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00, 0x07, 0x80, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x0e, 0x00, 0xf0, 0x00, 0x00,
+  0x00, 0x0f, 0x01, 0xe0, 0x00, 0x00, 0x00, 0x0f, 0x83, 0xc0, 0x00, 0x00, 0x00, 0x07, 0xc7, 0x80, 0x00, 0x00, 0x00, 0x03, 0xef, 0x00, 0x00, 0x00,
+  0x00, 0x01, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+};
+
+void IRAM_ATTR handleButtonPress() {
+  unsigned long currentTime = millis();  // Get current time
+
+  // Debounce: If the current press is too close to the last one, ignore it
+  if (currentTime - lastPressTime > 50) {
+    pressCount++;  // Count the button press
+
+    // Check if this is the second press within the double-press interval
+    if (pressCount == 2 && (currentTime - lastPressTime <= doublePressInterval)) {
+      doublePressDetected = true;  // Double press detected
+      pressCount = 0;              // Reset counter
+    }
+
+    lastPressTime = currentTime;  // Update the time of the last press
+  }
+}
+
+// Function to switch the boot partition to OTA1
+void setBootPartitionToOTA0() {
+  const esp_partition_t *ota0_partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_0, NULL);
+
+  if (ota0_partition) {
+    // Set OTA1 as new boot partition
+    esp_ota_set_boot_partition(ota0_partition);
+    Serial.println("Boot partition changed to OTA0. Restarting...");
+
+    // Restart to boot from the new partition
+    esp_restart();
+  } else {
+    Serial.println("OTA1 partition not found!");
+  }
+}
+
+void setupDisplay() {
+  displayEnabled = display.begin(SSD1306_SWITCHCAPVCC, 0x3D);
+  if (displayEnabled) {
+    display.display();
+    delay(100);
+    display.clearDisplay();
+  }
+}
+
+void displayStatusBar(int progress) {
+  display.clearDisplay();
+  display.setCursor(24, 8);
+  display.println("Sketch wird");
+  display.setCursor(22, 22);
+  display.println("hochgeladen!");
+
+  display.fillRect(0, SCREEN_HEIGHT - 24, SCREEN_WIDTH - 4, 8, BLACK);  // Clear status bar area
+  display.drawRect(0, SCREEN_HEIGHT - 24, SCREEN_WIDTH - 4, 8, WHITE);  // Draw border
+  int filledWidth = (progress * SCREEN_WIDTH - 4) / 100;                // Calculate progress width
+  display.fillRect(1, SCREEN_HEIGHT - 23, filledWidth - 4, 6, WHITE);   // Fill progress bar
+
+  display.setCursor((SCREEN_WIDTH / 2) - 12, SCREEN_HEIGHT - 10);
+  display.setTextSize(1);
+  display.setTextColor(WHITE, BLACK);
+  display.print(progress);
+  display.println(" %");
+  display.display();
+}
+
+void displayWelcomeScreen() {
+  display.clearDisplay();
+
+  // Draw WiFi symbol
+  display.drawBitmap(0, 12, epd_bitmap_wifi, 44, 44, WHITE);
+
+  // Display SSID text
+  display.setCursor(40, 13);
+  display.setTextSize(1);
+  display.setTextColor(WHITE, BLACK);
+  display.println("Verbinde dich");  // "Connect"
+  display.setCursor(60, 27);
+  display.println("mit:");  // "with"
+
+  // Display SSID
+  display.setCursor(40, 43);
+  display.setTextSize(1);  // Larger text for SSID
+  display.print(ssid);
+
+  display.display();
+}
+
+void displaySuccessScreen() {
+  display.clearDisplay();
+
+  // Draw WiFi symbol
+  display.drawBitmap(0, 12, epd_bitmap_checkmark, 44, 44, WHITE);
+
+  // Display SSID text
+  display.setCursor(48, 22);
+  display.setTextSize(1);
+  display.setTextColor(WHITE, BLACK);
+  display.println("Erfolgreich");  // "Successfully"
+  display.setCursor(48, 36);
+  display.println("hochgeladen!");  // "uploaded!"
+
+  display.display();
+}
+
+void wipeDisplay() {
+  display.clearDisplay();
+  display.println("");
+  display.display();
+}
+
+void setupWiFi() {
+  WiFi.macAddress(mac);
+  char macLastFour[5];
+  snprintf(macLastFour, sizeof(macLastFour), "%02X%02X", mac[4], mac[5]);
+  ssid = "senseBox:" + String(macLastFour);
+
+  // Define the IP address, gateway, and subnet mask
+  IPAddress local_IP(192, 168, 1, 1);  // The new IP address
+  IPAddress gateway(192, 168, 1, 1);   // Gateway address (can be the same as the AP's IP)
+  IPAddress subnet(255, 255, 255, 0);  // Subnet mask
+
+  // Set the IP address, gateway, and subnet mask of the access point
+  WiFi.softAPConfig(local_IP, gateway, subnet);
+
+  // Start the access point
+  WiFi.softAP(ssid.c_str());
+}
+
+void setupOTA() {
+  // Handle updating process
+  server.on(
+    "/sketch", HTTP_POST,
+    []() {
+      server.sendHeader("Connection", "close");
+      server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
+      ESP.restart();
+    },
+    []() {
+      HTTPUpload &upload = server.upload();
+
+      if (upload.status == UPLOAD_FILE_START) {
+        Serial.setDebugOutput(true);
+        size_t fsize = UPDATE_SIZE_UNKNOWN;
+        if (server.clientContentLength() > 0) {
+          fsize = server.clientContentLength();
+        }
+        Serial.printf("Receiving Update: %s, Size: %d\n", upload.filename.c_str(), fsize);
+
+        Serial.printf("Update: %s\n", upload.filename.c_str());
+        if (!Update.begin(fsize)) {  //start with max available size
+          Update.printError(Serial);
+        }
+      } else if (upload.status == UPLOAD_FILE_WRITE) {
+        /* flashing firmware to ESP*/
+        if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
+          Update.printError(Serial);
+        } else {
+          int progress = (Update.progress() * 100) / Update.size();
+          displayStatusBar(progress);  // Update progress on status bar
+        }
+      } else if (upload.status == UPLOAD_FILE_END) {
+        if (Update.end(true)) {  //true to set the size to the current progress
+          displaySuccessScreen();
+          delay(3000);
+          wipeDisplay();
+        } else {
+          Update.printError(Serial);
+        }
+        Serial.setDebugOutput(false);
+      }
+      yield();
+    }
+  );
+}
+
+void setup() {
+  // Start Serial communication
+  Serial.begin(115200);
+  rgb_led_1.begin();
+  rgb_led_1.setBrightness(30);
+  rgb_led_1.setPixelColor(0, rgb_led_1.Color(51, 51, 255));
+  rgb_led_1.show();
+
+  // Configure button pin as input
+  pinMode(BUTTON_PIN, INPUT_PULLUP);
+
+  // Interrupt for the button
+  attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), handleButtonPress, FALLING);
+
+#ifdef DISPLAY_ENABLED
+  setupDisplay();
+#endif
+  setupWiFi();
+  // Set the ESP32 as an access point
+  setupOTA();
+  server.begin();
+}
+
+void loop() {
+  // Handle client requests
+  server.handleClient();
+
+#ifdef DISPLAY_ENABLED
+  displayWelcomeScreen();
+#endif
+
+  if (doublePressDetected) {
+    Serial.println("Doppeldruck erkannt!");  // "Double press detected!"
+    setBootPartitionToOTA0();
+#ifdef DISPLAY_ENABLED
+    display.setCursor(0, 0);
+    display.setTextSize(1);
+    display.setTextColor(WHITE, BLACK);
+    display.println("");
+    display.display();
+    delay(50);
+#endif
+    // Restart to boot from the new partition
+    esp_restart();
+  }
+}
diff --git a/variants/sensebox_eye/variant.cpp b/variants/sensebox_eye/variant.cpp
index 42269d11357..c802c614cc1 100644
--- a/variants/sensebox_eye/variant.cpp
+++ b/variants/sensebox_eye/variant.cpp
@@ -26,9 +26,25 @@
 #include "pins_arduino.h"
 #include "driver/rmt_tx.h"
 #include "esp_log.h"
+#include "esp_partition.h"
+#include "esp_system.h"
+#include "esp_ota_ops.h"
 
 extern "C" {
 
+void blinkLED(uint8_t color[3], rmt_channel_handle_t led_chan, rmt_encoder_handle_t ws2812_encoder, rmt_transmit_config_t tx_config) {
+  ESP_ERROR_CHECK(rmt_transmit(led_chan, ws2812_encoder, color, sizeof(color), &tx_config));
+  rmt_tx_wait_all_done(led_chan, portMAX_DELAY);
+
+  // Wait a moment
+  delay(50);
+
+  // Turn LED off
+  uint8_t pixel_off[3] = { 0x00, 0x00, 0x00 };
+  ESP_ERROR_CHECK(rmt_transmit(led_chan, ws2812_encoder, pixel_off, sizeof(pixel_off), &tx_config));
+  rmt_tx_wait_all_done(led_chan, portMAX_DELAY);
+}
+
 void initVariant(void) {
   rmt_channel_handle_t led_chan = NULL;
   rmt_tx_channel_config_t tx_chan_config = {};
@@ -52,20 +68,49 @@ void initVariant(void) {
 
   ESP_ERROR_CHECK(rmt_enable(led_chan));
 
-  // WS2812 GRB data (green pixel)
-  uint8_t pixel[3] = { 0x10, 0x00, 0x00 }; // green
   rmt_transmit_config_t tx_config = {
     .loop_count = 0
   };
-  ESP_ERROR_CHECK(rmt_transmit(led_chan, ws2812_encoder, pixel, sizeof(pixel), &tx_config));
-  rmt_tx_wait_all_done(led_chan, portMAX_DELAY);
 
-  // Wait a moment
-  delay(50);
+  uint8_t pixel[3] = { 0x10, 0x00, 0x00 }; // green
+  blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
 
-  // Turn LED off
-  uint8_t pixel_off[3] = { 0x00, 0x00, 0x00 };
-  ESP_ERROR_CHECK(rmt_transmit(led_chan, ws2812_encoder, pixel_off, sizeof(pixel_off), &tx_config));
-  rmt_tx_wait_all_done(led_chan, portMAX_DELAY);
+  // define button pin
+  pinMode(0, INPUT_PULLUP);
+
+  // keep button pressed
+  unsigned long pressStartTime = 0;
+  bool buttonPressed = false;
+
+  // Wait 3.5 seconds for the button to be pressed
+  unsigned long startTime = millis();
+
+  // Check if button is pressed
+  while (millis() - startTime < 3500) {
+    if (digitalRead(0) == LOW) {
+      if (!buttonPressed) {
+        // The button was pressed
+        buttonPressed = true;
+      }
+    } else if (buttonPressed) {
+      // When the button is pressed and then released, boot into the OTA1 partition
+      const esp_partition_t *ota1_partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, NULL);
+
+      if (ota1_partition) {
+        esp_err_t err = esp_ota_set_boot_partition(ota1_partition);
+        if (err == ESP_OK) {
+          uint8_t pixel[3] = { 0x00, 0x00, 0x10 }; // blue
+          blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
+          esp_restart();  // restart, to boot OTA1 partition
+        } else {
+          uint8_t pixel[3] = { 0x00, 0x10, 0x00 }; // red
+          blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
+          ESP_LOGE("OTA", "Error setting OTA1 partition: %s", esp_err_to_name(err));
+        }
+      }
+      // Abort after releasing the button
+      break;
+    }
+  }
 }
 }

From f330585717ee9758b15a0ae8fe939967937a4539 Mon Sep 17 00:00:00 2001
From: Paula Scharf <paulascharf@gmx.de>
Date: Tue, 15 Jul 2025 11:14:26 +0200
Subject: [PATCH 059/105] feat(board): update PID

---
 variants/sensebox_eye/pins_arduino.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/variants/sensebox_eye/pins_arduino.h b/variants/sensebox_eye/pins_arduino.h
index 583cb38283e..99984dbc6a4 100644
--- a/variants/sensebox_eye/pins_arduino.h
+++ b/variants/sensebox_eye/pins_arduino.h
@@ -4,7 +4,7 @@
 #include <stdint.h>
 
 #define USB_VID          0x303A
-#define USB_PID          0x81B8
+#define USB_PID          0x82D1
 #define USB_MANUFACTURER "senseBox"
 #define USB_PRODUCT      "Eye ESP32S3"
 #define USB_SERIAL       ""  // Empty string for MAC address

From cdf606af5f4424a2ea568734be290e00d906c538 Mon Sep 17 00:00:00 2001
From: Paula Scharf <paulascharf@gmx.de>
Date: Tue, 15 Jul 2025 16:45:03 +0200
Subject: [PATCH 060/105] feat(board): updated tinyuf2 bins

---
 variants/sensebox_eye/bootloader-tinyuf2.bin | Bin 22352 -> 23120 bytes
 variants/sensebox_eye/tinyuf2.bin            | Bin 186912 -> 193056 bytes
 2 files changed, 0 insertions(+), 0 deletions(-)

diff --git a/variants/sensebox_eye/bootloader-tinyuf2.bin b/variants/sensebox_eye/bootloader-tinyuf2.bin
index c7676c718f2383a78785da38dcffde52ca67eab0..7a83be05436d3ea295c2a06e4ffd5a814c145f42 100644
GIT binary patch
diff --git a/variants/sensebox_eye/tinyuf2.bin b/variants/sensebox_eye/tinyuf2.bin
index 6b0fb1bcd0417ce9175fc75bf09b49f7516ab078..67c00aa39f0644371b2aeac5b2cbd898970a4481 100644
GIT binary patch

From 439bbb8391f6cf8db626cf1190ee3a36ec3479f1 Mon Sep 17 00:00:00 2001
From: Paula Scharf <paulascharf@gmx.de>
Date: Thu, 17 Jul 2025 16:15:10 +0200
Subject: [PATCH 061/105] feat(board): use additional button for APOTA

---
 variants/sensebox_eye/variant.cpp | 50 +++++++++++--------------------
 1 file changed, 17 insertions(+), 33 deletions(-)

diff --git a/variants/sensebox_eye/variant.cpp b/variants/sensebox_eye/variant.cpp
index c802c614cc1..1eef839494e 100644
--- a/variants/sensebox_eye/variant.cpp
+++ b/variants/sensebox_eye/variant.cpp
@@ -72,45 +72,29 @@ void initVariant(void) {
     .loop_count = 0
   };
 
-  uint8_t pixel[3] = { 0x10, 0x00, 0x00 }; // green
-  blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
-
   // define button pin
-  pinMode(0, INPUT_PULLUP);
-
-  // keep button pressed
-  unsigned long pressStartTime = 0;
-  bool buttonPressed = false;
-
-  // Wait 3.5 seconds for the button to be pressed
-  unsigned long startTime = millis();
+  pinMode(47, INPUT_PULLUP);
 
   // Check if button is pressed
-  while (millis() - startTime < 3500) {
-    if (digitalRead(0) == LOW) {
-      if (!buttonPressed) {
-        // The button was pressed
-        buttonPressed = true;
-      }
-    } else if (buttonPressed) {
-      // When the button is pressed and then released, boot into the OTA1 partition
-      const esp_partition_t *ota1_partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, NULL);
+  if (digitalRead(47) == LOW) {
+    // When the button is pressed and then released, boot into the OTA1 partition
+    const esp_partition_t *ota1_partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, NULL);
 
-      if (ota1_partition) {
-        esp_err_t err = esp_ota_set_boot_partition(ota1_partition);
-        if (err == ESP_OK) {
-          uint8_t pixel[3] = { 0x00, 0x00, 0x10 }; // blue
-          blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
-          esp_restart();  // restart, to boot OTA1 partition
-        } else {
-          uint8_t pixel[3] = { 0x00, 0x10, 0x00 }; // red
-          blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
-          ESP_LOGE("OTA", "Error setting OTA1 partition: %s", esp_err_to_name(err));
-        }
+    if (ota1_partition) {
+      esp_err_t err = esp_ota_set_boot_partition(ota1_partition);
+      if (err == ESP_OK) {
+        uint8_t pixel[3] = { 0x00, 0x00, 0x10 }; // blue
+        blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
+        esp_restart();  // restart, to boot OTA1 partition
+      } else {
+        uint8_t pixel[3] = { 0x00, 0x10, 0x00 }; // red
+        blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
+        ESP_LOGE("OTA", "Error setting OTA1 partition: %s", esp_err_to_name(err));
       }
-      // Abort after releasing the button
-      break;
     }
+  } else {
+    uint8_t pixel[3] = { 0x10, 0x00, 0x00 }; // green
+    blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
   }
 }
 }

From cf0a58908de30271845b036c17ef42ed2436d466 Mon Sep 17 00:00:00 2001
From: Paula Scharf <paulascharf@gmx.de>
Date: Fri, 18 Jul 2025 13:47:24 +0200
Subject: [PATCH 062/105] feat(board): remove APOTA

---
 boards.txt                        |   2 +-
 variants/sensebox_eye/APOTA.bin   | Bin 976464 -> 0 bytes
 variants/sensebox_eye/APOTA.ino   | 287 ------------------------------
 variants/sensebox_eye/variant.cpp |  54 +-----
 4 files changed, 3 insertions(+), 340 deletions(-)
 delete mode 100644 variants/sensebox_eye/APOTA.bin
 delete mode 100644 variants/sensebox_eye/APOTA.ino

diff --git a/boards.txt b/boards.txt
index faa7f94a994..2363fe2a63b 100644
--- a/boards.txt
+++ b/boards.txt
@@ -41448,7 +41448,7 @@ sensebox_eye.menu.PartitionScheme.tinyuf2=TinyUF2 Compatibility (2MB APP/12MB FF
 sensebox_eye.menu.PartitionScheme.tinyuf2.build.custom_bootloader=bootloader_tinyuf2
 sensebox_eye.menu.PartitionScheme.tinyuf2.build.custom_partitions=partitions_tinyuf2
 sensebox_eye.menu.PartitionScheme.tinyuf2.upload.maximum_size=2097152
-sensebox_eye.menu.PartitionScheme.tinyuf2.upload.extra_flags=0x410000 "{runtime.platform.path}/variants/{build.variant}/tinyuf2.bin" 0x210000 "{runtime.platform.path}/variants/{build.variant}/APOTA.bin"
+sensebox_eye.menu.PartitionScheme.tinyuf2.upload.extra_flags=0x410000 "{runtime.platform.path}/variants/{build.variant}/tinyuf2.bin"
 sensebox_eye.menu.PartitionScheme.gen4esp32scheme4=Huge App (16MB APP)
 sensebox_eye.menu.PartitionScheme.gen4esp32scheme4.build.custom_partitions=gen4esp32_16MBapp
 sensebox_eye.menu.PartitionScheme.gen4esp32scheme4.upload.maximum_size=16646144
diff --git a/variants/sensebox_eye/APOTA.bin b/variants/sensebox_eye/APOTA.bin
deleted file mode 100644
index 571336d378a9aaee97e074142d0e73cad85eacc9..0000000000000000000000000000000000000000
GIT binary patch
diff --git a/variants/sensebox_eye/APOTA.ino b/variants/sensebox_eye/APOTA.ino
deleted file mode 100644
index afb741499b2..00000000000
--- a/variants/sensebox_eye/APOTA.ino
+++ /dev/null
@@ -1,287 +0,0 @@
-// APOTA is a arduino fallback sketch that is written to OTA1_Partition. 
-// APOTA opens an access point which waits to receive a .binfile on /sketch. 
-// After succesful upload, the file is written to OTA0_Partition and the microcontroller reboots to the newly uploaded sketch.
-
-#define DISPLAY_ENABLED
-
-#include <WiFi.h>
-#include <WebServer.h>
-#include <ESPmDNS.h>
-#include <WiFiAP.h>
-#include <Update.h>
-#include <Wire.h>
-#ifdef DISPLAY_ENABLED
-#define SCREEN_WIDTH  128
-#define SCREEN_HEIGHT 64
-#define OLED_RESET    -1
-#include <Adafruit_GFX.h>
-#include <Adafruit_SSD1306.h>
-Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
-#include <Adafruit_NeoPixel.h>
-Adafruit_NeoPixel rgb_led_1 = Adafruit_NeoPixel(1, 1, NEO_GRB + NEO_KHZ800);
-
-#endif
-#include "esp_partition.h"
-#include "esp_ota_ops.h"
-#include "esp_system.h"
-
-String ssid;
-uint8_t mac[6];
-
-// Create an instance of the server
-WebServer server(80);
-bool displayEnabled;
-
-const int BUTTON_PIN = 0;                       // GPIO for the button
-volatile unsigned long lastPressTime = 0;       // Time of last button press
-volatile bool doublePressDetected = false;      // Flag for double press
-const unsigned long doublePressInterval = 500;  // Max. time (in ms) between two presses for double press
-volatile int pressCount = 0;                    // Counts the button presses
-
-const unsigned char epd_bitmap_wifi[] PROGMEM = {
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-  0x00, 0x00, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x01, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x07, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x1f, 0xe0, 0xff, 0x00, 0x00,
-  0x00, 0x3f, 0x00, 0x0f, 0x80, 0x00, 0x00, 0x7c, 0x00, 0x03, 0xe0, 0x00, 0x00, 0xf0, 0x00, 0x01, 0xf0, 0x00, 0x01, 0xe0, 0x00, 0x00, 0x78, 0x00,
-  0x03, 0xc0, 0x00, 0x00, 0x38, 0x00, 0x07, 0x80, 0x00, 0x00, 0x1c, 0x00, 0x0f, 0x00, 0x06, 0x00, 0x0e, 0x00, 0x0e, 0x00, 0x7f, 0xe0, 0x0e, 0x00,
-  0x0c, 0x01, 0xff, 0xf0, 0x06, 0x00, 0x00, 0x07, 0xff, 0xfc, 0x02, 0x00, 0x00, 0x0f, 0x80, 0x3e, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x0f, 0x00, 0x00,
-  0x00, 0x1c, 0x00, 0x07, 0x80, 0x00, 0x00, 0x38, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x70, 0x00, 0x01, 0xc0, 0x00, 0x00, 0x70, 0x00, 0x00, 0xc0, 0x00,
-  0x00, 0x20, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xc0, 0x00, 0x00, 0x00, 0x00, 0xff, 0xe0, 0x00, 0x00,
-  0x00, 0x01, 0xe0, 0xf0, 0x00, 0x00, 0x00, 0x01, 0xc0, 0x78, 0x00, 0x00, 0x00, 0x03, 0x80, 0x38, 0x00, 0x00, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
-};
-
-// 'checkmark', 44x44px
-const unsigned char epd_bitmap_checkmark[] PROGMEM = {
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00, 0x07, 0x80, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x0e, 0x00, 0xf0, 0x00, 0x00,
-  0x00, 0x0f, 0x01, 0xe0, 0x00, 0x00, 0x00, 0x0f, 0x83, 0xc0, 0x00, 0x00, 0x00, 0x07, 0xc7, 0x80, 0x00, 0x00, 0x00, 0x03, 0xef, 0x00, 0x00, 0x00,
-  0x00, 0x01, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
-};
-
-void IRAM_ATTR handleButtonPress() {
-  unsigned long currentTime = millis();  // Get current time
-
-  // Debounce: If the current press is too close to the last one, ignore it
-  if (currentTime - lastPressTime > 50) {
-    pressCount++;  // Count the button press
-
-    // Check if this is the second press within the double-press interval
-    if (pressCount == 2 && (currentTime - lastPressTime <= doublePressInterval)) {
-      doublePressDetected = true;  // Double press detected
-      pressCount = 0;              // Reset counter
-    }
-
-    lastPressTime = currentTime;  // Update the time of the last press
-  }
-}
-
-// Function to switch the boot partition to OTA1
-void setBootPartitionToOTA0() {
-  const esp_partition_t *ota0_partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_0, NULL);
-
-  if (ota0_partition) {
-    // Set OTA1 as new boot partition
-    esp_ota_set_boot_partition(ota0_partition);
-    Serial.println("Boot partition changed to OTA0. Restarting...");
-
-    // Restart to boot from the new partition
-    esp_restart();
-  } else {
-    Serial.println("OTA1 partition not found!");
-  }
-}
-
-void setupDisplay() {
-  displayEnabled = display.begin(SSD1306_SWITCHCAPVCC, 0x3D);
-  if (displayEnabled) {
-    display.display();
-    delay(100);
-    display.clearDisplay();
-  }
-}
-
-void displayStatusBar(int progress) {
-  display.clearDisplay();
-  display.setCursor(24, 8);
-  display.println("Sketch wird");
-  display.setCursor(22, 22);
-  display.println("hochgeladen!");
-
-  display.fillRect(0, SCREEN_HEIGHT - 24, SCREEN_WIDTH - 4, 8, BLACK);  // Clear status bar area
-  display.drawRect(0, SCREEN_HEIGHT - 24, SCREEN_WIDTH - 4, 8, WHITE);  // Draw border
-  int filledWidth = (progress * SCREEN_WIDTH - 4) / 100;                // Calculate progress width
-  display.fillRect(1, SCREEN_HEIGHT - 23, filledWidth - 4, 6, WHITE);   // Fill progress bar
-
-  display.setCursor((SCREEN_WIDTH / 2) - 12, SCREEN_HEIGHT - 10);
-  display.setTextSize(1);
-  display.setTextColor(WHITE, BLACK);
-  display.print(progress);
-  display.println(" %");
-  display.display();
-}
-
-void displayWelcomeScreen() {
-  display.clearDisplay();
-
-  // Draw WiFi symbol
-  display.drawBitmap(0, 12, epd_bitmap_wifi, 44, 44, WHITE);
-
-  // Display SSID text
-  display.setCursor(40, 13);
-  display.setTextSize(1);
-  display.setTextColor(WHITE, BLACK);
-  display.println("Verbinde dich");  // "Connect"
-  display.setCursor(60, 27);
-  display.println("mit:");  // "with"
-
-  // Display SSID
-  display.setCursor(40, 43);
-  display.setTextSize(1);  // Larger text for SSID
-  display.print(ssid);
-
-  display.display();
-}
-
-void displaySuccessScreen() {
-  display.clearDisplay();
-
-  // Draw WiFi symbol
-  display.drawBitmap(0, 12, epd_bitmap_checkmark, 44, 44, WHITE);
-
-  // Display SSID text
-  display.setCursor(48, 22);
-  display.setTextSize(1);
-  display.setTextColor(WHITE, BLACK);
-  display.println("Erfolgreich");  // "Successfully"
-  display.setCursor(48, 36);
-  display.println("hochgeladen!");  // "uploaded!"
-
-  display.display();
-}
-
-void wipeDisplay() {
-  display.clearDisplay();
-  display.println("");
-  display.display();
-}
-
-void setupWiFi() {
-  WiFi.macAddress(mac);
-  char macLastFour[5];
-  snprintf(macLastFour, sizeof(macLastFour), "%02X%02X", mac[4], mac[5]);
-  ssid = "senseBox:" + String(macLastFour);
-
-  // Define the IP address, gateway, and subnet mask
-  IPAddress local_IP(192, 168, 1, 1);  // The new IP address
-  IPAddress gateway(192, 168, 1, 1);   // Gateway address (can be the same as the AP's IP)
-  IPAddress subnet(255, 255, 255, 0);  // Subnet mask
-
-  // Set the IP address, gateway, and subnet mask of the access point
-  WiFi.softAPConfig(local_IP, gateway, subnet);
-
-  // Start the access point
-  WiFi.softAP(ssid.c_str());
-}
-
-void setupOTA() {
-  // Handle updating process
-  server.on(
-    "/sketch", HTTP_POST,
-    []() {
-      server.sendHeader("Connection", "close");
-      server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
-      ESP.restart();
-    },
-    []() {
-      HTTPUpload &upload = server.upload();
-
-      if (upload.status == UPLOAD_FILE_START) {
-        Serial.setDebugOutput(true);
-        size_t fsize = UPDATE_SIZE_UNKNOWN;
-        if (server.clientContentLength() > 0) {
-          fsize = server.clientContentLength();
-        }
-        Serial.printf("Receiving Update: %s, Size: %d\n", upload.filename.c_str(), fsize);
-
-        Serial.printf("Update: %s\n", upload.filename.c_str());
-        if (!Update.begin(fsize)) {  //start with max available size
-          Update.printError(Serial);
-        }
-      } else if (upload.status == UPLOAD_FILE_WRITE) {
-        /* flashing firmware to ESP*/
-        if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
-          Update.printError(Serial);
-        } else {
-          int progress = (Update.progress() * 100) / Update.size();
-          displayStatusBar(progress);  // Update progress on status bar
-        }
-      } else if (upload.status == UPLOAD_FILE_END) {
-        if (Update.end(true)) {  //true to set the size to the current progress
-          displaySuccessScreen();
-          delay(3000);
-          wipeDisplay();
-        } else {
-          Update.printError(Serial);
-        }
-        Serial.setDebugOutput(false);
-      }
-      yield();
-    }
-  );
-}
-
-void setup() {
-  // Start Serial communication
-  Serial.begin(115200);
-  rgb_led_1.begin();
-  rgb_led_1.setBrightness(30);
-  rgb_led_1.setPixelColor(0, rgb_led_1.Color(51, 51, 255));
-  rgb_led_1.show();
-
-  // Configure button pin as input
-  pinMode(BUTTON_PIN, INPUT_PULLUP);
-
-  // Interrupt for the button
-  attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), handleButtonPress, FALLING);
-
-#ifdef DISPLAY_ENABLED
-  setupDisplay();
-#endif
-  setupWiFi();
-  // Set the ESP32 as an access point
-  setupOTA();
-  server.begin();
-}
-
-void loop() {
-  // Handle client requests
-  server.handleClient();
-
-#ifdef DISPLAY_ENABLED
-  displayWelcomeScreen();
-#endif
-
-  if (doublePressDetected) {
-    Serial.println("Doppeldruck erkannt!");  // "Double press detected!"
-    setBootPartitionToOTA0();
-#ifdef DISPLAY_ENABLED
-    display.setCursor(0, 0);
-    display.setTextSize(1);
-    display.setTextColor(WHITE, BLACK);
-    display.println("");
-    display.display();
-    delay(50);
-#endif
-    // Restart to boot from the new partition
-    esp_restart();
-  }
-}
diff --git a/variants/sensebox_eye/variant.cpp b/variants/sensebox_eye/variant.cpp
index 1eef839494e..d8a37f58758 100644
--- a/variants/sensebox_eye/variant.cpp
+++ b/variants/sensebox_eye/variant.cpp
@@ -1,34 +1,6 @@
-/*
- * The MIT License (MIT)
- *
- * Copyright (c) 2021 Ha Thach (tinyusb.org) for Adafruit Industries
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
 #include "esp32-hal-gpio.h"
 #include "pins_arduino.h"
 #include "driver/rmt_tx.h"
-#include "esp_log.h"
-#include "esp_partition.h"
-#include "esp_system.h"
-#include "esp_ota_ops.h"
 
 extern "C" {
 
@@ -72,29 +44,7 @@ void initVariant(void) {
     .loop_count = 0
   };
 
-  // define button pin
-  pinMode(47, INPUT_PULLUP);
-
-  // Check if button is pressed
-  if (digitalRead(47) == LOW) {
-    // When the button is pressed and then released, boot into the OTA1 partition
-    const esp_partition_t *ota1_partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, NULL);
-
-    if (ota1_partition) {
-      esp_err_t err = esp_ota_set_boot_partition(ota1_partition);
-      if (err == ESP_OK) {
-        uint8_t pixel[3] = { 0x00, 0x00, 0x10 }; // blue
-        blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
-        esp_restart();  // restart, to boot OTA1 partition
-      } else {
-        uint8_t pixel[3] = { 0x00, 0x10, 0x00 }; // red
-        blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
-        ESP_LOGE("OTA", "Error setting OTA1 partition: %s", esp_err_to_name(err));
-      }
-    }
-  } else {
-    uint8_t pixel[3] = { 0x10, 0x00, 0x00 }; // green
-    blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
-  }
+  uint8_t pixel[3] = { 0x10, 0x00, 0x00 }; // green
+  blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
 }
 }

From 28e90766018ffe46fef16526487ba2a905052e53 Mon Sep 17 00:00:00 2001
From: Paula Scharf <paulascharf@gmx.de>
Date: Sun, 20 Jul 2025 22:53:35 +0200
Subject: [PATCH 063/105] feat(board): build name uppercase

---
 boards.txt | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/boards.txt b/boards.txt
index 2363fe2a63b..07c34649ea0 100644
--- a/boards.txt
+++ b/boards.txt
@@ -41343,7 +41343,7 @@ sensebox_eye.build.target=esp32s3
 sensebox_eye.build.mcu=esp32s3
 sensebox_eye.build.core=esp32
 sensebox_eye.build.variant=sensebox_eye
-sensebox_eye.build.board=sensebox_eye
+sensebox_eye.build.board=SENSEBOX_EYE
 
 sensebox_eye.build.usb_mode=0
 sensebox_eye.build.cdc_on_boot=1

From 349b11d2d86b37f3e6613cf25ea490b02c9fdecf Mon Sep 17 00:00:00 2001
From: Paula Scharf <paulascharf@gmx.de>
Date: Sun, 20 Jul 2025 23:00:05 +0200
Subject: [PATCH 064/105] feat(board): name tag lowercase

---
 boards.txt | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/boards.txt b/boards.txt
index 07c34649ea0..1043ece4445 100644
--- a/boards.txt
+++ b/boards.txt
@@ -41313,12 +41313,12 @@ sensebox_mcu_esp32s2.menu.EraseFlash.all.upload.erase_cmd=-e
 # senseBox Eye
 
 sensebox_eye.name=senseBox Eye
-senseBox_eye.vid.0=0x303A
-senseBox_eye.pid.0=0x82D1
-senseBox_eye.vid.1=0x303A
-senseBox_eye.pid.1=0x82D2
-senseBox_eye.vid.2=0x303A
-senseBox_eye.pid.2=0x82D3
+sensebox_eye.vid.0=0x303A
+sensebox_eye.pid.0=0x82D1
+sensebox_eye.vid.1=0x303A
+sensebox_eye.pid.1=0x82D2
+sensebox_eye.vid.2=0x303A
+sensebox_eye.pid.2=0x82D3
 
 sensebox_eye.bootloader.tool=esptool_py
 sensebox_eye.bootloader.tool.default=esptool_py

From cb3329be60f7cb446faa4aaa4572975ffdabab42 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Proch=C3=A1zka?=
 <90197375+P-R-O-C-H-Y@users.noreply.github.com>
Date: Mon, 21 Jul 2025 14:47:21 +0200
Subject: [PATCH 065/105] feat(zigbee): Add callback option for default
 response message (#11613)

* feat(zigbee): Add cb option for default response message

* fix(example): Add timeout and fix spelling

* feat(zigbee): Add global default response cb option

* fix(example): Use task for measure and sleep

* fix(zigbee): Remove debug logs

* ci(pre-commit): Apply automatic fixes

* fix(example): Add retry and fix typo

* ci(pre-commit): Apply automatic fixes

---------

Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 .../Zigbee_Temp_Hum_Sensor_Sleepy.ino         | 81 ++++++++++++++++---
 libraries/Zigbee/keywords.txt                 |  2 +
 libraries/Zigbee/src/Zigbee.h                 |  3 +
 libraries/Zigbee/src/ZigbeeCore.cpp           |  7 ++
 libraries/Zigbee/src/ZigbeeCore.h             | 12 +++
 libraries/Zigbee/src/ZigbeeEP.cpp             | 12 ++-
 libraries/Zigbee/src/ZigbeeEP.h               | 15 +++-
 libraries/Zigbee/src/ZigbeeHandlers.cpp       | 10 +++
 libraries/Zigbee/src/ZigbeeTypes.h            | 30 +++++++
 9 files changed, 158 insertions(+), 14 deletions(-)
 create mode 100644 libraries/Zigbee/src/ZigbeeTypes.h

diff --git a/libraries/Zigbee/examples/Zigbee_Temp_Hum_Sensor_Sleepy/Zigbee_Temp_Hum_Sensor_Sleepy.ino b/libraries/Zigbee/examples/Zigbee_Temp_Hum_Sensor_Sleepy/Zigbee_Temp_Hum_Sensor_Sleepy.ino
index e9d08d32175..54c085fbfea 100644
--- a/libraries/Zigbee/examples/Zigbee_Temp_Hum_Sensor_Sleepy/Zigbee_Temp_Hum_Sensor_Sleepy.ino
+++ b/libraries/Zigbee/examples/Zigbee_Temp_Hum_Sensor_Sleepy/Zigbee_Temp_Hum_Sensor_Sleepy.ino
@@ -32,18 +32,49 @@
 
 #include "Zigbee.h"
 
+#define USE_GLOBAL_ON_RESPONSE_CALLBACK 1  // Set to 0 to use local callback specified directly for the endpoint.
+
 /* Zigbee temperature + humidity sensor configuration */
 #define TEMP_SENSOR_ENDPOINT_NUMBER 10
 
 #define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */
 #define TIME_TO_SLEEP  55         /* Sleep for 55s will + 5s delay for establishing connection => data reported every 1 minute */
+#define REPORT_TIMEOUT 1000       /* Timeout for response from coordinator in ms */
 
 uint8_t button = BOOT_PIN;
 
 ZigbeeTempSensor zbTempSensor = ZigbeeTempSensor(TEMP_SENSOR_ENDPOINT_NUMBER);
 
+uint8_t dataToSend = 2;  // Temperature and humidity values are reported in same endpoint, so 2 values are reported
+bool resend = false;
+
+/************************ Callbacks *****************************/
+#if USE_GLOBAL_ON_RESPONSE_CALLBACK
+void onGlobalResponse(zb_cmd_type_t command, esp_zb_zcl_status_t status, uint8_t endpoint, uint16_t cluster) {
+  Serial.printf("Global response command: %d, status: %s, endpoint: %d, cluster: 0x%04x\r\n", command, esp_zb_zcl_status_to_name(status), endpoint, cluster);
+  if ((command == ZB_CMD_REPORT_ATTRIBUTE) && (endpoint == TEMP_SENSOR_ENDPOINT_NUMBER)) {
+    switch (status) {
+      case ESP_ZB_ZCL_STATUS_SUCCESS: dataToSend--; break;
+      case ESP_ZB_ZCL_STATUS_FAIL:    resend = true; break;
+      default:                        break;  // add more statuses like ESP_ZB_ZCL_STATUS_INVALID_VALUE, ESP_ZB_ZCL_STATUS_TIMEOUT etc.
+    }
+  }
+}
+#else
+void onResponse(zb_cmd_type_t command, esp_zb_zcl_status_t status) {
+  Serial.printf("Response command: %d, status: %s\r\n", command, esp_zb_zcl_status_to_name(status));
+  if (command == ZB_CMD_REPORT_ATTRIBUTE) {
+    switch (status) {
+      case ESP_ZB_ZCL_STATUS_SUCCESS: dataToSend--; break;
+      case ESP_ZB_ZCL_STATUS_FAIL:    resend = true; break;
+      default:                        break;  // add more statuses like ESP_ZB_ZCL_STATUS_INVALID_VALUE, ESP_ZB_ZCL_STATUS_TIMEOUT etc.
+    }
+  }
+}
+#endif
+
 /************************ Temp sensor *****************************/
-void meausureAndSleep() {
+static void meausureAndSleep(void *arg) {
   // Measure temperature sensor value
   float temperature = temperatureRead();
 
@@ -55,13 +86,35 @@ void meausureAndSleep() {
   zbTempSensor.setHumidity(humidity);
 
   // Report temperature and humidity values
-  zbTempSensor.report();
+  zbTempSensor.report();  // reports temperature and humidity values (if humidity sensor is not added, only temperature is reported)
   Serial.printf("Reported temperature: %.2f°C, Humidity: %.2f%%\r\n", temperature, humidity);
 
-  // Add small delay to allow the data to be sent before going to sleep
-  delay(100);
+  unsigned long startTime = millis();
+  const unsigned long timeout = REPORT_TIMEOUT;
+
+  Serial.printf("Waiting for data report to be confirmed \r\n");
+  // Wait until data was successfully sent
+  int tries = 0;
+  const int maxTries = 3;
+  while (dataToSend != 0 && tries < maxTries) {
+    if (resend) {
+      Serial.println("Resending data on failure!");
+      resend = false;
+      dataToSend = 2;
+      zbTempSensor.report();  // report again
+    }
+    if (millis() - startTime >= timeout) {
+      Serial.println("\nReport timeout! Report Again");
+      dataToSend = 2;
+      zbTempSensor.report();  // report again
+      startTime = millis();
+      tries++;
+    }
+    Serial.printf(".");
+    delay(50);  // 50ms delay to avoid busy-waiting
+  }
 
-  // Put device to deep sleep
+  // Put device to deep sleep after data was sent successfully or timeout
   Serial.println("Going to sleep now");
   esp_deep_sleep_start();
 }
@@ -92,6 +145,16 @@ void setup() {
   // Add humidity cluster to the temperature sensor device with min, max and tolerance values
   zbTempSensor.addHumiditySensor(0, 100, 1);
 
+  // Set callback for default response to handle status of reported data, there are 2 options.
+
+#if USE_GLOBAL_ON_RESPONSE_CALLBACK
+  // Global callback for all endpoints with more params to determine the endpoint and cluster in the callback function.
+  Zigbee.onGlobalDefaultResponse(onGlobalResponse);
+#else
+  // Callback specified for endpoint
+  zbTempSensor.onDefaultResponse(onResponse);
+#endif
+
   // Add endpoint to Zigbee Core
   Zigbee.addEndpoint(&zbTempSensor);
 
@@ -117,8 +180,8 @@ void setup() {
   Serial.println();
   Serial.println("Successfully connected to Zigbee network");
 
-  // Delay approx 1s (may be adjusted) to allow establishing proper connection with coordinator, needed for sleepy devices
-  delay(1000);
+  // Start Temperature sensor reading task
+  xTaskCreate(meausureAndSleep, "temp_sensor_update", 2048, NULL, 10, NULL);
 }
 
 void loop() {
@@ -141,7 +204,5 @@ void loop() {
       }
     }
   }
-
-  // Call the function to measure temperature and put the device to sleep
-  meausureAndSleep();
+  delay(100);
 }
diff --git a/libraries/Zigbee/keywords.txt b/libraries/Zigbee/keywords.txt
index 23f3af3bf02..68721c1a66f 100644
--- a/libraries/Zigbee/keywords.txt
+++ b/libraries/Zigbee/keywords.txt
@@ -47,6 +47,7 @@ zb_power_source_t	KEYWORD1
 ZigbeeWindowCoveringType	KEYWORD1
 ZigbeeFanMode	KEYWORD1
 ZigbeeFanModeSequence	KEYWORD1
+zb_cmd_type_t	KEYWORD1
 
 #######################################
 # Methods and Functions (KEYWORD2)
@@ -96,6 +97,7 @@ getTime	KEYWORD2
 getTimezone	KEYWORD2
 addOTAClient	KEYWORD2
 clearBoundDevices	KEYWORD2
+onDefaultResponse	KEYWORD2
 
 # ZigbeeLight + ZigbeeColorDimmableLight
 onLightChange	KEYWORD2
diff --git a/libraries/Zigbee/src/Zigbee.h b/libraries/Zigbee/src/Zigbee.h
index 65c9e7f0daa..ab94a163f3e 100644
--- a/libraries/Zigbee/src/Zigbee.h
+++ b/libraries/Zigbee/src/Zigbee.h
@@ -2,6 +2,9 @@
 
 #pragma once
 
+// Common types and functions
+#include "ZigbeeTypes.h"
+
 // Core
 #include "ZigbeeCore.h"
 #include "ZigbeeEP.h"
diff --git a/libraries/Zigbee/src/ZigbeeCore.cpp b/libraries/Zigbee/src/ZigbeeCore.cpp
index c49dedb221f..bf652642ac1 100644
--- a/libraries/Zigbee/src/ZigbeeCore.cpp
+++ b/libraries/Zigbee/src/ZigbeeCore.cpp
@@ -32,6 +32,7 @@ ZigbeeCore::ZigbeeCore() {
   _scan_duration = 3;  // default scan duration
   _rx_on_when_idle = true;
   _debug = false;
+  _global_default_response_cb = nullptr;  // Initialize global callback to nullptr
   if (!lock) {
     lock = xSemaphoreCreateBinary();
     if (lock == NULL) {
@@ -792,6 +793,12 @@ const char *ZigbeeCore::getDeviceTypeString(esp_zb_ha_standard_devices_t deviceI
   }
 }
 
+void ZigbeeCore::callDefaultResponseCallback(zb_cmd_type_t resp_to_cmd, esp_zb_zcl_status_t status, uint8_t endpoint, uint16_t cluster) {
+  if (_global_default_response_cb) {
+    _global_default_response_cb(resp_to_cmd, status, endpoint, cluster);
+  }
+}
+
 ZigbeeCore Zigbee = ZigbeeCore();
 
 #endif  // CONFIG_ZB_ENABLED
diff --git a/libraries/Zigbee/src/ZigbeeCore.h b/libraries/Zigbee/src/ZigbeeCore.h
index 69c91c63ac4..df334e1620d 100644
--- a/libraries/Zigbee/src/ZigbeeCore.h
+++ b/libraries/Zigbee/src/ZigbeeCore.h
@@ -11,6 +11,7 @@
 #include "aps/esp_zigbee_aps.h"
 #include <esp32-hal-log.h>
 #include <list>
+#include "ZigbeeTypes.h"
 #include "ZigbeeEP.h"
 class ZigbeeEP;
 
@@ -103,6 +104,9 @@ class ZigbeeCore {
   SemaphoreHandle_t lock;
   bool _debug;
 
+  // Global default response callback
+  void (*_global_default_response_cb)(zb_cmd_type_t resp_to_cmd, esp_zb_zcl_status_t status, uint8_t endpoint, uint16_t cluster);
+
   bool zigbeeInit(esp_zb_cfg_t *zb_cfg, bool erase_nvs);
   static void scanCompleteCallback(esp_zb_zdp_status_t zdo_status, uint8_t count, esp_zb_network_descriptor_t *nwk_descriptor);
   const char *getDeviceTypeString(esp_zb_ha_standard_devices_t deviceId);
@@ -176,6 +180,14 @@ class ZigbeeCore {
     return _debug;
   }
 
+  // Set global default response callback
+  void onGlobalDefaultResponse(void (*callback)(zb_cmd_type_t resp_to_cmd, esp_zb_zcl_status_t status, uint8_t endpoint, uint16_t cluster)) {
+    _global_default_response_cb = callback;
+  }
+
+  // Call global default response callback (for internal use)
+  void callDefaultResponseCallback(zb_cmd_type_t resp_to_cmd, esp_zb_zcl_status_t status, uint8_t endpoint, uint16_t cluster);
+
   // Friend function declaration to allow access to private members
   friend void esp_zb_app_signal_handler(esp_zb_app_signal_t *signal_struct);
   friend bool zb_apsde_data_indication_handler(esp_zb_apsde_data_ind_t ind);
diff --git a/libraries/Zigbee/src/ZigbeeEP.cpp b/libraries/Zigbee/src/ZigbeeEP.cpp
index efddbdd0368..6b63cae0312 100644
--- a/libraries/Zigbee/src/ZigbeeEP.cpp
+++ b/libraries/Zigbee/src/ZigbeeEP.cpp
@@ -608,7 +608,17 @@ void ZigbeeEP::removeBoundDevice(zb_device_params_t *device) {
   log_w("No matching device found for removal");
 }
 
-const char *ZigbeeEP::esp_zb_zcl_status_to_name(esp_zb_zcl_status_t status) {
+void ZigbeeEP::zbDefaultResponse(const esp_zb_zcl_cmd_default_resp_message_t *message) {
+  log_v("Default response received for endpoint %d", _endpoint);
+  log_v("Status code: %s", esp_zb_zcl_status_to_name(message->status_code));
+  log_v("Response to command: %d", message->resp_to_cmd);
+  if (_on_default_response) {
+    _on_default_response((zb_cmd_type_t)message->resp_to_cmd, message->status_code);
+  }
+}
+
+// Global function implementation
+const char *esp_zb_zcl_status_to_name(esp_zb_zcl_status_t status) {
   switch (status) {
     case ESP_ZB_ZCL_STATUS_SUCCESS:               return "Success";
     case ESP_ZB_ZCL_STATUS_FAIL:                  return "Fail";
diff --git a/libraries/Zigbee/src/ZigbeeEP.h b/libraries/Zigbee/src/ZigbeeEP.h
index a3217cbd066..23217407003 100644
--- a/libraries/Zigbee/src/ZigbeeEP.h
+++ b/libraries/Zigbee/src/ZigbeeEP.h
@@ -38,6 +38,9 @@ typedef enum {
   ZB_POWER_SOURCE_BATTERY = 0x03,
 } zb_power_source_t;
 
+// Global function for converting ZCL status to name
+const char *esp_zb_zcl_status_to_name(esp_zb_zcl_status_t status);
+
 /* Zigbee End Device Class */
 class ZigbeeEP {
 public:
@@ -138,6 +141,7 @@ class ZigbeeEP {
   virtual void zbReadTimeCluster(const esp_zb_zcl_attribute_t *attribute);  //already implemented
   virtual void zbIASZoneStatusChangeNotification(const esp_zb_zcl_ias_zone_status_change_notification_message_t *message) {};
   virtual void zbIASZoneEnrollResponse(const esp_zb_zcl_ias_zone_enroll_response_message_t *message) {};
+  virtual void zbDefaultResponse(const esp_zb_zcl_cmd_default_resp_message_t *message);  //already implemented
 
   virtual void addBoundDevice(zb_device_params_t *device) {
     _bound_devices.push_back(device);
@@ -156,17 +160,21 @@ class ZigbeeEP {
     _on_identify = callback;
   }
 
+  void onDefaultResponse(void (*callback)(zb_cmd_type_t resp_to_cmd, esp_zb_zcl_status_t status)) {
+    _on_default_response = callback;
+  }
+
+  // Convert ZCL status to name
+
 private:
   char *_read_manufacturer;
   char *_read_model;
   void (*_on_identify)(uint16_t time);
+  void (*_on_default_response)(zb_cmd_type_t resp_to_cmd, esp_zb_zcl_status_t status);
   time_t _read_time;
   int32_t _read_timezone;
 
 protected:
-  // Convert ZCL status to name
-  const char *esp_zb_zcl_status_to_name(esp_zb_zcl_status_t status);
-
   uint8_t _endpoint;
   esp_zb_ha_standard_devices_t _device_id;
   esp_zb_endpoint_config_t _ep_config;
@@ -179,6 +187,7 @@ class ZigbeeEP {
   zb_power_source_t _power_source;
   uint8_t _time_status;
 
+  // Friend class declaration to allow access to protected members
   friend class ZigbeeCore;
 };
 
diff --git a/libraries/Zigbee/src/ZigbeeHandlers.cpp b/libraries/Zigbee/src/ZigbeeHandlers.cpp
index 5d54e459058..0986056dcd9 100644
--- a/libraries/Zigbee/src/ZigbeeHandlers.cpp
+++ b/libraries/Zigbee/src/ZigbeeHandlers.cpp
@@ -398,6 +398,16 @@ static esp_err_t zb_cmd_default_resp_handler(const esp_zb_zcl_cmd_default_resp_m
     "Received default response: from address(0x%x), src_endpoint(%d) to dst_endpoint(%d), cluster(0x%x) with status 0x%x",
     message->info.src_address.u.short_addr, message->info.src_endpoint, message->info.dst_endpoint, message->info.cluster, message->status_code
   );
+
+  // Call global callback if set
+  Zigbee.callDefaultResponseCallback((zb_cmd_type_t)message->resp_to_cmd, message->status_code, message->info.dst_endpoint, message->info.cluster);
+
+  // List through all Zigbee EPs and call the callback function, with the message
+  for (std::list<ZigbeeEP *>::iterator it = Zigbee.ep_objects.begin(); it != Zigbee.ep_objects.end(); ++it) {
+    if (message->info.dst_endpoint == (*it)->getEndpoint()) {
+      (*it)->zbDefaultResponse(message);  //method zbDefaultResponse is implemented in the common EP class
+    }
+  }
   return ESP_OK;
 }
 
diff --git a/libraries/Zigbee/src/ZigbeeTypes.h b/libraries/Zigbee/src/ZigbeeTypes.h
new file mode 100644
index 00000000000..5025f90db7c
--- /dev/null
+++ b/libraries/Zigbee/src/ZigbeeTypes.h
@@ -0,0 +1,30 @@
+#pragma once
+
+#include "esp_zigbee_core.h"
+
+// Foundation Command Types
+typedef enum {
+  ZB_CMD_READ_ATTRIBUTE = 0x00U,                        /*!< Read attributes command */
+  ZB_CMD_READ_ATTRIBUTE_RESPONSE = 0x01U,               /*!< Read attributes response command */
+  ZB_CMD_WRITE_ATTRIBUTE = 0x02U,                       /*!< Write attributes foundation command */
+  ZB_CMD_WRITE_ATTRIBUTE_UNDIVIDED = 0x03U,             /*!< Write attributes undivided command */
+  ZB_CMD_WRITE_ATTRIBUTE_RESPONSE = 0x04U,              /*!< Write attributes response command */
+  ZB_CMD_WRITE_ATTRIBUTE_NO_RESPONSE = 0x05U,           /*!< Write attributes no response command */
+  ZB_CMD_CONFIGURE_REPORTING = 0x06U,                   /*!< Configure reporting command */
+  ZB_CMD_CONFIGURE_REPORTING_RESPONSE = 0x07U,          /*!< Configure reporting response command */
+  ZB_CMD_READ_REPORTING_CONFIG = 0x08U,                 /*!< Read reporting config command */
+  ZB_CMD_READ_REPORTING_CONFIG_RESPONSE = 0x09U,        /*!< Read reporting config response command */
+  ZB_CMD_REPORT_ATTRIBUTE = 0x0aU,                      /*!< Report attribute command */
+  ZB_CMD_DEFAULT_RESPONSE = 0x0bU,                      /*!< Default response command */
+  ZB_CMD_DISCOVER_ATTRIBUTES = 0x0cU,                   /*!< Discover attributes command */
+  ZB_CMD_DISCOVER_ATTRIBUTES_RESPONSE = 0x0dU,          /*!< Discover attributes response command */
+  ZB_CMD_READ_ATTRIBUTE_STRUCTURED = 0x0eU,             /*!< Read attributes structured */
+  ZB_CMD_WRITE_ATTRIBUTE_STRUCTURED = 0x0fU,            /*!< Write attributes structured */
+  ZB_CMD_WRITE_ATTRIBUTE_STRUCTURED_RESPONSE = 0x10U,   /*!< Write attributes structured response */
+  ZB_CMD_DISCOVER_COMMANDS_RECEIVED = 0x11U,            /*!< Discover Commands Received command */
+  ZB_CMD_DISCOVER_COMMANDS_RECEIVED_RESPONSE = 0x12U,   /*!< Discover Commands Received response command */
+  ZB_CMD_DISCOVER_COMMANDS_GENERATED = 0x13U,           /*!< Discover Commands Generated command */
+  ZB_CMD_DISCOVER_COMMANDS_GENERATED_RESPONSE = 0x14U,  /*!< Discover Commands Generated response command */
+  ZB_CMD_DISCOVER_ATTRIBUTES_EXTENDED = 0x15U,          /*!< Discover attributes extended command */
+  ZB_CMD_DISCOVER_ATTRIBUTES_EXTENDED_RESPONSE = 0x16U, /*!< Discover attributes extended response command */
+} zb_cmd_type_t;

From 995e603d3af8305959948a46ff0793c72e5c1687 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Proch=C3=A1zka?=
 <90197375+P-R-O-C-H-Y@users.noreply.github.com>
Date: Mon, 21 Jul 2025 14:47:43 +0200
Subject: [PATCH 066/105] fix(zigbee): Replace assert with error log to solve
 immediate crash (#11614)

* fix(zigbee): Replace assert with error log to solve immediate crash

* ci(pre-commit): Apply automatic fixes

---------

Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 libraries/Zigbee/src/ZigbeeCore.cpp | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/libraries/Zigbee/src/ZigbeeCore.cpp b/libraries/Zigbee/src/ZigbeeCore.cpp
index bf652642ac1..90b29cf9d0a 100644
--- a/libraries/Zigbee/src/ZigbeeCore.cpp
+++ b/libraries/Zigbee/src/ZigbeeCore.cpp
@@ -238,7 +238,9 @@ void ZigbeeCore::closeNetwork() {
 }
 
 static void bdb_start_top_level_commissioning_cb(uint8_t mode_mask) {
-  ESP_ERROR_CHECK(esp_zb_bdb_start_top_level_commissioning(mode_mask));
+  if (esp_zb_bdb_start_top_level_commissioning(mode_mask) != ESP_OK) {
+    log_e("Failed to start Zigbee commissioning");
+  }
 }
 
 void esp_zb_app_signal_handler(esp_zb_app_signal_t *signal_struct) {

From f1712943b4960749316612bcf0fb4caf5d74efa0 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Mon, 21 Jul 2025 15:48:05 +0300
Subject: [PATCH 067/105] fix(ppp): Detach PPP RST pin from periman on end
 (#11620)

---
 libraries/PPP/src/PPP.cpp | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/libraries/PPP/src/PPP.cpp b/libraries/PPP/src/PPP.cpp
index 87fee6920c3..2a5c5760287 100644
--- a/libraries/PPP/src/PPP.cpp
+++ b/libraries/PPP/src/PPP.cpp
@@ -432,6 +432,11 @@ void PPPClass::end(void) {
     _pin_cts = -1;
     perimanClearPinBus(pin);
   }
+  if (_pin_rst != -1) {
+    pin = _pin_rst;
+    _pin_rst = -1;
+    perimanClearPinBus(pin);
+  }
 
   _mode = ESP_MODEM_MODE_COMMAND;
 }

From 4a3c6d7fbbb21ac7439e145680f8201c00b11b67 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Mon, 21 Jul 2025 15:49:15 +0300
Subject: [PATCH 068/105] feat(netif): Allow setting interface's routing
 priority (#11617)

* feat(netif): Allow setting interface's routing priority

* feat(netif): Rename route priority method names and add notes

* feat(netif): Print route prio for each interface
---
 libraries/Network/src/NetworkInterface.cpp | 28 ++++++++++++++++++++--
 libraries/Network/src/NetworkInterface.h   |  5 +++-
 2 files changed, 30 insertions(+), 3 deletions(-)

diff --git a/libraries/Network/src/NetworkInterface.cpp b/libraries/Network/src/NetworkInterface.cpp
index 01790ec2493..06cf2a377b0 100644
--- a/libraries/Network/src/NetworkInterface.cpp
+++ b/libraries/Network/src/NetworkInterface.cpp
@@ -606,13 +606,33 @@ int NetworkInterface::impl_index() const {
   return esp_netif_get_netif_impl_index(_esp_netif);
 }
 
-int NetworkInterface::route_prio() const {
+/**
+ * Every netif has a parameter named route_prio, you can refer to file esp_netif_defaults.h.
+ * A higher value of route_prio indicates a higher priority.
+ * The active interface with highest priority will be used for default route (gateway).
+ * Defaults are: STA=100, BR=70, ETH=50, PPP=20, AP/NAN=10
+ */
+int NetworkInterface::getRoutePrio() const {
   if (_esp_netif == NULL) {
     return -1;
   }
   return esp_netif_get_route_prio(_esp_netif);
 }
 
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
+int NetworkInterface::setRoutePrio(int prio) {
+  if (_esp_netif == NULL) {
+    return -1;
+  }
+  return esp_netif_set_route_prio(_esp_netif, prio);
+}
+#endif
+
+/**
+ * This API overrides the automatic configuration of the default interface based on the route_prio
+ * If the selected netif is set default using this API, no other interface could be set-default disregarding
+ * its route_prio number (unless the selected netif gets destroyed)
+ */
 bool NetworkInterface::setDefault() {
   if (_esp_netif == NULL) {
     return false;
@@ -819,7 +839,11 @@ size_t NetworkInterface::printTo(Print &out) const {
   if (flags & ESP_NETIF_FLAG_MLDV6_REPORT) {
     bytes += out.print(",V6_REP");
   }
-  bytes += out.println(")");
+  bytes += out.print(")");
+
+  bytes += out.print(" PRIO: ");
+  bytes += out.print(getRoutePrio());
+  bytes += out.println("");
 
   bytes += out.print("      ");
   bytes += out.print("ether ");
diff --git a/libraries/Network/src/NetworkInterface.h b/libraries/Network/src/NetworkInterface.h
index 4f97181d4fd..fd26df77697 100644
--- a/libraries/Network/src/NetworkInterface.h
+++ b/libraries/Network/src/NetworkInterface.h
@@ -57,7 +57,10 @@ class NetworkInterface : public Printable {
   const char *desc() const;
   String impl_name() const;
   int impl_index() const;
-  int route_prio() const;
+  int getRoutePrio() const;
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
+  int setRoutePrio(int prio);
+#endif
   bool setDefault();
   bool isDefault() const;
 

From c369dca062ee99bf8b20ffee89537f3c66d9ea52 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Proch=C3=A1zka?=
 <90197375+P-R-O-C-H-Y@users.noreply.github.com>
Date: Mon, 21 Jul 2025 23:35:28 +0200
Subject: [PATCH 069/105] feat(docs): Add Zigbee library API documentation
 (#11525)

* feat(docs): Add Zigbee library documentation

* fix: Remove helper scripts

* fix: Proper class naming for better readability

* fix(docs): Fix typos

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* ci(pre-commit): Apply automatic fixes

* fix(docs): Precommit fixes

* fix(docs): Precommit fixes

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
---
 docs/en/libraries.rst                        |  12 +
 docs/en/zigbee/ep_analog.rst                 | 280 ++++++++++++++
 docs/en/zigbee/ep_binary.rst                 | 137 +++++++
 docs/en/zigbee/ep_carbon_dioxide_sensor.rst  | 105 ++++++
 docs/en/zigbee/ep_color_dimmable_light.rst   | 223 +++++++++++
 docs/en/zigbee/ep_color_dimmer_switch.rst    | 186 +++++++++
 docs/en/zigbee/ep_contact_switch.rst         |  95 +++++
 docs/en/zigbee/ep_dimmable_light.rst         | 138 +++++++
 docs/en/zigbee/ep_door_window_handle.rst     |  95 +++++
 docs/en/zigbee/ep_electrical_measurement.rst | 254 +++++++++++++
 docs/en/zigbee/ep_flow_sensor.rst            | 119 ++++++
 docs/en/zigbee/ep_gateway.rst                |  35 ++
 docs/en/zigbee/ep_illuminance_sensor.rst     | 109 ++++++
 docs/en/zigbee/ep_light.rst                  |  88 +++++
 docs/en/zigbee/ep_occupancy_sensor.rst       |  81 ++++
 docs/en/zigbee/ep_pm25_sensor.rst            | 109 ++++++
 docs/en/zigbee/ep_power_outlet.rst           |  88 +++++
 docs/en/zigbee/ep_pressure_sensor.rst        | 109 ++++++
 docs/en/zigbee/ep_range_extender.rst         |  34 ++
 docs/en/zigbee/ep_switch.rst                 | 136 +++++++
 docs/en/zigbee/ep_temperature_sensor.rst     | 184 +++++++++
 docs/en/zigbee/ep_thermostat.rst             | 238 ++++++++++++
 docs/en/zigbee/ep_vibration_sensor.rst       |  87 +++++
 docs/en/zigbee/ep_wind_speed_sensor.rst      | 119 ++++++
 docs/en/zigbee/ep_window_covering.rst        | 233 ++++++++++++
 docs/en/zigbee/zigbee.rst                    | 159 ++++++++
 docs/en/zigbee/zigbee_core.rst               | 375 +++++++++++++++++++
 docs/en/zigbee/zigbee_ep.rst                 | 357 ++++++++++++++++++
 28 files changed, 4185 insertions(+)
 create mode 100644 docs/en/zigbee/ep_analog.rst
 create mode 100644 docs/en/zigbee/ep_binary.rst
 create mode 100644 docs/en/zigbee/ep_carbon_dioxide_sensor.rst
 create mode 100644 docs/en/zigbee/ep_color_dimmable_light.rst
 create mode 100644 docs/en/zigbee/ep_color_dimmer_switch.rst
 create mode 100644 docs/en/zigbee/ep_contact_switch.rst
 create mode 100644 docs/en/zigbee/ep_dimmable_light.rst
 create mode 100644 docs/en/zigbee/ep_door_window_handle.rst
 create mode 100644 docs/en/zigbee/ep_electrical_measurement.rst
 create mode 100644 docs/en/zigbee/ep_flow_sensor.rst
 create mode 100644 docs/en/zigbee/ep_gateway.rst
 create mode 100644 docs/en/zigbee/ep_illuminance_sensor.rst
 create mode 100644 docs/en/zigbee/ep_light.rst
 create mode 100644 docs/en/zigbee/ep_occupancy_sensor.rst
 create mode 100644 docs/en/zigbee/ep_pm25_sensor.rst
 create mode 100644 docs/en/zigbee/ep_power_outlet.rst
 create mode 100644 docs/en/zigbee/ep_pressure_sensor.rst
 create mode 100644 docs/en/zigbee/ep_range_extender.rst
 create mode 100644 docs/en/zigbee/ep_switch.rst
 create mode 100644 docs/en/zigbee/ep_temperature_sensor.rst
 create mode 100644 docs/en/zigbee/ep_thermostat.rst
 create mode 100644 docs/en/zigbee/ep_vibration_sensor.rst
 create mode 100644 docs/en/zigbee/ep_wind_speed_sensor.rst
 create mode 100644 docs/en/zigbee/ep_window_covering.rst
 create mode 100644 docs/en/zigbee/zigbee.rst
 create mode 100644 docs/en/zigbee/zigbee_core.rst
 create mode 100644 docs/en/zigbee/zigbee_ep.rst

diff --git a/docs/en/libraries.rst b/docs/en/libraries.rst
index 525a5c4ba26..07f0978be68 100644
--- a/docs/en/libraries.rst
+++ b/docs/en/libraries.rst
@@ -91,3 +91,15 @@ The Arduino ESP32 offers some unique APIs, described in this section:
     :glob:
 
     api/*
+
+Zigbee APIs
+-----------
+
+.. toctree::
+    :maxdepth: 1
+    :glob:
+
+    zigbee/zigbee
+    zigbee/zigbee_core
+    zigbee/zigbee_ep
+    zigbee/ep_*
diff --git a/docs/en/zigbee/ep_analog.rst b/docs/en/zigbee/ep_analog.rst
new file mode 100644
index 00000000000..45740007881
--- /dev/null
+++ b/docs/en/zigbee/ep_analog.rst
@@ -0,0 +1,280 @@
+############
+ZigbeeAnalog
+############
+
+About
+-----
+
+The ``ZigbeeAnalog`` class provides analog input and output endpoints for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for analog signal processing and control.
+Analog Input (AI) is meant to be used for sensors that provide an analog signal, such as temperature, humidity, pressure to be sent to the coordinator.
+Analog Output (AO) is meant to be used for actuators that require an analog signal, such as dimmers, valves, etc. to be controlled by the coordinator.
+
+
+Common API
+----------
+
+Constructor
+***********
+
+ZigbeeAnalog
+^^^^^^^^^^^^
+
+Creates a new Zigbee analog endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeAnalog(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Cluster Management
+******************
+
+addAnalogInput
+^^^^^^^^^^^^^^
+
+Adds analog input cluster to the endpoint.
+
+.. code-block:: arduino
+
+    bool addAnalogInput();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+addAnalogOutput
+^^^^^^^^^^^^^^^
+
+Adds analog output cluster to the endpoint.
+
+.. code-block:: arduino
+
+    bool addAnalogOutput();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Analog Input API
+----------------
+
+Configuration Methods
+*********************
+
+setAnalogInputApplication
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sets the application type for the analog input.
+
+.. code-block:: arduino
+
+    bool setAnalogInputApplication(uint32_t application_type);
+
+* ``application_type`` - Application type constant (see esp_zigbee_zcl_analog_input.h for values)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setAnalogInputDescription
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sets a custom description for the analog input.
+
+.. code-block:: arduino
+
+    bool setAnalogInputDescription(const char *description);
+
+* ``description`` - Description string
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setAnalogInputResolution
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sets the resolution for the analog input.
+
+.. code-block:: arduino
+
+    bool setAnalogInputResolution(float resolution);
+
+* ``resolution`` - Resolution value
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setAnalogInputMinMax
+^^^^^^^^^^^^^^^^^^^^
+
+Sets the minimum and maximum values for the analog input.
+
+.. code-block:: arduino
+
+    bool setAnalogInputMinMax(float min, float max);
+
+* ``min`` - Minimum value
+* ``max`` - Maximum value
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Value Control
+*************
+
+setAnalogInput
+^^^^^^^^^^^^^^
+
+Sets the analog input value.
+
+.. code-block:: arduino
+
+    bool setAnalogInput(float analog);
+
+* ``analog`` - Analog input value
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Reporting Methods
+*****************
+
+setAnalogInputReporting
+^^^^^^^^^^^^^^^^^^^^^^^
+
+Sets the reporting configuration for analog input.
+
+.. code-block:: arduino
+
+    bool setAnalogInputReporting(uint16_t min_interval, uint16_t max_interval, float delta);
+
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change in value to trigger a report
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+reportAnalogInput
+^^^^^^^^^^^^^^^^^
+
+Manually reports the current analog input value.
+
+.. code-block:: arduino
+
+    bool reportAnalogInput();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Analog Output API
+-----------------
+
+Configuration Methods
+*********************
+
+setAnalogOutputApplication
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sets the application type for the analog output.
+
+.. code-block:: arduino
+
+    bool setAnalogOutputApplication(uint32_t application_type);
+
+* ``application_type`` - Application type constant (see esp_zigbee_zcl_analog_output.h for values)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setAnalogOutputDescription
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sets a custom description for the analog output.
+
+.. code-block:: arduino
+
+    bool setAnalogOutputDescription(const char *description);
+
+* ``description`` - Description string
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setAnalogOutputResolution
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sets the resolution for the analog output.
+
+.. code-block:: arduino
+
+    bool setAnalogOutputResolution(float resolution);
+
+* ``resolution`` - Resolution value
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setAnalogOutputMinMax
+^^^^^^^^^^^^^^^^^^^^^
+
+Sets the minimum and maximum values for the analog output.
+
+.. code-block:: arduino
+
+    bool setAnalogOutputMinMax(float min, float max);
+
+* ``min`` - Minimum value
+* ``max`` - Maximum value
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Value Control
+*************
+
+setAnalogOutput
+^^^^^^^^^^^^^^^
+
+Sets the analog output value.
+
+.. code-block:: arduino
+
+    bool setAnalogOutput(float analog);
+
+* ``analog`` - Analog output value
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+getAnalogOutput
+^^^^^^^^^^^^^^^
+
+Gets the current analog output value.
+
+.. code-block:: arduino
+
+    float getAnalogOutput();
+
+This function will return current analog output value.
+
+Reporting Methods
+*****************
+
+reportAnalogOutput
+^^^^^^^^^^^^^^^^^^
+
+Manually reports the current analog output value.
+
+.. code-block:: arduino
+
+    bool reportAnalogOutput();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Event Handling
+**************
+
+onAnalogOutputChange
+^^^^^^^^^^^^^^^^^^^^
+
+Sets a callback function to be called when the analog output value changes.
+
+.. code-block:: arduino
+
+    void onAnalogOutputChange(void (*callback)(float analog));
+
+* ``callback`` - Function to call when analog output changes
+
+Example
+-------
+
+Analog Input/Output
+*******************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Analog_Input_Output/Zigbee_Analog_Input_Output.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_binary.rst b/docs/en/zigbee/ep_binary.rst
new file mode 100644
index 00000000000..950e20ef42b
--- /dev/null
+++ b/docs/en/zigbee/ep_binary.rst
@@ -0,0 +1,137 @@
+############
+ZigbeeBinary
+############
+
+About
+-----
+
+The ``ZigbeeBinary`` class provides an endpoint for binary input/output sensors in Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for binary sensors, supporting various application types for HVAC, security, and general binary sensing.
+Binary Input (BI) is meant to be used for sensors that provide a binary signal, such as door/window sensors, motion detectors, etc. to be sent to the network.
+
+.. note::
+
+    Binary Output (BO) is not supported yet.
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeBinary
+^^^^^^^^^^^^
+
+Creates a new Zigbee binary sensor endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeBinary(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Binary Input Application Types
+******************************
+
+HVAC Application Types
+^^^^^^^^^^^^^^^^^^^^^^
+
+.. code-block:: arduino
+
+    #define BINARY_INPUT_APPLICATION_TYPE_HVAC_BOILER_STATUS  0x00000003
+    #define BINARY_INPUT_APPLICATION_TYPE_HVAC_CHILLER_STATUS 0x00000013
+    #define BINARY_INPUT_APPLICATION_TYPE_HVAC_OCCUPANCY      0x00000031
+    #define BINARY_INPUT_APPLICATION_TYPE_HVAC_FAN_STATUS     0x00000035
+    #define BINARY_INPUT_APPLICATION_TYPE_HVAC_FILTER_STATUS  0x00000036
+    #define BINARY_INPUT_APPLICATION_TYPE_HVAC_HEATING_ALARM  0x0000003E
+    #define BINARY_INPUT_APPLICATION_TYPE_HVAC_COOLING_ALARM  0x0000001D
+    #define BINARY_INPUT_APPLICATION_TYPE_HVAC_UNIT_ENABLE    0x00000090
+    #define BINARY_INPUT_APPLICATION_TYPE_HVAC_OTHER          0x0000FFFF
+
+Security Application Types
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. code-block:: arduino
+
+    #define BINARY_INPUT_APPLICATION_TYPE_SECURITY_GLASS_BREAKAGE_DETECTION_0 0x01000000
+    #define BINARY_INPUT_APPLICATION_TYPE_SECURITY_INTRUSION_DETECTION        0x01000001
+    #define BINARY_INPUT_APPLICATION_TYPE_SECURITY_MOTION_DETECTION           0x01000002
+    #define BINARY_INPUT_APPLICATION_TYPE_SECURITY_GLASS_BREAKAGE_DETECTION_1 0x01000003
+    #define BINARY_INPUT_APPLICATION_TYPE_SECURITY_ZONE_ARMED                 0x01000004
+    #define BINARY_INPUT_APPLICATION_TYPE_SECURITY_GLASS_BREAKAGE_DETECTION_2 0x01000005
+    #define BINARY_INPUT_APPLICATION_TYPE_SECURITY_SMOKE_DETECTION            0x01000006
+    #define BINARY_INPUT_APPLICATION_TYPE_SECURITY_CARBON_DIOXIDE_DETECTION   0x01000007
+    #define BINARY_INPUT_APPLICATION_TYPE_SECURITY_HEAT_DETECTION             0x01000008
+    #define BINARY_INPUT_APPLICATION_TYPE_SECURITY_OTHER                      0x0100FFFF
+
+API Methods
+***********
+
+addBinaryInput
+^^^^^^^^^^^^^^
+
+Adds a binary input cluster to the endpoint.
+
+.. code-block:: arduino
+
+    bool addBinaryInput();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setBinaryInputApplication
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sets the application type for the binary input.
+
+.. code-block:: arduino
+
+    bool setBinaryInputApplication(uint32_t application_type);
+
+* ``application_type`` - Application type constant (see above)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setBinaryInputDescription
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sets a custom description for the binary input.
+
+.. code-block:: arduino
+
+    bool setBinaryInputDescription(const char *description);
+
+* ``description`` - Description string
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setBinaryInput
+^^^^^^^^^^^^^^
+
+Sets the binary input value.
+
+.. code-block:: arduino
+
+    bool setBinaryInput(bool input);
+
+* ``input`` - Binary value (true/false)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+reportBinaryInput
+^^^^^^^^^^^^^^^^^
+
+Manually reports the current binary input value.
+
+.. code-block:: arduino
+
+    bool reportBinaryInput();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Example
+-------
+
+Binary Input Implementation
+****************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Binary_Input/Zigbee_Binary_Input.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_carbon_dioxide_sensor.rst b/docs/en/zigbee/ep_carbon_dioxide_sensor.rst
new file mode 100644
index 00000000000..6f219a16fd0
--- /dev/null
+++ b/docs/en/zigbee/ep_carbon_dioxide_sensor.rst
@@ -0,0 +1,105 @@
+#########################
+ZigbeeCarbonDioxideSensor
+#########################
+
+About
+-----
+
+The ``ZigbeeCarbonDioxideSensor`` class provides a CO2 sensor endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for carbon dioxide measurement devices.
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeCarbonDioxideSensor
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee CO2 sensor endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeCarbonDioxideSensor(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+API Methods
+***********
+
+setCarbonDioxide
+^^^^^^^^^^^^^^^^
+
+Sets the CO2 concentration measurement value.
+
+.. code-block:: arduino
+
+    bool setCarbonDioxide(float carbon_dioxide);
+
+* ``carbon_dioxide`` - CO2 concentration value in ppm
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setMinMaxValue
+^^^^^^^^^^^^^^
+
+Sets the minimum and maximum measurement values.
+
+.. code-block:: arduino
+
+    bool setMinMaxValue(float min, float max);
+
+* ``min`` - Minimum CO2 concentration value in ppm
+* ``max`` - Maximum CO2 concentration value in ppm
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setTolerance
+^^^^^^^^^^^^
+
+Sets the tolerance value for measurements.
+
+.. code-block:: arduino
+
+    bool setTolerance(float tolerance);
+
+* ``tolerance`` - Tolerance value in ppm
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setReporting
+^^^^^^^^^^^^
+
+Sets the reporting configuration for CO2 measurements.
+
+.. code-block:: arduino
+
+    bool setReporting(uint16_t min_interval, uint16_t max_interval, uint16_t delta);
+
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change required to trigger a report in ppm
+
+**Note:** Delta reporting is currently not supported by the carbon dioxide sensor.
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+report
+^^^^^^
+
+Manually reports the current CO2 concentration value.
+
+.. code-block:: arduino
+
+    bool report();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Example
+-------
+
+CO2 Sensor Implementation
+*************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_CarbonDioxide_Sensor/Zigbee_CarbonDioxide_Sensor.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_color_dimmable_light.rst b/docs/en/zigbee/ep_color_dimmable_light.rst
new file mode 100644
index 00000000000..b2fa6d0bf91
--- /dev/null
+++ b/docs/en/zigbee/ep_color_dimmable_light.rst
@@ -0,0 +1,223 @@
+########################
+ZigbeeColorDimmableLight
+########################
+
+About
+-----
+
+The ``ZigbeeColorDimmableLight`` class provides an endpoint for color dimmable lights in Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for color lighting devices, supporting RGB color control, dimming, and scene management.
+
+**Features:**
+* On/off control
+* Brightness level control (0-100%)
+* RGB color control
+* HSV color support
+* Scene and group support
+* Automatic state restoration
+* Integration with common endpoint features (binding, OTA, etc.)
+* Zigbee HA standard compliance
+
+**Use Cases:**
+* Smart RGB light bulbs
+* Color-changing LED strips
+* Mood lighting systems
+* Entertainment lighting
+* Architectural lighting
+* Smart home color lighting
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeColorDimmableLight
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee color dimmable light endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeColorDimmableLight(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Callback Functions
+******************
+
+onLightChange
+^^^^^^^^^^^^^
+
+Sets the callback function for light state changes.
+
+.. code-block:: arduino
+
+    void onLightChange(void (*callback)(bool, uint8_t, uint8_t, uint8_t, uint8_t));
+
+* ``callback`` - Function pointer to the light change callback (state, red, green, blue, level)
+
+Control Methods
+***************
+
+setLightState
+^^^^^^^^^^^^^
+
+Sets the light on/off state.
+
+.. code-block:: arduino
+
+    bool setLightState(bool state);
+
+* ``state`` - Light state (true = on, false = off)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setLightLevel
+^^^^^^^^^^^^^
+
+Sets the light brightness level.
+
+.. code-block:: arduino
+
+    bool setLightLevel(uint8_t level);
+
+* ``level`` - Brightness level (0-100, where 0 is off, 100 is full brightness)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setLightColor (RGB)
+^^^^^^^^^^^^^^^^^^^
+
+Sets the light color using RGB values.
+
+.. code-block:: arduino
+
+    bool setLightColor(uint8_t red, uint8_t green, uint8_t blue);
+    bool setLightColor(espRgbColor_t rgb_color);
+
+* ``red`` - Red component (0-255)
+* ``green`` - Green component (0-255)
+* ``blue`` - Blue component (0-255)
+* ``rgb_color`` - RGB color structure
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setLightColor (HSV)
+^^^^^^^^^^^^^^^^^^^
+
+Sets the light color using HSV values.
+
+.. code-block:: arduino
+
+    bool setLightColor(espHsvColor_t hsv_color);
+
+* ``hsv_color`` - HSV color structure
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setLight
+^^^^^^^^
+
+Sets all light parameters at once.
+
+.. code-block:: arduino
+
+    bool setLight(bool state, uint8_t level, uint8_t red, uint8_t green, uint8_t blue);
+
+* ``state`` - Light state (true/false)
+* ``level`` - Brightness level (0-100)
+* ``red`` - Red component (0-255)
+* ``green`` - Green component (0-255)
+* ``blue`` - Blue component (0-255)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+State Retrieval Methods
+***********************
+
+getLightState
+^^^^^^^^^^^^^
+
+Gets the current light state.
+
+.. code-block:: arduino
+
+    bool getLightState();
+
+This function will return current light state (true = on, false = off).
+
+getLightLevel
+^^^^^^^^^^^^^
+
+Gets the current brightness level.
+
+.. code-block:: arduino
+
+    uint8_t getLightLevel();
+
+This function will return current brightness level (0-100).
+
+getLightColor
+^^^^^^^^^^^^^
+
+Gets the current RGB color.
+
+.. code-block:: arduino
+
+    espRgbColor_t getLightColor();
+
+This function will return current RGB color structure.
+
+getLightRed
+^^^^^^^^^^^
+
+Gets the current red component.
+
+.. code-block:: arduino
+
+    uint8_t getLightRed();
+
+This function will return current red component (0-255).
+
+getLightGreen
+^^^^^^^^^^^^^
+
+Gets the current green component.
+
+.. code-block:: arduino
+
+    uint8_t getLightGreen();
+
+This function will return current green component (0-255).
+
+getLightBlue
+^^^^^^^^^^^^
+
+Gets the current blue component.
+
+.. code-block:: arduino
+
+    uint8_t getLightBlue();
+
+This function will return current blue component (0-255).
+
+Utility Methods
+***************
+
+restoreLight
+^^^^^^^^^^^^
+
+Restores the light to its last known state.
+
+.. code-block:: arduino
+
+    void restoreLight();
+
+Example
+-------
+
+Color Dimmable Light Implementation
+***********************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Color_Dimmable_Light/Zigbee_Color_Dimmable_Light.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_color_dimmer_switch.rst b/docs/en/zigbee/ep_color_dimmer_switch.rst
new file mode 100644
index 00000000000..720c5d8f5bf
--- /dev/null
+++ b/docs/en/zigbee/ep_color_dimmer_switch.rst
@@ -0,0 +1,186 @@
+#######################
+ZigbeeColorDimmerSwitch
+#######################
+
+About
+-----
+
+The ``ZigbeeColorDimmerSwitch`` class provides a color dimmer switch endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for advanced lighting control switches that can control both dimming and color of lights.
+
+**Features:**
+* On/off control for bound lights
+* Brightness level control (0-100%)
+* Color control (RGB, HSV)
+* Color temperature control
+* Scene and group support
+* Special effects and timed operations
+* Integration with common endpoint features (binding, OTA, etc.)
+* Zigbee HA standard compliance
+
+**Use Cases:**
+* Smart lighting switches
+* Color control remotes
+* Advanced lighting controllers
+* Smart home lighting automation
+* Entertainment lighting control
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeColorDimmerSwitch
+^^^^^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee color dimmer switch endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeColorDimmerSwitch(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Basic Control Commands
+**********************
+
+lightToggle
+^^^^^^^^^^^
+
+Toggles the state of bound lights (on to off, or off to on).
+
+.. code-block:: arduino
+
+    void lightToggle();
+    void lightToggle(uint16_t group_addr);
+    void lightToggle(uint8_t endpoint, uint16_t short_addr);
+    void lightToggle(uint8_t endpoint, esp_zb_ieee_addr_t ieee_addr);
+
+* ``group_addr`` - Group address to control (optional)
+* ``endpoint`` - Target device endpoint (optional)
+* ``short_addr`` - Target device short address (optional)
+* ``ieee_addr`` - Target device IEEE address (optional)
+
+lightOn
+^^^^^^^
+
+Turns on bound lights.
+
+.. code-block:: arduino
+
+    void lightOn();
+    void lightOn(uint16_t group_addr);
+    void lightOn(uint8_t endpoint, uint16_t short_addr);
+    void lightOn(uint8_t endpoint, esp_zb_ieee_addr_t ieee_addr);
+
+* ``group_addr`` - Group address to control (optional)
+* ``endpoint`` - Target device endpoint (optional)
+* ``short_addr`` - Target device short address (optional)
+* ``ieee_addr`` - Target device IEEE address (optional)
+
+lightOff
+^^^^^^^^
+
+Turns off bound lights.
+
+.. code-block:: arduino
+
+    void lightOff();
+    void lightOff(uint16_t group_addr);
+    void lightOff(uint8_t endpoint, uint16_t short_addr);
+    void lightOff(uint8_t endpoint, esp_zb_ieee_addr_t ieee_addr);
+
+* ``group_addr`` - Group address to control (optional)
+* ``endpoint`` - Target device endpoint (optional)
+* ``short_addr`` - Target device short address (optional)
+* ``ieee_addr`` - Target device IEEE address (optional)
+
+Dimmer Control Commands
+***********************
+
+setLightLevel
+^^^^^^^^^^^^^
+
+Sets the brightness level of bound lights.
+
+.. code-block:: arduino
+
+    void setLightLevel(uint8_t level);
+    void setLightLevel(uint8_t level, uint16_t group_addr);
+    void setLightLevel(uint8_t level, uint8_t endpoint, uint16_t short_addr);
+    void setLightLevel(uint8_t level, uint8_t endpoint, esp_zb_ieee_addr_t ieee_addr);
+
+* ``level`` - Brightness level (0-100, where 0 is off, 100 is full brightness)
+* ``group_addr`` - Group address to control (optional)
+* ``endpoint`` - Target device endpoint (optional)
+* ``short_addr`` - Target device short address (optional)
+* ``ieee_addr`` - Target device IEEE address (optional)
+
+Color Control Commands
+**********************
+
+setLightColor
+^^^^^^^^^^^^^
+
+Sets the color of bound lights using RGB values.
+
+.. code-block:: arduino
+
+    void setLightColor(uint8_t red, uint8_t green, uint8_t blue);
+    void setLightColor(uint8_t red, uint8_t green, uint8_t blue, uint16_t group_addr);
+    void setLightColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t endpoint, uint16_t short_addr);
+    void setLightColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t endpoint, esp_zb_ieee_addr_t ieee_addr);
+
+* ``red`` - Red component (0-255)
+* ``green`` - Green component (0-255)
+* ``blue`` - Blue component (0-255)
+* ``group_addr`` - Group address to control (optional)
+* ``endpoint`` - Target device endpoint (optional)
+* ``short_addr`` - Target device short address (optional)
+* ``ieee_addr`` - Target device IEEE address (optional)
+
+Advanced Control Commands
+*************************
+
+lightOffWithEffect
+^^^^^^^^^^^^^^^^^^
+
+Turns off lights with a specific effect.
+
+.. code-block:: arduino
+
+    void lightOffWithEffect(uint8_t effect_id, uint8_t effect_variant);
+
+* ``effect_id`` - Effect identifier
+* ``effect_variant`` - Effect variant
+
+lightOnWithTimedOff
+^^^^^^^^^^^^^^^^^^^
+
+Turns on lights with automatic turn-off after specified time.
+
+.. code-block:: arduino
+
+    void lightOnWithTimedOff(uint8_t on_off_control, uint16_t time_on, uint16_t time_off);
+
+* ``on_off_control`` - Control byte
+* ``time_on`` - Time to stay on (in 1/10th seconds)
+* ``time_off`` - Time to stay off (in 1/10th seconds)
+
+lightOnWithSceneRecall
+^^^^^^^^^^^^^^^^^^^^^^
+
+Turns on lights with scene recall.
+
+.. code-block:: arduino
+
+    void lightOnWithSceneRecall();
+
+Example
+-------
+
+Color Dimmer Switch Implementation
+**********************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Color_Dimmer_Switch/Zigbee_Color_Dimmer_Switch.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_contact_switch.rst b/docs/en/zigbee/ep_contact_switch.rst
new file mode 100644
index 00000000000..f7f6dc15c66
--- /dev/null
+++ b/docs/en/zigbee/ep_contact_switch.rst
@@ -0,0 +1,95 @@
+###################
+ZigbeeContactSwitch
+###################
+
+About
+-----
+
+The ``ZigbeeContactSwitch`` class provides a contact switch endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for door/window contact sensors and other binary contact devices.
+
+**Features:**
+* Contact state detection (open/closed)
+* Configurable application types
+* Automatic reporting capabilities
+* Integration with common endpoint features (binding, OTA, etc.)
+* Zigbee HA standard compliance
+
+**Use Cases:**
+* Door and window sensors
+* Security system contacts
+* Cabinet and drawer sensors
+* Industrial contact monitoring
+* Smart home security applications
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeContactSwitch
+^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee contact switch endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeContactSwitch(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+API Methods
+***********
+
+setClosed
+^^^^^^^^^
+
+Sets the contact switch to closed state.
+
+.. code-block:: arduino
+
+    bool setClosed();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setOpen
+^^^^^^^
+
+Sets the contact switch to open state.
+
+.. code-block:: arduino
+
+    bool setOpen();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setIASClientEndpoint
+^^^^^^^^^^^^^^^^^^^^
+
+Sets the IAS Client endpoint number (default is 1).
+
+.. code-block:: arduino
+
+    void setIASClientEndpoint(uint8_t ep_number);
+
+* ``ep_number`` - IAS Client endpoint number
+
+report
+^^^^^^
+
+Manually reports the current contact state.
+
+.. code-block:: arduino
+
+    bool report();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Example
+-------
+
+Contact Switch Implementation
+*****************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Contact_Switch/Zigbee_Contact_Switch.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_dimmable_light.rst b/docs/en/zigbee/ep_dimmable_light.rst
new file mode 100644
index 00000000000..dcfe6e1fc9d
--- /dev/null
+++ b/docs/en/zigbee/ep_dimmable_light.rst
@@ -0,0 +1,138 @@
+###################
+ZigbeeDimmableLight
+###################
+
+About
+-----
+
+The ``ZigbeeDimmableLight`` class provides a dimmable light endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for dimmable lighting control with both on/off and brightness level control.
+
+**Features:**
+* On/off control
+* Brightness level control (0-100%)
+* State and level change callbacks
+* Integration with common endpoint features (binding, OTA, etc.)
+* Zigbee HA standard compliance
+
+**Use Cases:**
+* Dimmable smart bulbs
+* LED strips with brightness control
+* Any device requiring both on/off and dimming functionality
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeDimmableLight
+^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee dimmable light endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeDimmableLight(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Light Control
+*************
+
+setLightState
+^^^^^^^^^^^^^
+
+Sets only the light state (on or off) without changing the brightness level.
+
+.. code-block:: arduino
+
+    bool setLightState(bool state);
+
+* ``state`` - ``true`` to turn on, ``false`` to turn off
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setLightLevel
+^^^^^^^^^^^^^
+
+Sets only the brightness level (0-100) without changing the on/off state.
+
+.. code-block:: arduino
+
+    bool setLightLevel(uint8_t level);
+
+* ``level`` - Brightness level (0-100, where 0 is off, 100 is full brightness)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setLight
+^^^^^^^^
+
+Sets both the light state and brightness level simultaneously.
+
+.. code-block:: arduino
+
+    bool setLight(bool state, uint8_t level);
+
+* ``state`` - ``true`` to turn on, ``false`` to turn off
+* ``level`` - Brightness level (0-100)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+getLightState
+^^^^^^^^^^^^^
+
+Gets the current light state.
+
+.. code-block:: arduino
+
+    bool getLightState();
+
+This function will return current light state (``true`` = on, ``false`` = off).
+
+getLightLevel
+^^^^^^^^^^^^^
+
+Gets the current brightness level.
+
+.. code-block:: arduino
+
+    uint8_t getLightLevel();
+
+This function will return current brightness level (0-100).
+
+restoreLight
+^^^^^^^^^^^^
+
+Restores the light state and triggers any registered callbacks.
+
+.. code-block:: arduino
+
+    void restoreLight();
+
+Event Handling
+**************
+
+onLightChange
+^^^^^^^^^^^^^
+
+Sets a callback function to be called when the light state or level changes.
+
+.. code-block:: arduino
+
+    void onLightChange(void (*callback)(bool, uint8_t));
+
+* ``callback`` - Function to call when light state or level changes
+
+**Callback Parameters:**
+* ``bool state`` - New light state (true = on, false = off)
+* ``uint8_t level`` - New brightness level (0-100)
+
+Example
+-------
+
+Dimmable Light Implementation
+*****************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Dimmable_Light/Zigbee_Dimmable_Light.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_door_window_handle.rst b/docs/en/zigbee/ep_door_window_handle.rst
new file mode 100644
index 00000000000..53203f463dd
--- /dev/null
+++ b/docs/en/zigbee/ep_door_window_handle.rst
@@ -0,0 +1,95 @@
+######################
+ZigbeeDoorWindowHandle
+######################
+
+About
+-----
+
+The ``ZigbeeDoorWindowHandle`` class provides a door/window handle endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for handle position sensors and other handle-related devices.
+
+**Features:**
+* Handle position detection
+* Multiple position states support
+* Configurable application types
+* Automatic reporting capabilities
+
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeDoorWindowHandle
+^^^^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee door/window handle endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeDoorWindowHandle(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+API Methods
+***********
+
+setClosed
+^^^^^^^^^
+
+Sets the door/window handle to closed position.
+
+.. code-block:: arduino
+
+    bool setClosed();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setOpen
+^^^^^^^
+
+Sets the door/window handle to open position.
+
+.. code-block:: arduino
+
+    bool setOpen();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setTilted
+^^^^^^^^^
+
+Sets the door/window handle to tilted position.
+
+.. code-block:: arduino
+
+    bool setTilted();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setIASClientEndpoint
+^^^^^^^^^^^^^^^^^^^^
+
+Sets the IAS Client endpoint number (default is 1).
+
+.. code-block:: arduino
+
+    void setIASClientEndpoint(uint8_t ep_number);
+
+* ``ep_number`` - IAS Client endpoint number
+
+report
+^^^^^^
+
+Manually reports the current handle position.
+
+.. code-block:: arduino
+
+    bool report();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Example
+-------
+
+*To be added*
diff --git a/docs/en/zigbee/ep_electrical_measurement.rst b/docs/en/zigbee/ep_electrical_measurement.rst
new file mode 100644
index 00000000000..86410768484
--- /dev/null
+++ b/docs/en/zigbee/ep_electrical_measurement.rst
@@ -0,0 +1,254 @@
+###########################
+ZigbeeElectricalMeasurement
+###########################
+
+About
+-----
+
+The ``ZigbeeElectricalMeasurement`` class provides an endpoint for electrical measurement devices in Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for power monitoring and electrical measurement.
+
+**Features:**
+* AC and DC electrical measurements
+* Voltage, current, and power monitoring
+* Power factor measurement
+* Multi-phase support
+* Configurable measurement ranges
+* Automatic reporting capabilities
+* Integration with common endpoint features (binding, OTA, etc.)
+* Zigbee HA standard compliance
+
+**Use Cases:**
+* Smart power monitoring
+* Energy monitoring systems
+* Solar panel monitoring
+* Battery monitoring systems
+* Electrical load monitoring
+
+Common API
+----------
+
+Constructor
+***********
+
+ZigbeeElectricalMeasurement
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee electrical measurement endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeElectricalMeasurement(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+DC Electrical Measurement
+*************************
+
+addDCMeasurement
+^^^^^^^^^^^^^^^^
+
+Adds a DC measurement type to the endpoint.
+
+.. code-block:: arduino
+
+    bool addDCMeasurement(ZIGBEE_DC_MEASUREMENT_TYPE measurement_type);
+
+* ``measurement_type`` - DC measurement type constant (ZIGBEE_DC_MEASUREMENT_TYPE_VOLTAGE, ZIGBEE_DC_MEASUREMENT_TYPE_CURRENT, ZIGBEE_DC_MEASUREMENT_TYPE_POWER)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setDCMeasurement
+^^^^^^^^^^^^^^^^
+
+Sets the DC measurement value for a specific measurement type.
+
+.. code-block:: arduino
+
+    bool setDCMeasurement(ZIGBEE_DC_MEASUREMENT_TYPE measurement_type, int16_t value);
+
+* ``measurement_type`` - DC measurement type constant (ZIGBEE_DC_MEASUREMENT_TYPE_VOLTAGE, ZIGBEE_DC_MEASUREMENT_TYPE_CURRENT, ZIGBEE_DC_MEASUREMENT_TYPE_POWER)
+* ``value`` - Measurement value
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setDCMinMaxValue
+^^^^^^^^^^^^^^^^
+
+Sets the minimum and maximum values for a DC measurement type.
+
+.. code-block:: arduino
+
+    bool setDCMinMaxValue(ZIGBEE_DC_MEASUREMENT_TYPE measurement_type, int16_t min, int16_t max);
+
+* ``measurement_type`` - DC measurement type constant (ZIGBEE_DC_MEASUREMENT_TYPE_VOLTAGE, ZIGBEE_DC_MEASUREMENT_TYPE_CURRENT, ZIGBEE_DC_MEASUREMENT_TYPE_POWER)
+* ``min`` - Minimum value
+* ``max`` - Maximum value
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setDCMultiplierDivisor
+^^^^^^^^^^^^^^^^^^^^^^
+
+Sets the multiplier and divisor for scaling DC measurements.
+
+.. code-block:: arduino
+
+    bool setDCMultiplierDivisor(ZIGBEE_DC_MEASUREMENT_TYPE measurement_type, uint16_t multiplier, uint16_t divisor);
+
+* ``measurement_type`` - DC measurement type constant (ZIGBEE_DC_MEASUREMENT_TYPE_VOLTAGE, ZIGBEE_DC_MEASUREMENT_TYPE_CURRENT, ZIGBEE_DC_MEASUREMENT_TYPE_POWER)
+* ``multiplier`` - Multiplier value
+* ``divisor`` - Divisor value
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setDCReporting
+^^^^^^^^^^^^^^
+
+Sets the reporting configuration for DC measurements.
+
+.. code-block:: arduino
+
+    bool setDCReporting(ZIGBEE_DC_MEASUREMENT_TYPE measurement_type, uint16_t min_interval, uint16_t max_interval, int16_t delta);
+
+* ``measurement_type`` - DC measurement type constant (ZIGBEE_DC_MEASUREMENT_TYPE_VOLTAGE, ZIGBEE_DC_MEASUREMENT_TYPE_CURRENT, ZIGBEE_DC_MEASUREMENT_TYPE_POWER)
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change required to trigger a report
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+reportDC
+^^^^^^^^
+
+Manually reports a DC measurement value.
+
+.. code-block:: arduino
+
+    bool reportDC(ZIGBEE_DC_MEASUREMENT_TYPE measurement_type);
+
+* ``measurement_type`` - DC measurement type constant (ZIGBEE_DC_MEASUREMENT_TYPE_VOLTAGE, ZIGBEE_DC_MEASUREMENT_TYPE_CURRENT, ZIGBEE_DC_MEASUREMENT_TYPE_POWER)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+AC Electrical Measurement
+*************************
+
+addACMeasurement
+^^^^^^^^^^^^^^^^
+
+Adds an AC measurement type for a specific phase.
+
+.. code-block:: arduino
+
+    bool addACMeasurement(ZIGBEE_AC_MEASUREMENT_TYPE measurement_type, ZIGBEE_AC_PHASE_TYPE phase_type);
+
+* ``measurement_type`` - AC measurement type constant (ZIGBEE_AC_MEASUREMENT_TYPE_VOLTAGE, ZIGBEE_AC_MEASUREMENT_TYPE_CURRENT, ZIGBEE_AC_MEASUREMENT_TYPE_POWER, ZIGBEE_AC_MEASUREMENT_TYPE_POWER_FACTOR, ZIGBEE_AC_MEASUREMENT_TYPE_FREQUENCY)
+* ``phase_type`` - Phase type constant (ZIGBEE_AC_PHASE_TYPE_NON_SPECIFIC, ZIGBEE_AC_PHASE_TYPE_A, ZIGBEE_AC_PHASE_TYPE_B, ZIGBEE_AC_PHASE_TYPE_C)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setACMeasurement
+^^^^^^^^^^^^^^^^
+
+Sets the AC measurement value for a specific measurement type and phase.
+
+.. code-block:: arduino
+
+    bool setACMeasurement(ZIGBEE_AC_MEASUREMENT_TYPE measurement_type, ZIGBEE_AC_PHASE_TYPE phase_type, int32_t value);
+
+* ``measurement_type`` - AC measurement type constant (ZIGBEE_AC_MEASUREMENT_TYPE_VOLTAGE, ZIGBEE_AC_MEASUREMENT_TYPE_CURRENT, ZIGBEE_AC_MEASUREMENT_TYPE_POWER, ZIGBEE_AC_MEASUREMENT_TYPE_POWER_FACTOR, ZIGBEE_AC_MEASUREMENT_TYPE_FREQUENCY)
+* ``phase_type`` - Phase type constant (ZIGBEE_AC_PHASE_TYPE_NON_SPECIFIC, ZIGBEE_AC_PHASE_TYPE_A, ZIGBEE_AC_PHASE_TYPE_B, ZIGBEE_AC_PHASE_TYPE_C)
+* ``value`` - Measurement value
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setACMinMaxValue
+^^^^^^^^^^^^^^^^
+
+Sets the minimum and maximum values for an AC measurement type and phase.
+
+.. code-block:: arduino
+
+    bool setACMinMaxValue(ZIGBEE_AC_MEASUREMENT_TYPE measurement_type, ZIGBEE_AC_PHASE_TYPE phase_type, int32_t min, int32_t max);
+
+* ``measurement_type`` - AC measurement type constant (ZIGBEE_AC_MEASUREMENT_TYPE_VOLTAGE, ZIGBEE_AC_MEASUREMENT_TYPE_CURRENT, ZIGBEE_AC_MEASUREMENT_TYPE_POWER, ZIGBEE_AC_MEASUREMENT_TYPE_POWER_FACTOR, ZIGBEE_AC_MEASUREMENT_TYPE_FREQUENCY)
+* ``phase_type`` - Phase type constant (ZIGBEE_AC_PHASE_TYPE_NON_SPECIFIC, ZIGBEE_AC_PHASE_TYPE_A, ZIGBEE_AC_PHASE_TYPE_B, ZIGBEE_AC_PHASE_TYPE_C)
+* ``min`` - Minimum value
+* ``max`` - Maximum value
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setACMultiplierDivisor
+^^^^^^^^^^^^^^^^^^^^^^
+
+Sets the multiplier and divisor for scaling AC measurements.
+
+.. code-block:: arduino
+
+    bool setACMultiplierDivisor(ZIGBEE_AC_MEASUREMENT_TYPE measurement_type, uint16_t multiplier, uint16_t divisor);
+
+* ``measurement_type`` - AC measurement type constant (ZIGBEE_AC_MEASUREMENT_TYPE_VOLTAGE, ZIGBEE_AC_MEASUREMENT_TYPE_CURRENT, ZIGBEE_AC_MEASUREMENT_TYPE_POWER, ZIGBEE_AC_MEASUREMENT_TYPE_POWER_FACTOR, ZIGBEE_AC_MEASUREMENT_TYPE_FREQUENCY)
+* ``multiplier`` - Multiplier value
+* ``divisor`` - Divisor value
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setACPowerFactor
+^^^^^^^^^^^^^^^^
+
+Sets the power factor for a specific phase.
+
+.. code-block:: arduino
+
+    bool setACPowerFactor(ZIGBEE_AC_PHASE_TYPE phase_type, int8_t power_factor);
+
+* ``phase_type`` - Phase type constant (ZIGBEE_AC_PHASE_TYPE_NON_SPECIFIC, ZIGBEE_AC_PHASE_TYPE_A, ZIGBEE_AC_PHASE_TYPE_B, ZIGBEE_AC_PHASE_TYPE_C)
+* ``power_factor`` - Power factor value (-100 to 100)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setACReporting
+^^^^^^^^^^^^^^
+
+Sets the reporting configuration for AC measurements.
+
+.. code-block:: arduino
+
+    bool setACReporting(ZIGBEE_AC_MEASUREMENT_TYPE measurement_type, ZIGBEE_AC_PHASE_TYPE phase_type, uint16_t min_interval, uint16_t max_interval, int32_t delta);
+
+* ``measurement_type`` - AC measurement type constant (ZIGBEE_AC_MEASUREMENT_TYPE_VOLTAGE, ZIGBEE_AC_MEASUREMENT_TYPE_CURRENT, ZIGBEE_AC_MEASUREMENT_TYPE_POWER, ZIGBEE_AC_MEASUREMENT_TYPE_POWER_FACTOR, ZIGBEE_AC_MEASUREMENT_TYPE_FREQUENCY)
+* ``phase_type`` - Phase type constant (ZIGBEE_AC_PHASE_TYPE_NON_SPECIFIC, ZIGBEE_AC_PHASE_TYPE_A, ZIGBEE_AC_PHASE_TYPE_B, ZIGBEE_AC_PHASE_TYPE_C)
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change required to trigger a report
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+reportAC
+^^^^^^^^
+
+Manually reports an AC measurement value.
+
+.. code-block:: arduino
+
+    bool reportAC(ZIGBEE_AC_MEASUREMENT_TYPE measurement_type, ZIGBEE_AC_PHASE_TYPE phase_type);
+
+* ``measurement_type`` - AC measurement type constant (ZIGBEE_AC_MEASUREMENT_TYPE_VOLTAGE, ZIGBEE_AC_MEASUREMENT_TYPE_CURRENT, ZIGBEE_AC_MEASUREMENT_TYPE_POWER, ZIGBEE_AC_MEASUREMENT_TYPE_POWER_FACTOR, ZIGBEE_AC_MEASUREMENT_TYPE_FREQUENCY)
+* ``phase_type`` - Phase type constant (ZIGBEE_AC_PHASE_TYPE_NON_SPECIFIC, ZIGBEE_AC_PHASE_TYPE_A, ZIGBEE_AC_PHASE_TYPE_B, ZIGBEE_AC_PHASE_TYPE_C)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Example
+-------
+
+DC Electrical Measurement
+*************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Electrical_DC_Sensor/Zigbee_Electrical_DC_Sensor.ino
+    :language: arduino
+
+AC Electrical Measurement
+*************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Electrical_AC_Sensor_MultiPhase/Zigbee_Electrical_AC_Sensor_MultiPhase.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_flow_sensor.rst b/docs/en/zigbee/ep_flow_sensor.rst
new file mode 100644
index 00000000000..9423f321a5d
--- /dev/null
+++ b/docs/en/zigbee/ep_flow_sensor.rst
@@ -0,0 +1,119 @@
+################
+ZigbeeFlowSensor
+################
+
+About
+-----
+
+The ``ZigbeeFlowSensor`` class provides a flow sensor endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for liquid and gas flow measurement devices.
+
+**Features:**
+* Flow rate measurement in m³/h
+* Configurable measurement range
+* Tolerance and reporting configuration
+* Automatic reporting capabilities
+* Integration with common endpoint features (binding, OTA, etc.)
+* Zigbee HA standard compliance
+
+**Use Cases:**
+* Water flow monitoring
+* Gas flow measurement
+* Industrial process monitoring
+* Smart home water management
+* HVAC system flow monitoring
+* Agricultural irrigation systems
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeFlowSensor
+^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee flow sensor endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeFlowSensor(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+API Methods
+***********
+
+setFlow
+^^^^^^^
+
+Sets the flow rate measurement value.
+
+.. code-block:: arduino
+
+    bool setFlow(float value);
+
+* ``value`` - Flow rate value in 0.1 m³/h
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setMinMaxValue
+^^^^^^^^^^^^^^
+
+Sets the minimum and maximum measurement values.
+
+.. code-block:: arduino
+
+    bool setMinMaxValue(float min, float max);
+
+* ``min`` - Minimum flow rate value in 0.1 m³/h
+* ``max`` - Maximum flow rate value in 0.1 m³/h
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setTolerance
+^^^^^^^^^^^^
+
+Sets the tolerance value for measurements.
+
+.. code-block:: arduino
+
+    bool setTolerance(float tolerance);
+
+* ``tolerance`` - Tolerance value in 0.01 m³/h
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setReporting
+^^^^^^^^^^^^
+
+Sets the reporting configuration for flow rate measurements.
+
+.. code-block:: arduino
+
+    bool setReporting(uint16_t min_interval, uint16_t max_interval, float delta);
+
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change required to trigger a report in 0.1 m³/h
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+report
+^^^^^^
+
+Manually reports the current flow rate value.
+
+.. code-block:: arduino
+
+    bool report();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Example
+-------
+
+Flow + PressureSensor Implementation
+************************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Pressure_Flow_Sensor/Zigbee_Pressure_Flow_Sensor.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_gateway.rst b/docs/en/zigbee/ep_gateway.rst
new file mode 100644
index 00000000000..d436887a373
--- /dev/null
+++ b/docs/en/zigbee/ep_gateway.rst
@@ -0,0 +1,35 @@
+#############
+ZigbeeGateway
+#############
+
+About
+-----
+
+The ``ZigbeeGateway`` class provides a gateway endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for network coordination and gateway functionality.
+Gateway is a device that can be used to bridge Zigbee network to other networks (e.g. Wi-Fi, Ethernet, etc.).
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeGateway
+^^^^^^^^^^^^^
+
+Creates a new Zigbee gateway endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeGateway(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Example
+-------
+
+Gateway Implementation
+**********************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Gateway/Zigbee_Gateway.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_illuminance_sensor.rst b/docs/en/zigbee/ep_illuminance_sensor.rst
new file mode 100644
index 00000000000..1e627f7dfe9
--- /dev/null
+++ b/docs/en/zigbee/ep_illuminance_sensor.rst
@@ -0,0 +1,109 @@
+#######################
+ZigbeeIlluminanceSensor
+#######################
+
+About
+-----
+
+The ``ZigbeeIlluminanceSensor`` class provides an endpoint for illuminance sensors in Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for light level measurement devices, supporting ambient light monitoring.
+
+**Features:**
+* Illuminance measurement in lux
+* Configurable measurement range
+* Tolerance and reporting configuration
+* Automatic reporting capabilities
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeIlluminanceSensor
+^^^^^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee illuminance sensor endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeIlluminanceSensor(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+API Methods
+***********
+
+setIlluminance
+^^^^^^^^^^^^^^
+
+Sets the illuminance measurement value.
+
+.. code-block:: arduino
+
+    bool setIlluminance(uint16_t value);
+
+* ``value`` - Illuminance value in lux
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setMinMaxValue
+^^^^^^^^^^^^^^
+
+Sets the minimum and maximum measurement values.
+
+.. code-block:: arduino
+
+    bool setMinMaxValue(uint16_t min, uint16_t max);
+
+* ``min`` - Minimum illuminance value in lux
+* ``max`` - Maximum illuminance value in lux
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setTolerance
+^^^^^^^^^^^^
+
+Sets the tolerance value for measurements.
+
+.. code-block:: arduino
+
+    bool setTolerance(uint16_t tolerance);
+
+* ``tolerance`` - Tolerance value in lux
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setReporting
+^^^^^^^^^^^^
+
+Sets the reporting configuration for illuminance measurements.
+
+.. code-block:: arduino
+
+    bool setReporting(uint16_t min_interval, uint16_t max_interval, uint16_t delta);
+
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change required to trigger a report in lux
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+report
+^^^^^^
+
+Manually reports the current illuminance value.
+
+.. code-block:: arduino
+
+    bool report();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Example
+-------
+
+Illuminance Sensor Implementation
+*********************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Illuminance_Sensor/Zigbee_Illuminance_Sensor.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_light.rst b/docs/en/zigbee/ep_light.rst
new file mode 100644
index 00000000000..fb70320321b
--- /dev/null
+++ b/docs/en/zigbee/ep_light.rst
@@ -0,0 +1,88 @@
+###########
+ZigbeeLight
+###########
+
+About
+-----
+
+The ``ZigbeeLight`` class provides a simple on/off light endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for basic lighting control.
+
+**Features:**
+* Simple on/off control
+* State change callbacks
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeLight
+^^^^^^^^^^^
+
+Creates a new Zigbee light endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeLight(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Light Control
+*************
+
+setLight
+^^^^^^^^
+
+Sets the light state (on or off).
+
+.. code-block:: arduino
+
+    bool setLight(bool state);
+
+* ``state`` - ``true`` to turn on, ``false`` to turn off
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+getLightState
+^^^^^^^^^^^^^
+
+Gets the current light state.
+
+.. code-block:: arduino
+
+    bool getLightState();
+
+This function will return current light state (``true`` = on, ``false`` = off).
+
+restoreLight
+^^^^^^^^^^^^
+
+Restores the light state and triggers any registered callbacks.
+
+.. code-block:: arduino
+
+    void restoreLight();
+
+Event Handling
+**************
+
+onLightChange
+^^^^^^^^^^^^^
+
+Sets a callback function to be called when the light state changes.
+
+.. code-block:: arduino
+
+    void onLightChange(void (*callback)(bool));
+
+* ``callback`` - Function to call when light state changes
+
+Example
+-------
+
+Basic Light Implementation
+**************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_On_Off_Light/Zigbee_On_Off_Light.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_occupancy_sensor.rst b/docs/en/zigbee/ep_occupancy_sensor.rst
new file mode 100644
index 00000000000..7fe50d59ea4
--- /dev/null
+++ b/docs/en/zigbee/ep_occupancy_sensor.rst
@@ -0,0 +1,81 @@
+#####################
+ZigbeeOccupancySensor
+#####################
+
+About
+-----
+
+The ``ZigbeeOccupancySensor`` class provides an endpoint for occupancy sensors in Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for occupancy detection devices, supporting various sensor types for detecting presence.
+
+**Features:**
+* Occupancy detection (occupied/unoccupied)
+* Multiple sensor type support (PIR, ultrasonic, etc.)
+* Automatic reporting capabilities
+* Integration with common endpoint features (binding, OTA, etc.)
+* Zigbee HA standard compliance
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeOccupancySensor
+^^^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee occupancy sensor endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeOccupancySensor(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+API Methods
+***********
+
+setOccupancy
+^^^^^^^^^^^^
+
+Sets the occupancy state.
+
+.. code-block:: arduino
+
+    bool setOccupancy(bool occupied);
+
+* ``occupied`` - Occupancy state (true = occupied, false = unoccupied)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setSensorType
+^^^^^^^^^^^^^
+
+Sets the sensor type.
+
+.. code-block:: arduino
+
+    bool setSensorType(uint8_t sensor_type);
+
+* ``sensor_type`` - Sensor type identifier (see esp_zb_zcl_occupancy_sensing_occupancy_sensor_type_t)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+report
+^^^^^^
+
+Manually reports the current occupancy state.
+
+.. code-block:: arduino
+
+    bool report();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Example
+-------
+
+Occupancy Sensor Implementation
+*******************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Occupancy_Sensor/Zigbee_Occupancy_Sensor.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_pm25_sensor.rst b/docs/en/zigbee/ep_pm25_sensor.rst
new file mode 100644
index 00000000000..2f1432f8224
--- /dev/null
+++ b/docs/en/zigbee/ep_pm25_sensor.rst
@@ -0,0 +1,109 @@
+################
+ZigbeePM25Sensor
+################
+
+About
+-----
+
+The ``ZigbeePM25Sensor`` class provides a PM2.5 air quality sensor endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for particulate matter measurement devices.
+
+**Features:**
+* PM2.5 concentration measurement in μg/m³
+* Configurable measurement range
+* Tolerance and reporting configuration
+* Automatic reporting capabilities
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeePM25Sensor
+^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee PM2.5 sensor endpoint.
+
+.. code-block:: arduino
+
+    ZigbeePM25Sensor(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+API Methods
+***********
+
+setPM25
+^^^^^^^
+
+Sets the PM2.5 concentration measurement value.
+
+.. code-block:: arduino
+
+    bool setPM25(float pm25);
+
+* ``pm25`` - PM2.5 concentration value in 0.1 μg/m³
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setMinMaxValue
+^^^^^^^^^^^^^^
+
+Sets the minimum and maximum measurement values.
+
+.. code-block:: arduino
+
+    bool setMinMaxValue(float min, float max);
+
+* ``min`` - Minimum PM2.5 concentration value in 0.1 μg/m³
+* ``max`` - Maximum PM2.5 concentration value in 0.1 μg/m³
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setTolerance
+^^^^^^^^^^^^
+
+Sets the tolerance value for measurements.
+
+.. code-block:: arduino
+
+    bool setTolerance(float tolerance);
+
+* ``tolerance`` - Tolerance value in 0.1 μg/m³
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setReporting
+^^^^^^^^^^^^
+
+Sets the reporting configuration for PM2.5 measurements.
+
+.. code-block:: arduino
+
+    bool setReporting(uint16_t min_interval, uint16_t max_interval, float delta);
+
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change required to trigger a report in 0.1 μg/m³
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+report
+^^^^^^
+
+Manually reports the current PM2.5 concentration value.
+
+.. code-block:: arduino
+
+    bool report();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Example
+-------
+
+PM2.5 Sensor Implementation
+***************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_PM25_Sensor/Zigbee_PM25_Sensor.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_power_outlet.rst b/docs/en/zigbee/ep_power_outlet.rst
new file mode 100644
index 00000000000..97b22cbbc2a
--- /dev/null
+++ b/docs/en/zigbee/ep_power_outlet.rst
@@ -0,0 +1,88 @@
+#################
+ZigbeePowerOutlet
+#################
+
+About
+-----
+
+The ``ZigbeePowerOutlet`` class provides a smart power outlet endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for power control, allowing remote on/off control of electrical devices.
+
+**Features:**
+* On/off power control
+* State change callbacks
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeePowerOutlet
+^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee power outlet endpoint.
+
+.. code-block:: arduino
+
+    ZigbeePowerOutlet(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Power Control
+*************
+
+setState
+^^^^^^^^
+
+Sets the power outlet state (on or off).
+
+.. code-block:: arduino
+
+    bool setState(bool state);
+
+* ``state`` - ``true`` to turn on, ``false`` to turn off
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+getPowerOutletState
+^^^^^^^^^^^^^^^^^^^
+
+Gets the current power outlet state.
+
+.. code-block:: arduino
+
+    bool getPowerOutletState();
+
+This function will return current power state (``true`` = on, ``false`` = off).
+
+restoreState
+^^^^^^^^^^^^
+
+Restores the power outlet state and triggers any registered callbacks.
+
+.. code-block:: arduino
+
+    void restoreState();
+
+Event Handling
+**************
+
+onPowerOutletChange
+^^^^^^^^^^^^^^^^^^^
+
+Sets a callback function to be called when the power outlet state changes.
+
+.. code-block:: arduino
+
+    void onPowerOutletChange(void (*callback)(bool));
+
+* ``callback`` - Function to call when power outlet state changes
+
+Example
+-------
+
+Smart Power Outlet Implementation
+*********************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Power_Outlet/Zigbee_Power_Outlet.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_pressure_sensor.rst b/docs/en/zigbee/ep_pressure_sensor.rst
new file mode 100644
index 00000000000..5d857bb163e
--- /dev/null
+++ b/docs/en/zigbee/ep_pressure_sensor.rst
@@ -0,0 +1,109 @@
+####################
+ZigbeePressureSensor
+####################
+
+About
+-----
+
+The ``ZigbeePressureSensor`` class provides an endpoint for pressure sensors in Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for pressure measurement devices, supporting atmospheric pressure, barometric pressure, and other pressure measurements.
+
+**Features:**
+* Pressure measurement in hPa (hectopascals)
+* Configurable measurement range
+* Tolerance and reporting configuration
+* Automatic reporting capabilities
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeePressureSensor
+^^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee pressure sensor endpoint.
+
+.. code-block:: arduino
+
+    ZigbeePressureSensor(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+API Methods
+***********
+
+setPressure
+^^^^^^^^^^^
+
+Sets the pressure measurement value.
+
+.. code-block:: arduino
+
+    bool setPressure(int16_t value);
+
+* ``value`` - Pressure value in hPa
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setMinMaxValue
+^^^^^^^^^^^^^^
+
+Sets the minimum and maximum measurement values.
+
+.. code-block:: arduino
+
+    bool setMinMaxValue(int16_t min, int16_t max);
+
+* ``min`` - Minimum pressure value in hPa
+* ``max`` - Maximum pressure value in hPa
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setTolerance
+^^^^^^^^^^^^
+
+Sets the tolerance value for measurements.
+
+.. code-block:: arduino
+
+    bool setTolerance(uint16_t tolerance);
+
+* ``tolerance`` - Tolerance value in hPa
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setReporting
+^^^^^^^^^^^^
+
+Sets the reporting configuration for pressure measurements.
+
+.. code-block:: arduino
+
+    bool setReporting(uint16_t min_interval, uint16_t max_interval, uint16_t delta);
+
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change required to trigger a report in hPa
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+report
+^^^^^^
+
+Manually reports the current pressure value.
+
+.. code-block:: arduino
+
+    bool report();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Example
+-------
+
+Pressure + Flow Sensor Implementation
+*************************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Pressure_Flow_Sensor/Zigbee_Pressure_Flow_Sensor.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_range_extender.rst b/docs/en/zigbee/ep_range_extender.rst
new file mode 100644
index 00000000000..b451f8764fc
--- /dev/null
+++ b/docs/en/zigbee/ep_range_extender.rst
@@ -0,0 +1,34 @@
+###################
+ZigbeeRangeExtender
+###################
+
+About
+-----
+
+The ``ZigbeeRangeExtender`` class provides a range extender endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for range extender devices that help extend the coverage of Zigbee networks by acting as repeaters.
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeRangeExtender
+^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee range extender endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeRangeExtender(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Example
+-------
+
+Range Extender Implementation
+*****************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Range_Extender/Zigbee_Range_Extender.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_switch.rst b/docs/en/zigbee/ep_switch.rst
new file mode 100644
index 00000000000..e1847996cc2
--- /dev/null
+++ b/docs/en/zigbee/ep_switch.rst
@@ -0,0 +1,136 @@
+############
+ZigbeeSwitch
+############
+
+About
+-----
+
+The ``ZigbeeSwitch`` class provides a switch endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for controlling other devices (typically lights) through on/off commands.
+
+**Features:**
+* On/off control commands for bound devices
+* Group control support
+* Direct device addressing
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeSwitch
+^^^^^^^^^^^^
+
+Creates a new Zigbee switch endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeSwitch(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Basic Control Commands
+**********************
+
+lightToggle
+^^^^^^^^^^^
+
+Toggles the state of bound lights (on to off, or off to on).
+
+.. code-block:: arduino
+
+    void lightToggle();
+    void lightToggle(uint16_t group_addr);
+    void lightToggle(uint8_t endpoint, uint16_t short_addr);
+    void lightToggle(uint8_t endpoint, esp_zb_ieee_addr_t ieee_addr);
+
+* ``group_addr`` - Group address to control (optional)
+* ``endpoint`` - Target device endpoint (optional)
+* ``short_addr`` - Target device short address (optional)
+* ``ieee_addr`` - Target device IEEE address (optional)
+
+lightOn
+^^^^^^^
+
+Turns on bound lights.
+
+.. code-block:: arduino
+
+    void lightOn();
+    void lightOn(uint16_t group_addr);
+    void lightOn(uint8_t endpoint, uint16_t short_addr);
+    void lightOn(uint8_t endpoint, esp_zb_ieee_addr_t ieee_addr);
+
+* ``group_addr`` - Group address to control (optional)
+* ``endpoint`` - Target device endpoint (optional)
+* ``short_addr`` - Target device short address (optional)
+* ``ieee_addr`` - Target device IEEE address (optional)
+
+lightOff
+^^^^^^^^
+
+Turns off bound lights.
+
+.. code-block:: arduino
+
+    void lightOff();
+    void lightOff(uint16_t group_addr);
+    void lightOff(uint8_t endpoint, uint16_t short_addr);
+    void lightOff(uint8_t endpoint, esp_zb_ieee_addr_t ieee_addr);
+
+* ``group_addr`` - Group address to control (optional)
+* ``endpoint`` - Target device endpoint (optional)
+* ``short_addr`` - Target device short address (optional)
+* ``ieee_addr`` - Target device IEEE address (optional)
+
+Advanced Control Commands
+*************************
+
+lightOffWithEffect
+^^^^^^^^^^^^^^^^^^
+
+Turns off lights with a specific effect.
+
+.. code-block:: arduino
+
+    void lightOffWithEffect(uint8_t effect_id, uint8_t effect_variant);
+
+* ``effect_id`` - Effect identifier
+* ``effect_variant`` - Effect variant
+
+lightOnWithTimedOff
+^^^^^^^^^^^^^^^^^^^
+
+Turns on lights with automatic turn-off after specified time.
+
+.. code-block:: arduino
+
+    void lightOnWithTimedOff(uint8_t on_off_control, uint16_t time_on, uint16_t time_off);
+
+* ``on_off_control`` - Control byte
+* ``time_on`` - Time to stay on (in 1/10th seconds)
+* ``time_off`` - Time to stay off (in 1/10th seconds)
+
+lightOnWithSceneRecall
+^^^^^^^^^^^^^^^^^^^^^^
+
+Turns on lights by recalling a scene.
+
+.. code-block:: arduino
+
+    void lightOnWithSceneRecall();
+
+Example
+-------
+
+Basic Switch Implementation
+***************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_On_Off_Switch/Zigbee_On_Off_Switch.ino
+    :language: arduino
+
+Multi Switch Implementation
+***************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_On_Off_MultiSwitch/Zigbee_On_Off_MultiSwitch.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_temperature_sensor.rst b/docs/en/zigbee/ep_temperature_sensor.rst
new file mode 100644
index 00000000000..85c2147f1a1
--- /dev/null
+++ b/docs/en/zigbee/ep_temperature_sensor.rst
@@ -0,0 +1,184 @@
+################
+ZigbeeTempSensor
+################
+
+About
+-----
+
+The ``ZigbeeTempSensor`` class provides a temperature and humidity sensor endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for environmental monitoring with configurable reporting intervals and thresholds.
+
+**Features:**
+* Temperature measurement and reporting
+* Optional humidity measurement
+* Configurable reporting intervals
+* Min/max value and tolerance settings
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeTempSensor
+^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee temperature sensor endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeTempSensor(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Temperature Control
+*******************
+
+setTemperature
+^^^^^^^^^^^^^^
+
+Sets the temperature value in 0.01°C resolution.
+
+.. code-block:: arduino
+
+    bool setTemperature(float value);
+
+* ``value`` - Temperature value in degrees Celsius
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setMinMaxValue
+^^^^^^^^^^^^^^
+
+Sets the minimum and maximum temperature values for the sensor.
+
+.. code-block:: arduino
+
+    bool setMinMaxValue(float min, float max);
+
+* ``min`` - Minimum temperature value in degrees Celsius
+* ``max`` - Maximum temperature value in degrees Celsius
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setTolerance
+^^^^^^^^^^^^
+
+Sets the tolerance value for temperature reporting.
+
+.. code-block:: arduino
+
+    bool setTolerance(float tolerance);
+
+* ``tolerance`` - Tolerance value in degrees Celsius
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setReporting
+^^^^^^^^^^^^
+
+Sets the reporting interval for temperature measurements.
+
+.. code-block:: arduino
+
+    bool setReporting(uint16_t min_interval, uint16_t max_interval, float delta);
+
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change in temperature to trigger report (in 0.01°C)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+reportTemperature
+^^^^^^^^^^^^^^^^^
+
+Manually reports the current temperature value.
+
+.. code-block:: arduino
+
+    bool reportTemperature();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Humidity Control (Optional)
+***************************
+
+addHumiditySensor
+^^^^^^^^^^^^^^^^^
+
+Adds humidity measurement capability to the temperature sensor.
+
+.. code-block:: arduino
+
+    void addHumiditySensor(float min, float max, float tolerance);
+
+* ``min`` - Minimum humidity value in percentage
+* ``max`` - Maximum humidity value in percentage
+* ``tolerance`` - Tolerance value in percentage
+
+setHumidity
+^^^^^^^^^^^
+
+Sets the humidity value in 0.01% resolution.
+
+.. code-block:: arduino
+
+    bool setHumidity(float value);
+
+* ``value`` - Humidity value in percentage (0-100)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setHumidityReporting
+^^^^^^^^^^^^^^^^^^^^
+
+Sets the reporting interval for humidity measurements.
+
+.. code-block:: arduino
+
+    bool setHumidityReporting(uint16_t min_interval, uint16_t max_interval, float delta);
+
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change in humidity to trigger report (in 0.01%)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+reportHumidity
+^^^^^^^^^^^^^^
+
+Manually reports the current humidity value.
+
+.. code-block:: arduino
+
+    bool reportHumidity();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Combined Reporting
+******************
+
+report
+^^^^^^
+
+Reports both temperature and humidity values if humidity sensor is enabled.
+
+.. code-block:: arduino
+
+    bool report();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Example
+-------
+
+Temperature Sensor Implementation
+*********************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Temperature_Sensor/Zigbee_Temperature_Sensor.ino
+    :language: arduino
+
+Temperature + Humidity Sleepy Sensor Implementation
+***************************************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Temp_Hum_Sensor_Sleepy/Zigbee_Temp_Hum_Sensor_Sleepy.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_thermostat.rst b/docs/en/zigbee/ep_thermostat.rst
new file mode 100644
index 00000000000..b7c79254d0f
--- /dev/null
+++ b/docs/en/zigbee/ep_thermostat.rst
@@ -0,0 +1,238 @@
+################
+ZigbeeThermostat
+################
+
+About
+-----
+
+The ``ZigbeeThermostat`` class provides a thermostat endpoint for Zigbee networks that receives temperature data from temperature sensors. This endpoint implements the Zigbee Home Automation (HA) standard for thermostats that can bind to temperature sensors and receive temperature readings.
+
+**Features:**
+* Automatic discovery and binding to temperature sensors
+* Temperature data reception from bound sensors
+* Configurable temperature reporting intervals
+* Sensor settings retrieval (min/max temperature, tolerance)
+* Multiple addressing modes (group, specific endpoint, IEEE address)
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeThermostat
+^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee thermostat endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeThermostat(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Event Handling
+**************
+
+onTempReceive
+^^^^^^^^^^^^^
+
+Sets a callback function for receiving temperature data.
+
+.. code-block:: arduino
+
+    void onTempReceive(void (*callback)(float temperature));
+
+* ``callback`` - Function to call when temperature data is received
+* ``temperature`` - Temperature value in degrees Celsius
+
+onTempReceiveWithSource
+^^^^^^^^^^^^^^^^^^^^^^^
+
+Sets a callback function for receiving temperature data with source information.
+
+.. code-block:: arduino
+
+    void onTempReceiveWithSource(void (*callback)(float temperature, uint8_t src_endpoint, esp_zb_zcl_addr_t src_address));
+
+* ``callback`` - Function to call when temperature data is received
+* ``temperature`` - Temperature value in degrees Celsius
+* ``src_endpoint`` - Source endpoint that sent the temperature data
+* ``src_address`` - Source address information
+
+onConfigReceive
+^^^^^^^^^^^^^^^
+
+Sets a callback function for receiving sensor configuration data.
+
+.. code-block:: arduino
+
+    void onConfigReceive(void (*callback)(float min_temp, float max_temp, float tolerance));
+
+* ``callback`` - Function to call when sensor configuration is received
+* ``min_temp`` - Minimum temperature supported by the sensor
+* ``max_temp`` - Maximum temperature supported by the sensor
+* ``tolerance`` - Temperature tolerance of the sensor
+
+Temperature Data Retrieval
+**************************
+
+getTemperature
+^^^^^^^^^^^^^^
+
+Requests temperature data from all bound sensors.
+
+.. code-block:: arduino
+
+    void getTemperature();
+
+getTemperature (Group)
+^^^^^^^^^^^^^^^^^^^^^^
+
+Requests temperature data from a specific group.
+
+.. code-block:: arduino
+
+    void getTemperature(uint16_t group_addr);
+
+* ``group_addr`` - Group address to send the request to
+
+getTemperature (Endpoint + Short Address)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Requests temperature data from a specific endpoint using short address.
+
+.. code-block:: arduino
+
+    void getTemperature(uint8_t endpoint, uint16_t short_addr);
+
+* ``endpoint`` - Target endpoint number
+* ``short_addr`` - Short address of the target device
+
+getTemperature (Endpoint + IEEE Address)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Requests temperature data from a specific endpoint using IEEE address.
+
+.. code-block:: arduino
+
+    void getTemperature(uint8_t endpoint, esp_zb_ieee_addr_t ieee_addr);
+
+* ``endpoint`` - Target endpoint number
+* ``ieee_addr`` - IEEE address of the target device
+
+Sensor Settings Retrieval
+*************************
+
+getSensorSettings
+^^^^^^^^^^^^^^^^^
+
+Requests sensor settings from all bound sensors.
+
+.. code-block:: arduino
+
+    void getSensorSettings();
+
+getSensorSettings (Group)
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Requests sensor settings from a specific group.
+
+.. code-block:: arduino
+
+    void getSensorSettings(uint16_t group_addr);
+
+* ``group_addr`` - Group address to send the request to
+
+getSensorSettings (Endpoint + Short Address)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Requests sensor settings from a specific endpoint using short address.
+
+.. code-block:: arduino
+
+    void getSensorSettings(uint8_t endpoint, uint16_t short_addr);
+
+* ``endpoint`` - Target endpoint number
+* ``short_addr`` - Short address of the target device
+
+getSensorSettings (Endpoint + IEEE Address)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Requests sensor settings from a specific endpoint using IEEE address.
+
+.. code-block:: arduino
+
+    void getSensorSettings(uint8_t endpoint, esp_zb_ieee_addr_t ieee_addr);
+
+* ``endpoint`` - Target endpoint number
+* ``ieee_addr`` - IEEE address of the target device
+
+Temperature Reporting Configuration
+***********************************
+
+setTemperatureReporting
+^^^^^^^^^^^^^^^^^^^^^^^
+
+Configures temperature reporting for all bound sensors.
+
+.. code-block:: arduino
+
+    void setTemperatureReporting(uint16_t min_interval, uint16_t max_interval, float delta);
+
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change in temperature to trigger a report
+
+setTemperatureReporting (Group)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Configures temperature reporting for a specific group.
+
+.. code-block:: arduino
+
+    void setTemperatureReporting(uint16_t group_addr, uint16_t min_interval, uint16_t max_interval, float delta);
+
+* ``group_addr`` - Group address to configure
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change in temperature to trigger a report
+
+setTemperatureReporting (Endpoint + Short Address)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Configures temperature reporting for a specific endpoint using short address.
+
+.. code-block:: arduino
+
+    void setTemperatureReporting(uint8_t endpoint, uint16_t short_addr, uint16_t min_interval, uint16_t max_interval, float delta);
+
+* ``endpoint`` - Target endpoint number
+* ``short_addr`` - Short address of the target device
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change in temperature to trigger a report
+
+setTemperatureReporting (Endpoint + IEEE Address)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Configures temperature reporting for a specific endpoint using IEEE address.
+
+.. code-block:: arduino
+
+    void setTemperatureReporting(uint8_t endpoint, esp_zb_ieee_addr_t ieee_addr, uint16_t min_interval, uint16_t max_interval, float delta);
+
+* ``endpoint`` - Target endpoint number
+* ``ieee_addr`` - IEEE address of the target device
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change in temperature to trigger a report
+
+Example
+-------
+
+Thermostat Implementation
+*************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Thermostat/Zigbee_Thermostat.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_vibration_sensor.rst b/docs/en/zigbee/ep_vibration_sensor.rst
new file mode 100644
index 00000000000..896c4672c6d
--- /dev/null
+++ b/docs/en/zigbee/ep_vibration_sensor.rst
@@ -0,0 +1,87 @@
+#####################
+ZigbeeVibrationSensor
+#####################
+
+About
+-----
+
+The ``ZigbeeVibrationSensor`` class provides a vibration sensor endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for vibration detection devices.
+
+**Features:**
+* Vibration detection and measurement
+* Configurable sensitivity levels
+* Multiple detection modes
+* Automatic reporting capabilities
+* Integration with common endpoint features (binding, OTA, etc.)
+* Zigbee HA standard compliance
+
+**Use Cases:**
+* Security system vibration detection
+* Industrial equipment monitoring
+* Structural health monitoring
+* Smart home security applications
+* Machine condition monitoring
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeVibrationSensor
+^^^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee vibration sensor endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeVibrationSensor(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+API Methods
+***********
+
+setVibration
+^^^^^^^^^^^^
+
+Sets the vibration detection state.
+
+.. code-block:: arduino
+
+    bool setVibration(bool sensed);
+
+* ``sensed`` - Vibration state (true = sensed, false = not sensed)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setIASClientEndpoint
+^^^^^^^^^^^^^^^^^^^^
+
+Sets the IAS Client endpoint number (default is 1).
+
+.. code-block:: arduino
+
+    void setIASClientEndpoint(uint8_t ep_number);
+
+* ``ep_number`` - IAS Client endpoint number
+
+report
+^^^^^^
+
+Manually reports the current vibration state.
+
+.. code-block:: arduino
+
+    void report();
+
+This function does not return a value.
+
+Example
+-------
+
+Vibration Sensor Implementation
+*******************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Vibration_Sensor/Zigbee_Vibration_Sensor.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_wind_speed_sensor.rst b/docs/en/zigbee/ep_wind_speed_sensor.rst
new file mode 100644
index 00000000000..67c4958e37c
--- /dev/null
+++ b/docs/en/zigbee/ep_wind_speed_sensor.rst
@@ -0,0 +1,119 @@
+#####################
+ZigbeeWindSpeedSensor
+#####################
+
+About
+-----
+
+The ``ZigbeeWindSpeedSensor`` class provides a wind speed sensor endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for wind speed measurement devices.
+
+**Features:**
+* Wind speed measurement in m/s
+* Configurable measurement range
+* Tolerance and reporting configuration
+* Automatic reporting capabilities
+* Integration with common endpoint features (binding, OTA, etc.)
+* Zigbee HA standard compliance
+
+**Use Cases:**
+* Weather stations
+* Wind turbine monitoring
+* Agricultural weather monitoring
+* Marine applications
+* Smart home weather systems
+* Industrial wind monitoring
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeWindSpeedSensor
+^^^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee wind speed sensor endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeWindSpeedSensor(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+API Methods
+***********
+
+setWindSpeed
+^^^^^^^^^^^^
+
+Sets the wind speed measurement value.
+
+.. code-block:: arduino
+
+    bool setWindSpeed(float value);
+
+* ``value`` - Wind speed value in 0.01 m/s
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setMinMaxValue
+^^^^^^^^^^^^^^
+
+Sets the minimum and maximum measurement values.
+
+.. code-block:: arduino
+
+    bool setMinMaxValue(float min, float max);
+
+* ``min`` - Minimum wind speed value in 0.01 m/s
+* ``max`` - Maximum wind speed value in 0.01 m/s
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setTolerance
+^^^^^^^^^^^^
+
+Sets the tolerance value for measurements.
+
+.. code-block:: arduino
+
+    bool setTolerance(float tolerance);
+
+* ``tolerance`` - Tolerance value in 0.01 m/s
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setReporting
+^^^^^^^^^^^^
+
+Sets the reporting configuration for wind speed measurements.
+
+.. code-block:: arduino
+
+    bool setReporting(uint16_t min_interval, uint16_t max_interval, float delta);
+
+* ``min_interval`` - Minimum reporting interval in seconds
+* ``max_interval`` - Maximum reporting interval in seconds
+* ``delta`` - Minimum change required to trigger a report in 0.01 m/s
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+reportWindSpeed
+^^^^^^^^^^^^^^^
+
+Manually reports the current wind speed value.
+
+.. code-block:: arduino
+
+    bool reportWindSpeed();
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Example
+-------
+
+Wind Speed Sensor Implementation
+********************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Wind_Speed_Sensor/Zigbee_Wind_Speed_Sensor.ino
+    :language: arduino
diff --git a/docs/en/zigbee/ep_window_covering.rst b/docs/en/zigbee/ep_window_covering.rst
new file mode 100644
index 00000000000..a4b8cd918a6
--- /dev/null
+++ b/docs/en/zigbee/ep_window_covering.rst
@@ -0,0 +1,233 @@
+####################
+ZigbeeWindowCovering
+####################
+
+About
+-----
+
+The ``ZigbeeWindowCovering`` class provides a window covering endpoint for Zigbee networks. This endpoint implements the Zigbee Home Automation (HA) standard for motorized blinds, shades, and other window coverings.
+
+**Features:**
+* Position control (lift and tilt)
+* Multiple window covering types support
+* Configurable operation modes and limits
+* Status reporting and callbacks
+* Safety features and limits
+
+**Supported Window Covering Types:**
+* ROLLERSHADE - Lift support
+* ROLLERSHADE_2_MOTOR - Lift support
+* ROLLERSHADE_EXTERIOR - Lift support
+* ROLLERSHADE_EXTERIOR_2_MOTOR - Lift support
+* DRAPERY - Lift support
+* AWNING - Lift support
+* SHUTTER - Tilt support
+* BLIND_TILT_ONLY - Tilt support
+* BLIND_LIFT_AND_TILT - Lift and Tilt support
+* PROJECTOR_SCREEN - Lift support
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeWindowCovering
+^^^^^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee window covering endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeWindowCovering(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Position Control
+****************
+
+setLiftPosition
+^^^^^^^^^^^^^^^
+
+Sets the window covering lift position.
+
+.. code-block:: arduino
+
+    bool setLiftPosition(uint16_t lift_position);
+
+* ``lift_position`` - Lift position
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setLiftPercentage
+^^^^^^^^^^^^^^^^^
+
+Sets the window covering lift position as a percentage.
+
+.. code-block:: arduino
+
+    bool setLiftPercentage(uint8_t lift_percentage);
+
+* ``lift_percentage`` - Lift percentage (0-100, where 0 is fully closed, 100 is fully open)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setTiltPosition
+^^^^^^^^^^^^^^^
+
+Sets the window covering tilt position in degrees.
+
+.. code-block:: arduino
+
+    bool setTiltPosition(uint16_t tilt_position);
+
+* ``tilt_position`` - Tilt position in degrees
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setTiltPercentage
+^^^^^^^^^^^^^^^^^
+
+Sets the window covering tilt position as a percentage.
+
+.. code-block:: arduino
+
+    bool setTiltPercentage(uint8_t tilt_percentage);
+
+* ``tilt_percentage`` - Tilt percentage (0-100)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Configuration
+*************
+
+setCoveringType
+^^^^^^^^^^^^^^^
+
+Sets the window covering type.
+
+.. code-block:: arduino
+
+    bool setCoveringType(ZigbeeWindowCoveringType covering_type);
+
+* ``covering_type`` - Window covering type (see supported types above)
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setConfigStatus
+^^^^^^^^^^^^^^^
+
+Sets the window covering configuration status.
+
+.. code-block:: arduino
+
+    bool setConfigStatus(bool operational, bool online, bool commands_reversed, bool lift_closed_loop, bool tilt_closed_loop, bool lift_encoder_controlled, bool tilt_encoder_controlled);
+
+* ``operational`` - Operational status
+* ``online`` - Online status
+* ``commands_reversed`` - Commands reversed flag
+* ``lift_closed_loop`` - Lift closed loop flag
+* ``tilt_closed_loop`` - Tilt closed loop flag
+* ``lift_encoder_controlled`` - Lift encoder controlled flag
+* ``tilt_encoder_controlled`` - Tilt encoder controlled flag
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setMode
+^^^^^^^
+
+Sets the window covering operation mode.
+
+.. code-block:: arduino
+
+    bool setMode(bool motor_reversed, bool calibration_mode, bool maintenance_mode, bool leds_on);
+
+* ``motor_reversed`` - Motor reversed flag
+* ``calibration_mode`` - Calibration mode flag
+* ``maintenance_mode`` - Maintenance mode flag
+* ``leds_on`` - LEDs on flag
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+setLimits
+^^^^^^^^^
+
+Sets the motion limits for the window covering.
+
+.. code-block:: arduino
+
+    bool setLimits(uint16_t installed_open_limit_lift, uint16_t installed_closed_limit_lift, uint16_t installed_open_limit_tilt, uint16_t installed_closed_limit_tilt);
+
+* ``installed_open_limit_lift`` - Installed open limit for lift
+* ``installed_closed_limit_lift`` - Installed closed limit for lift
+* ``installed_open_limit_tilt`` - Installed open limit for tilt
+* ``installed_closed_limit_tilt`` - Installed closed limit for tilt
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+Event Handling
+**************
+
+onOpen
+^^^^^^
+
+Sets a callback function to be called when the window covering opens.
+
+.. code-block:: arduino
+
+    void onOpen(void (*callback)());
+
+* ``callback`` - Function to call when window covering opens
+
+onClose
+^^^^^^^
+
+Sets a callback function to be called when the window covering closes.
+
+.. code-block:: arduino
+
+    void onClose(void (*callback)());
+
+* ``callback`` - Function to call when window covering closes
+
+onGoToLiftPercentage
+^^^^^^^^^^^^^^^^^^^^
+
+Sets a callback function to be called when lift percentage changes.
+
+.. code-block:: arduino
+
+    void onGoToLiftPercentage(void (*callback)(uint8_t));
+
+* ``callback`` - Function to call when lift percentage changes
+
+onGoToTiltPercentage
+^^^^^^^^^^^^^^^^^^^^
+
+Sets a callback function to be called when tilt percentage changes.
+
+.. code-block:: arduino
+
+    void onGoToTiltPercentage(void (*callback)(uint8_t));
+
+* ``callback`` - Function to call when tilt percentage changes
+
+onStop
+^^^^^^
+
+Sets a callback function to be called when window covering stops.
+
+.. code-block:: arduino
+
+    void onStop(void (*callback)());
+
+* ``callback`` - Function to call when window covering stops
+
+Example
+-------
+
+Window Covering Implementation
+******************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Window_Covering/Zigbee_Window_Covering.ino
+    :language: arduino
diff --git a/docs/en/zigbee/zigbee.rst b/docs/en/zigbee/zigbee.rst
new file mode 100644
index 00000000000..ba14adad8e1
--- /dev/null
+++ b/docs/en/zigbee/zigbee.rst
@@ -0,0 +1,159 @@
+######
+Zigbee
+######
+
+About
+-----
+
+The Zigbee library provides support for creating Zigbee 3.0 compatible devices including:
+
+* Support for different Zigbee roles (Coordinator, Router, End Device)
+* Network management (scanning, joining, commissioning)
+* Multiple endpoint types for various device categories
+* OTA (Over-The-Air) update support
+* Power management for battery-powered devices
+* Time synchronization
+* Advanced binding and group management
+
+The Zigbee library is built on top of `ESP-ZIGBEE-SDK <https://github.com/espressif/esp-zigbee-sdk>`_ and provides a high-level Arduino-style interface for creating Zigbee devices.
+
+Zigbee Network Topology
+***********************
+
+.. code-block:: text
+
+    ┌─────────────────┐       ┌─────────────────┐       ┌─────────────────┐
+    │   Coordinator   │◄─────►│     Router      │◄─────►│     Router      │
+    │   (Gateway)     │       │   (Repeater)    │       │  (Thermostat)   │
+    └─────────────────┘       └─────────────────┘       └─────────────────┘
+            │                          │                         │
+            │                          ▼                         │
+            │                 ┌─────────────────┐                │
+            │                 │   End Device    │                │
+            │                 │    (Sensor)     │                │
+            │                 └─────────────────┘                │
+            │                                                    │
+            ▼                                                    ▼
+    ┌─────────────────┐                                 ┌─────────────────┐
+    │   End Device    │                                 │   End Device    │
+    │   (Sensor)      │                                 │    (Sensor)     │
+    └─────────────────┘                                 └─────────────────┘
+
+
+**Device Roles**
+
+* **Coordinator**: Forms and manages the network, stores network information
+* **Router**: Extends network range, routes messages, mains powered devices (typically lights, switches, etc.)
+* **End Device**: Battery-powered devices that can sleep for extended periods (typically sensors)
+
+Zigbee Library Structure
+------------------------
+
+**The library is split into three main components:**
+
+* ``ZigbeeCore``: The main class that manages the Zigbee network
+* ``ZigbeeEP``: The base class for all Zigbee endpoints, which provides common functionality for all endpoint types
+* ``Specific endpoint classes``: The classes for all Zigbee endpoints, which provides the specific functionality for each endpoint type
+
+ZigbeeCore
+**********
+
+The ``ZigbeeCore`` class is the main entry point for all Zigbee operations. It serves as the central coordinator that manages:
+
+* **Network Operations**: Starting, stopping, and managing the Zigbee network
+* **Device Role Management**: Configuring the device as Coordinator, Router, or End Device
+* **Endpoint Management**: Adding and managing multiple device endpoints
+* **Network Discovery**: Scanning for and joining existing networks
+* **OTA Updates**: Managing over-the-air firmware updates
+* **Power Management**: Configuring sleep modes for battery-powered devices
+
+The ``ZigbeeCore`` class is implemented as a singleton, meaning there's only one instance available globally. You access it directly as ``Zigbee`` without creating an instance.
+
+.. toctree::
+    :maxdepth: 3
+
+    zigbee_core
+
+ZigbeeEP
+********
+
+The ``ZigbeeEP`` class is the base class for all Zigbee endpoints. It provides common functionality for all endpoint types.
+
+* **Device Information**: Every endpoint can be configured with manufacturer and model information that helps identify the device on the network
+* **Binding Management**: Binding allows endpoints to establish direct communication links with other devices. This enables automatic command transmission without requiring manual addressing
+* **Power Management**: Endpoints can report their power source type and battery status, which helps the network optimize communication patterns
+* **Time Synchronization**: Endpoints can synchronize with network time, enabling time-based operations and scheduling
+* **OTA Support**: Endpoints can receive over-the-air firmware updates to add new features or fix bugs
+* **Device Discovery**: Endpoints can read manufacturer and model information from other devices on the network
+
+.. toctree::
+    :maxdepth: 2
+
+    zigbee_ep
+
+Specific endpoint classes
+*************************
+
+Library provides the following endpoint classes from lights, switches, sensors, etc. Each endpoint class provides the specific functionality for each endpoint type and inherits from the ``ZigbeeEP`` class.
+
+.. toctree::
+    :maxdepth: 1
+    :glob:
+
+    ep_*
+
+
+Common Problems and Issues
+--------------------------
+
+Troubleshooting
+---------------
+
+Common Issues
+*************
+
+**Device won't join network**
+  * Ensure the coordinator is in pairing mode
+  * Check that the device is configured with the correct role
+  * Verify the channel mask includes the coordinator's channel
+
+**OTA updates fail**
+  * Ensure the OTA server is properly configured
+  * Check that the device has sufficient memory for the update
+  * Verify network connectivity
+
+**Battery devices not working**
+  * Ensure proper power source configuration
+  * Check sleep/wake timing settings
+  * Verify parent device (router/coordinator) is always powered
+
+**Binding issues**
+  * Check that both devices support the required clusters
+  * Verify that binding is enabled on both devices
+  * Ensure devices are on the same network
+
+**Network connectivity problems**
+  * Check that devices are within range
+  * Verify that routers are properly configured
+  * Check for interference from other 2.4 GHz devices
+
+Factory Reset
+*************
+
+If you have problems with connecting to the network, you can try to factory reset the device. This will erase all the network settings and act as brand new device.
+
+.. code-block:: arduino
+
+    Zigbee.factoryReset(true); // true = restart after reset
+
+Debug Mode
+**********
+
+For better debugging, you can enable debug mode to get detailed information about network operations. Call debug mode before starting Zigbee.
+Also selecting zigbee mode with *debug* suffix is recommended.
+
+.. code-block:: arduino
+
+    Zigbee.setDebugMode(true);
+    // Start Zigbee with debug output
+    Zigbee.begin();
diff --git a/docs/en/zigbee/zigbee_core.rst b/docs/en/zigbee/zigbee_core.rst
new file mode 100644
index 00000000000..ee8f7234210
--- /dev/null
+++ b/docs/en/zigbee/zigbee_core.rst
@@ -0,0 +1,375 @@
+##########
+ZigbeeCore
+##########
+
+About
+-----
+
+The ``ZigbeeCore`` class is the main entry point for all Zigbee operations. It serves as the central class that manages:
+
+* **Network Operations**: Starting, stopping, and managing the Zigbee network
+* **Device Role Management**: Configuring the device as Coordinator, Router, or End Device
+* **Endpoint Management**: Adding and managing multiple device endpoints
+* **Network Discovery**: Scanning for and joining existing networks
+
+ZigbeeCore APIs
+---------------
+
+Network Initialization
+**********************
+
+begin
+^^^^^
+
+Initializes the Zigbee stack and starts the network.
+
+.. code-block:: arduino
+
+    bool begin(zigbee_role_t role = ZIGBEE_END_DEVICE, bool erase_nvs = false);
+    bool begin(esp_zb_cfg_t *role_cfg, bool erase_nvs = false);
+
+* ``role`` - Device role (default: ``ZIGBEE_END_DEVICE``)
+* ``role_cfg`` - Custom role configuration structure
+* ``erase_nvs`` - Whether to erase NVS storage (default: ``false``)
+
+This function will return ``true`` if initialization successful, ``false`` otherwise.
+
+**Available Roles:**
+
+* **ZIGBEE_COORDINATOR**: Network coordinator, forms and manages the network
+* **ZIGBEE_ROUTER**: Network router, connects to existing network and extends network range and routes messages (if device is mains powered, always use this role)
+* **ZIGBEE_END_DEVICE**: End device, connects to existing network (typically battery-powered which can sleep)
+
+.. note::
+
+    Depending on the Zigbee role, proper Zigbee mode and partition scheme must be set in the Arduino IDE.
+
+    * **ZIGBEE_COORDINATOR** and **ZIGBEE_ROUTER**:
+        * Zigbee mode to ``Zigbee ZCZR (coordinator/router)``.
+        * Partition scheme to ``Zigbee ZCZR xMB with spiffs`` (where ``x`` is the number of MB of selected flash size).
+    * **ZIGBEE_END_DEVICE**:
+        * Zigbee mode to ``Zigbee ED (end device)``.
+        * Partition scheme to ``Zigbee xMB with spiffs`` (where ``x`` is the number of MB of selected flash size).
+
+Network Status
+**************
+
+started
+^^^^^^^
+
+Checks if the Zigbee stack has been started.
+
+.. code-block:: arduino
+
+    bool started();
+
+This function will return ``true`` if Zigbee stack is running, ``false`` otherwise.
+
+connected
+^^^^^^^^^
+
+Checks if the device is connected to a Zigbee network.
+
+.. code-block:: arduino
+
+    bool connected();
+
+This function will return ``true`` if connected to network, ``false`` otherwise.
+
+getRole
+^^^^^^^
+
+Gets the current Zigbee device role.
+
+.. code-block:: arduino
+
+    zigbee_role_t getRole();
+
+This function will return current device role (``ZIGBEE_COORDINATOR``, ``ZIGBEE_ROUTER``, ``ZIGBEE_END_DEVICE``).
+
+Endpoint Management
+*******************
+
+addEndpoint
+^^^^^^^^^^^
+
+Adds an endpoint to the Zigbee network.
+
+.. code-block:: arduino
+
+    bool addEndpoint(ZigbeeEP *ep);
+
+* ``ep`` - Pointer to the endpoint object to add
+
+This function will return ``true`` if endpoint added successfully, ``false`` otherwise.
+
+Network Configuration
+*********************
+
+setPrimaryChannelMask
+^^^^^^^^^^^^^^^^^^^^^
+
+Sets the primary channel mask for network scanning and joining.
+
+.. code-block:: arduino
+
+    void setPrimaryChannelMask(uint32_t mask);
+
+* ``mask`` - Channel mask (default: all channels 11-26, mask 0x07FFF800)
+
+setScanDuration
+^^^^^^^^^^^^^^^
+
+Sets the scan duration for network discovery.
+
+.. code-block:: arduino
+
+    void setScanDuration(uint8_t duration);
+
+* ``duration`` - Scan duration (1-4, where 1 is fastest, 4 is slowest)
+
+getScanDuration
+^^^^^^^^^^^^^^^
+
+Gets the current scan duration setting.
+
+.. code-block:: arduino
+
+    uint8_t getScanDuration();
+
+This function will return current scan duration (1-4).
+
+Power Management
+****************
+
+setRxOnWhenIdle
+^^^^^^^^^^^^^^^
+
+Sets whether the device keeps its receiver on when idle.
+
+.. code-block:: arduino
+
+    void setRxOnWhenIdle(bool rx_on_when_idle);
+
+* ``rx_on_when_idle`` - ``true`` to keep receiver on, ``false`` to allow sleep
+
+getRxOnWhenIdle
+^^^^^^^^^^^^^^^
+
+Gets the current receiver idle setting.
+
+.. code-block:: arduino
+
+    bool getRxOnWhenIdle();
+
+This function will return current receiver idle setting.
+
+setTimeout
+^^^^^^^^^^
+
+Sets the timeout for network operations.
+
+.. code-block:: arduino
+
+    void setTimeout(uint32_t timeout);
+
+* ``timeout`` - Timeout in milliseconds (default: 30000 ms)
+
+Network Discovery
+*****************
+
+scanNetworks
+^^^^^^^^^^^^
+
+Scans for available Zigbee networks.
+
+.. code-block:: arduino
+
+    void scanNetworks(uint32_t channel_mask = ESP_ZB_TRANSCEIVER_ALL_CHANNELS_MASK, uint8_t scan_duration = 5);
+
+* ``channel_mask`` - Channels to scan (default: all channels)
+* ``scan_duration`` - Scan duration (default: 5)
+
+scanComplete
+^^^^^^^^^^^^
+
+Checks if network scanning is complete.
+
+.. code-block:: arduino
+
+    int16_t scanComplete();
+
+This function will return:
+* ``-2``: Scan failed or not started
+* ``-1``: Scan running
+* ``0``: No networks found
+* ``>0``: Number of networks found
+
+getScanResult
+^^^^^^^^^^^^^
+
+Gets the scan results.
+
+.. code-block:: arduino
+
+    zigbee_scan_result_t *getScanResult();
+
+This function will return pointer to scan results, or ``NULL`` if no results.
+
+scanDelete
+^^^^^^^^^^
+
+Deletes the scan results from memory.
+
+.. code-block:: arduino
+
+    void scanDelete();
+
+Network Management (Coordinator only)
+*************************************
+
+setRebootOpenNetwork
+^^^^^^^^^^^^^^^^^^^^
+
+Opens the network for joining after reboot for a specified time.
+
+.. code-block:: arduino
+
+    void setRebootOpenNetwork(uint8_t time);
+
+* ``time`` - Time in seconds to keep network open after reboot
+
+openNetwork
+^^^^^^^^^^^
+
+Opens the network for device joining for a specified time.
+
+.. code-block:: arduino
+
+    void openNetwork(uint8_t time);
+
+* ``time`` - Time in seconds to keep network open for device joining
+
+closeNetwork
+^^^^^^^^^^^^
+
+Closes the network to prevent new devices from joining.
+
+.. code-block:: arduino
+
+    void closeNetwork();
+
+Radio Configuration
+*******************
+
+setRadioConfig
+^^^^^^^^^^^^^^
+
+Sets the radio configuration.
+
+.. code-block:: arduino
+
+    void setRadioConfig(esp_zb_radio_config_t config);
+
+* ``config`` - Radio configuration structure
+
+getRadioConfig
+^^^^^^^^^^^^^^
+
+Gets the current radio configuration.
+
+.. code-block:: arduino
+
+    esp_zb_radio_config_t getRadioConfig();
+
+This function will return current radio configuration.
+
+Host Configuration
+******************
+
+setHostConfig
+^^^^^^^^^^^^^
+
+Sets the host configuration.
+
+.. code-block:: arduino
+
+    void setHostConfig(esp_zb_host_config_t config);
+
+* ``config`` - Host configuration structure
+
+getHostConfig
+^^^^^^^^^^^^^
+
+Gets the current host configuration.
+
+.. code-block:: arduino
+
+    esp_zb_host_config_t getHostConfig();
+
+This function will return current host configuration.
+
+Debug and Utilities
+*******************
+
+setDebugMode
+^^^^^^^^^^^^
+
+Enables or disables debug mode.
+
+.. code-block:: arduino
+
+    void setDebugMode(bool debug);
+
+* ``debug`` - ``true`` to enable debug output, ``false`` to disable
+
+getDebugMode
+^^^^^^^^^^^^
+
+Gets the current debug mode setting.
+
+.. code-block:: arduino
+
+    bool getDebugMode();
+
+This function will return current debug mode setting.
+
+factoryReset
+^^^^^^^^^^^^
+
+Performs a factory reset, clearing all network settings.
+
+.. code-block:: arduino
+
+    void factoryReset(bool restart = true);
+
+* ``restart`` - ``true`` to restart after reset (default: ``true``)
+
+Utility Functions
+*****************
+
+formatIEEEAddress
+^^^^^^^^^^^^^^^^^
+
+Formats an IEEE address for display.
+
+.. code-block:: arduino
+
+    static const char *formatIEEEAddress(const esp_zb_ieee_addr_t addr);
+
+* ``addr`` - IEEE address to format
+
+This function will return formatted address string.
+
+formatShortAddress
+^^^^^^^^^^^^^^^^^^
+
+Formats a short address for display.
+
+.. code-block:: arduino
+
+    static const char *formatShortAddress(uint16_t addr);
+
+* ``addr`` - Short address to format
+
+This function will return formatted address string.
diff --git a/docs/en/zigbee/zigbee_ep.rst b/docs/en/zigbee/zigbee_ep.rst
new file mode 100644
index 00000000000..ce13d60bbaf
--- /dev/null
+++ b/docs/en/zigbee/zigbee_ep.rst
@@ -0,0 +1,357 @@
+########
+ZigbeeEP
+########
+
+About
+-----
+
+The ``ZigbeeEP`` class is the base class for all Zigbee endpoints. It provides common functionality for all endpoint types.
+
+* **Device Information**: Every endpoint can be configured with manufacturer and model information that helps identify the device on the network
+* **Binding Management**: Binding allows endpoints to establish direct communication links with other devices. This enables automatic command transmission without requiring manual addressing
+* **Power Management**: Endpoints can report their power source type and battery status, which helps the network optimize communication patterns
+* **Time Synchronization**: Endpoints can synchronize with network time, enabling time-based operations and scheduling
+* **OTA Support**: Endpoints can receive over-the-air firmware updates to add new features or fix bugs
+* **Device Discovery**: Endpoints can read manufacturer and model information from other devices on the network
+
+
+ZigbeeEP APIs
+-------------
+
+Device Information
+******************
+
+setManufacturerAndModel
+^^^^^^^^^^^^^^^^^^^^^^^
+
+Sets the manufacturer name and model identifier for the device.
+
+.. code-block:: arduino
+
+    bool setManufacturerAndModel(const char *name, const char *model);
+
+* ``name`` - Manufacturer name (max 32 characters)
+* ``model`` - Model identifier (max 32 characters)
+
+This function will return ``true`` if set successfully, ``false`` otherwise.
+
+getEndpoint
+^^^^^^^^^^^
+
+Gets the endpoint number assigned to this device.
+
+.. code-block:: arduino
+
+    uint8_t getEndpoint();
+
+This function will return the endpoint number (1-254).
+
+Binding Management
+******************
+
+bound
+^^^^^
+
+Checks if the endpoint has any bound devices.
+
+.. code-block:: arduino
+
+    bool bound();
+
+This function will return ``true`` if the endpoint has bound devices, ``false`` otherwise.
+
+getBoundDevices
+^^^^^^^^^^^^^^^
+
+Gets the list of devices bound to this endpoint.
+
+.. code-block:: arduino
+
+    std::vector<esp_zb_binding_info_t> getBoundDevices();
+
+This function will return list of bound device parameters.
+
+printBoundDevices
+^^^^^^^^^^^^^^^^^
+
+Prints information about bound devices to Serial or a custom Print object.
+
+.. code-block:: arduino
+
+    void printBoundDevices(Print &print = Serial);
+
+* ``print`` - Custom Print object (optional, defaults to Serial)
+
+allowMultipleBinding
+^^^^^^^^^^^^^^^^^^^^
+
+Enables or disables multiple device binding for this endpoint.
+
+.. code-block:: arduino
+
+    void allowMultipleBinding(bool bind);
+
+* ``bind`` - ``true`` to allow multiple bindings, ``false`` for single binding only
+
+setManualBinding
+^^^^^^^^^^^^^^^^
+
+Enables or disables manual binding mode. Manual binding mode is supposed to be used when using ZHA or Z2M where you bind devices manually.
+
+.. code-block:: arduino
+
+    void setManualBinding(bool bind);
+
+* ``bind`` - ``true`` for manual binding, ``false`` for automatic binding (default)
+
+clearBoundDevices
+^^^^^^^^^^^^^^^^^
+
+Removes all bound devices from this endpoint.
+
+.. code-block:: arduino
+
+    void clearBoundDevices();
+
+Binding Status
+**************
+
+epAllowMultipleBinding
+^^^^^^^^^^^^^^^^^^^^^^
+
+Gets whether multiple device binding is allowed for this endpoint.
+
+.. code-block:: arduino
+
+    bool epAllowMultipleBinding();
+
+This function will return ``true`` if multiple bindings are allowed, ``false`` otherwise.
+
+epUseManualBinding
+^^^^^^^^^^^^^^^^^^
+
+Gets whether manual binding mode is enabled for this endpoint.
+
+.. code-block:: arduino
+
+    bool epUseManualBinding();
+
+This function will return ``true`` if manual binding is enabled, ``false`` otherwise.
+
+Power Management
+****************
+
+setPowerSource
+^^^^^^^^^^^^^^
+
+Sets the power source type for the endpoint.
+
+.. code-block:: arduino
+
+    bool setPowerSource(uint8_t source, uint8_t percentage = 0xff, uint8_t voltage = 0xff);
+
+* ``source`` - Power source type (``ZB_POWER_SOURCE_MAINS``, ``ZB_POWER_SOURCE_BATTERY``, etc.)
+* ``percentage`` - Battery percentage (0-100, default: 0xff)
+* ``voltage`` - Battery voltage in 100 mV units (default: 0xff)
+
+This function will return ``true`` if set successfully, ``false`` otherwise.
+
+setBatteryPercentage
+^^^^^^^^^^^^^^^^^^^^
+
+Sets the current battery percentage.
+
+.. code-block:: arduino
+
+    bool setBatteryPercentage(uint8_t percentage);
+
+* ``percentage`` - Battery percentage (0-100)
+
+This function will return ``true`` if set successfully, ``false`` otherwise.
+
+setBatteryVoltage
+^^^^^^^^^^^^^^^^^
+
+Sets the battery voltage.
+
+.. code-block:: arduino
+
+    bool setBatteryVoltage(uint8_t voltage);
+
+* ``voltage`` - Battery voltage in 100 mV units (e.g., 35 for 3.5 V)
+
+This function will return ``true`` if set successfully, ``false`` otherwise.
+
+reportBatteryPercentage
+^^^^^^^^^^^^^^^^^^^^^^^
+
+Reports the current battery percentage to the network.
+
+.. code-block:: arduino
+
+    bool reportBatteryPercentage();
+
+This function will return ``true`` if reported successfully, ``false`` otherwise.
+
+Time Synchronization
+********************
+
+addTimeCluster
+^^^^^^^^^^^^^^
+
+Adds time synchronization cluster to the endpoint. When you want to add a server cluster (have the time and GMT offset) fill the time structure with the current time and GMT offset.
+For client cluster (get the time and GMT offset) keep the default parameters.
+
+.. code-block:: arduino
+
+    bool addTimeCluster(tm time = {}, int32_t gmt_offset = 0);
+
+* ``time`` - Current time structure (default: empty)
+* ``gmt_offset`` - GMT offset in seconds (default: 0)
+
+This function will return ``true`` if added successfully, ``false`` otherwise.
+
+setTime
+^^^^^^^
+
+Sets the current time for the endpoint.
+
+.. code-block:: arduino
+
+    bool setTime(tm time);
+
+* ``time`` - Time structure to set
+
+This function will return ``true`` if set successfully, ``false`` otherwise.
+
+setTimezone
+^^^^^^^^^^^
+
+Sets the timezone offset for the endpoint.
+
+.. code-block:: arduino
+
+    bool setTimezone(int32_t gmt_offset);
+
+* ``gmt_offset`` - GMT offset in seconds
+
+This function will return ``true`` if set successfully, ``false`` otherwise.
+
+getTime
+^^^^^^^
+
+Gets the current network time.
+
+.. code-block:: arduino
+
+    struct tm getTime(uint8_t endpoint = 1, int32_t short_addr = 0x0000, esp_zb_ieee_addr_t ieee_addr = {});
+
+* ``endpoint`` - Target endpoint (default: 1)
+* ``short_addr`` - Target device short address (default: 0x0000)
+* ``ieee_addr`` - Target device IEEE address (default: empty)
+
+This function will return network time structure.
+
+getTimezone
+^^^^^^^^^^^
+
+Gets the timezone offset.
+
+.. code-block:: arduino
+
+    int32_t getTimezone(uint8_t endpoint = 1, int32_t short_addr = 0x0000, esp_zb_ieee_addr_t ieee_addr = {});
+
+* ``endpoint`` - Target endpoint (default: 1)
+* ``short_addr`` - Target device short address (default: 0x0000)
+* ``ieee_addr`` - Target device IEEE address (default: empty)
+
+This function will return GMT offset in seconds.
+
+OTA Support
+***********
+
+addOTAClient
+^^^^^^^^^^^^
+
+Adds OTA client to the endpoint for firmware updates.
+
+.. code-block:: arduino
+
+    bool addOTAClient(uint32_t file_version, uint32_t downloaded_file_ver, uint16_t hw_version, uint16_t manufacturer = 0x1001, uint16_t image_type = 0x1011, uint8_t max_data_size = 223);
+
+* ``file_version`` - Current firmware version
+* ``downloaded_file_ver`` - Downloaded file version
+* ``hw_version`` - Hardware version
+* ``manufacturer`` - Manufacturer code (default: 0x1001)
+* ``image_type`` - Image type code (default: 0x1011)
+* ``max_data_size`` - Maximum data size for OTA transfer (default: 223)
+
+This function will return ``true`` if added successfully, ``false`` otherwise.
+
+requestOTAUpdate
+^^^^^^^^^^^^^^^^
+
+Requests OTA update from the server.
+
+.. code-block:: arduino
+
+    void requestOTAUpdate();
+
+Device Discovery
+****************
+
+readManufacturer
+^^^^^^^^^^^^^^^^
+
+Reads the manufacturer name from a remote device.
+
+.. code-block:: arduino
+
+    char *readManufacturer(uint8_t endpoint, uint16_t short_addr, esp_zb_ieee_addr_t ieee_addr);
+
+* ``endpoint`` - Target endpoint number
+* ``short_addr`` - Target device short address
+* ``ieee_addr`` - Target device IEEE address
+
+This function will return pointer to manufacturer string, or ``NULL`` if read failed.
+
+readModel
+^^^^^^^^^
+
+Reads the model identifier from a remote device.
+
+.. code-block:: arduino
+
+    char *readModel(uint8_t endpoint, uint16_t short_addr, esp_zb_ieee_addr_t ieee_addr);
+
+* ``endpoint`` - Target endpoint number
+* ``short_addr`` - Target device short address
+* ``ieee_addr`` - Target device IEEE address
+
+This function will return pointer to model string, or ``NULL`` if read failed.
+
+Event Handling
+**************
+
+onIdentify
+^^^^^^^^^^
+
+Sets a callback function for identify events.
+
+.. code-block:: arduino
+
+    void onIdentify(void (*callback)(uint16_t));
+
+* ``callback`` - Function to call when identify event occurs
+* ``time`` - Identify time in seconds
+
+Supported Endpoints
+-------------------
+
+The Zigbee library provides specialized endpoint classes for different device types. Each endpoint type includes specific clusters and functionality relevant to that device category.
+
+.. toctree::
+    :maxdepth: 1
+    :glob:
+
+    ep_*

From 554de56f40e68d591b945bd1a8c931798e8a9167 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Tue, 22 Jul 2025 11:23:49 +0300
Subject: [PATCH 070/105] IDF release/v5.5 25c7c119 (#11623)

---
 package/package_esp32_index.template.json | 68 +++++++++++------------
 1 file changed, 34 insertions(+), 34 deletions(-)

diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index 6e2dd0ab337..f844a91161a 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-release_v5.5-cf8dad07-v1"
+              "version": "idf-release_v5.5-25c7c119-v1"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-release_v5.5-cf8dad07-v1",
+          "version": "idf-release_v5.5-25c7c119-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
-              "size": "430423461"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
+              "size": "430472412"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
-              "size": "430423461"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
+              "size": "430472412"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
-              "size": "430423461"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
+              "size": "430472412"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
-              "size": "430423461"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
+              "size": "430472412"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
-              "size": "430423461"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
+              "size": "430472412"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
-              "size": "430423461"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
+              "size": "430472412"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
-              "size": "430423461"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
+              "size": "430472412"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-cf8dad07-v1.zip",
-              "checksum": "SHA-256:c8310c661871a5d82b8b09a2b8d792936bf9a5023ed6dcb683ff93ff9ea4aaa7",
-              "size": "430423461"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
+              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
+              "size": "430472412"
             }
           ]
         },

From 69d891434bd5cd327cd93516fc60941f3e2bfd85 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Wed, 23 Jul 2025 01:37:23 +0300
Subject: [PATCH 071/105] IDF release/v5.5 b66b5448 (#11626)

IDF release/v5.5 b66b5448
---
 package/package_esp32_index.template.json | 68 +++++++++++------------
 1 file changed, 34 insertions(+), 34 deletions(-)

diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index f844a91161a..3909c833c56 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -51,7 +51,7 @@
             {
               "packager": "esp32",
               "name": "esp32-arduino-libs",
-              "version": "idf-release_v5.5-25c7c119-v1"
+              "version": "idf-release_v5.5-b66b5448-v1"
             },
             {
               "packager": "esp32",
@@ -104,63 +104,63 @@
       "tools": [
         {
           "name": "esp32-arduino-libs",
-          "version": "idf-release_v5.5-25c7c119-v1",
+          "version": "idf-release_v5.5-b66b5448-v1",
           "systems": [
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
-              "size": "430472412"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "checksum": "SHA-256:a871d945c6bfb685ecff5e30ad759f280c841ea143071466b2e611bd1800f18f",
+              "size": "430471837"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
-              "size": "430472412"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "checksum": "SHA-256:a871d945c6bfb685ecff5e30ad759f280c841ea143071466b2e611bd1800f18f",
+              "size": "430471837"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
-              "size": "430472412"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "checksum": "SHA-256:a871d945c6bfb685ecff5e30ad759f280c841ea143071466b2e611bd1800f18f",
+              "size": "430471837"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
-              "size": "430472412"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "checksum": "SHA-256:a871d945c6bfb685ecff5e30ad759f280c841ea143071466b2e611bd1800f18f",
+              "size": "430471837"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
-              "size": "430472412"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "checksum": "SHA-256:a871d945c6bfb685ecff5e30ad759f280c841ea143071466b2e611bd1800f18f",
+              "size": "430471837"
             },
             {
               "host": "i686-pc-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
-              "size": "430472412"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "checksum": "SHA-256:a871d945c6bfb685ecff5e30ad759f280c841ea143071466b2e611bd1800f18f",
+              "size": "430471837"
             },
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
-              "size": "430472412"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "checksum": "SHA-256:a871d945c6bfb685ecff5e30ad759f280c841ea143071466b2e611bd1800f18f",
+              "size": "430471837"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-25c7c119-v1.zip",
-              "checksum": "SHA-256:5760b8d2215c07b0f054e9cd62a268f218c2026db8b395e90696d8038f69d9a8",
-              "size": "430472412"
+              "url": "https://github.com/espressif/esp32-arduino-lib-builder/releases/download/idf-release_v5.5/esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "archiveFileName": "esp32-arduino-libs-idf-release_v5.5-b66b5448-v1.zip",
+              "checksum": "SHA-256:a871d945c6bfb685ecff5e30ad759f280c841ea143071466b2e611bd1800f18f",
+              "size": "430471837"
             }
           ]
         },

From a14ce89715088edd5c97d51f4c14f6cd380dded8 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Tue, 22 Jul 2025 19:38:01 -0300
Subject: [PATCH 072/105] fix(tamc_termod_s3): Fix header includes (#11625)

---
 variants/tamc_termod_s3/pins_arduino.h | 1 +
 variants/tamc_termod_s3/variant.cpp    | 1 +
 2 files changed, 2 insertions(+)

diff --git a/variants/tamc_termod_s3/pins_arduino.h b/variants/tamc_termod_s3/pins_arduino.h
index 3d846c9b111..89d0b5107ae 100644
--- a/variants/tamc_termod_s3/pins_arduino.h
+++ b/variants/tamc_termod_s3/pins_arduino.h
@@ -2,6 +2,7 @@
 #define Pins_Arduino_h
 
 #include <stdint.h>
+#include <stdbool.h>
 
 #define USB_VID 0x303a
 #define USB_PID 0x1001
diff --git a/variants/tamc_termod_s3/variant.cpp b/variants/tamc_termod_s3/variant.cpp
index 8079bdbba8d..cc255c31684 100644
--- a/variants/tamc_termod_s3/variant.cpp
+++ b/variants/tamc_termod_s3/variant.cpp
@@ -1,4 +1,5 @@
 #include "Arduino.h"
+#include "pins_arduino.h"
 
 float getBatteryVoltage() {
   int analogVolt = analogReadMilliVolts(1);

From f08efa1fa3dd7c816ddfecc7ef26f771e4aff1a5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Proch=C3=A1zka?=
 <90197375+P-R-O-C-H-Y@users.noreply.github.com>
Date: Wed, 23 Jul 2025 00:43:23 +0200
Subject: [PATCH 073/105] feat(docs): Updaze Zigbee docs with latest changes
 (#11627)

---
 docs/en/zigbee/ep_fan_control.rst | 133 ++++++++++++++++++++++++++++++
 docs/en/zigbee/zigbee_core.rst    |  13 +++
 docs/en/zigbee/zigbee_ep.rst      |  13 +++
 3 files changed, 159 insertions(+)
 create mode 100644 docs/en/zigbee/ep_fan_control.rst

diff --git a/docs/en/zigbee/ep_fan_control.rst b/docs/en/zigbee/ep_fan_control.rst
new file mode 100644
index 00000000000..1cfff0820df
--- /dev/null
+++ b/docs/en/zigbee/ep_fan_control.rst
@@ -0,0 +1,133 @@
+################
+ZigbeeFanControl
+################
+
+About
+-----
+
+The ``ZigbeeFanControl`` class provides a Zigbee endpoint for controlling fan devices in a Home Automation (HA) network. This endpoint implements the Fan Control cluster and allows for controlling fan modes and sequences.
+
+**Features:**
+* Fan mode control (OFF, LOW, MEDIUM, HIGH, ON, AUTO, SMART)
+* Fan mode sequence configuration
+* State change callbacks
+* Zigbee HA standard compliance
+
+**Use Cases:**
+* Smart ceiling fans
+* HVAC system fans
+* Exhaust fans
+* Any device requiring fan speed control
+
+API Reference
+-------------
+
+Constructor
+***********
+
+ZigbeeFanControl
+^^^^^^^^^^^^^^^^
+
+Creates a new Zigbee fan control endpoint.
+
+.. code-block:: arduino
+
+    ZigbeeFanControl(uint8_t endpoint);
+
+* ``endpoint`` - Endpoint number (1-254)
+
+Fan Mode Enums
+**************
+
+ZigbeeFanMode
+^^^^^^^^^^^^^
+
+Available fan modes for controlling the fan speed and operation.
+
+.. code-block:: arduino
+
+    enum ZigbeeFanMode {
+      FAN_MODE_OFF,      // Fan is off
+      FAN_MODE_LOW,      // Low speed
+      FAN_MODE_MEDIUM,   // Medium speed
+      FAN_MODE_HIGH,     // High speed
+      FAN_MODE_ON,       // Fan is on (full speed)
+      FAN_MODE_AUTO,     // Automatic mode
+      FAN_MODE_SMART,    // Smart mode
+    };
+
+ZigbeeFanModeSequence
+^^^^^^^^^^^^^^^^^^^^^
+
+Available fan mode sequences that define which modes are available for the fan.
+
+.. code-block:: arduino
+
+    enum ZigbeeFanModeSequence {
+      FAN_MODE_SEQUENCE_LOW_MED_HIGH,        // Low -> Medium -> High
+      FAN_MODE_SEQUENCE_LOW_HIGH,            // Low -> High
+      FAN_MODE_SEQUENCE_LOW_MED_HIGH_AUTO,   // Low -> Medium -> High -> Auto
+      FAN_MODE_SEQUENCE_LOW_HIGH_AUTO,       // Low -> High -> Auto
+      FAN_MODE_SEQUENCE_ON_AUTO,             // On -> Auto
+    };
+
+API Methods
+***********
+
+setFanModeSequence
+^^^^^^^^^^^^^^^^^^
+
+Sets the fan mode sequence and initializes the fan control.
+
+.. code-block:: arduino
+
+    bool setFanModeSequence(ZigbeeFanModeSequence sequence);
+
+* ``sequence`` - The fan mode sequence to set
+
+This function will return ``true`` if successful, ``false`` otherwise.
+
+getFanMode
+^^^^^^^^^^
+
+Gets the current fan mode.
+
+.. code-block:: arduino
+
+    ZigbeeFanMode getFanMode();
+
+This function will return current fan mode.
+
+getFanModeSequence
+^^^^^^^^^^^^^^^^^^
+
+Gets the current fan mode sequence.
+
+.. code-block:: arduino
+
+    ZigbeeFanModeSequence getFanModeSequence();
+
+This function will return current fan mode sequence.
+
+Event Handling
+**************
+
+onFanModeChange
+^^^^^^^^^^^^^^^
+
+Sets a callback function to be called when the fan mode changes.
+
+.. code-block:: arduino
+
+    void onFanModeChange(void (*callback)(ZigbeeFanMode mode));
+
+* ``callback`` - Function to call when fan mode changes
+
+Example
+-------
+
+Fan Control Implementation
+**************************
+
+.. literalinclude:: ../../../libraries/Zigbee/examples/Zigbee_Fan_Control/Zigbee_Fan_Control.ino
+    :language: arduino
diff --git a/docs/en/zigbee/zigbee_core.rst b/docs/en/zigbee/zigbee_core.rst
index ee8f7234210..89cf88ecca1 100644
--- a/docs/en/zigbee/zigbee_core.rst
+++ b/docs/en/zigbee/zigbee_core.rst
@@ -345,6 +345,19 @@ Performs a factory reset, clearing all network settings.
 
 * ``restart`` - ``true`` to restart after reset (default: ``true``)
 
+onGlobalDefaultResponse
+^^^^^^^^^^^^^^^^^^^^^^^
+
+Sets a global callback for default response messages.
+
+.. code-block:: arduino
+
+    void onGlobalDefaultResponse(void (*callback)(zb_cmd_type_t resp_to_cmd, esp_zb_zcl_status_t status, uint8_t endpoint, uint16_t cluster));
+
+* ``callback`` - Function pointer to the callback function
+
+This callback will be called for all endpoints when a default response is received.
+
 Utility Functions
 *****************
 
diff --git a/docs/en/zigbee/zigbee_ep.rst b/docs/en/zigbee/zigbee_ep.rst
index ce13d60bbaf..10c0c9fd084 100644
--- a/docs/en/zigbee/zigbee_ep.rst
+++ b/docs/en/zigbee/zigbee_ep.rst
@@ -345,6 +345,19 @@ Sets a callback function for identify events.
 * ``callback`` - Function to call when identify event occurs
 * ``time`` - Identify time in seconds
 
+onDefaultResponse
+^^^^^^^^^^^^^^^^^
+
+Sets a callback for default response messages for this endpoint.
+
+.. code-block:: arduino
+
+    void onDefaultResponse(void (*callback)(zb_cmd_type_t resp_to_cmd, esp_zb_zcl_status_t status));
+
+* ``callback`` - Function pointer to the callback function
+
+This callback will be called when a default response is received for this specific endpoint.
+
 Supported Endpoints
 -------------------
 

From ae634a92e3b3af3a68daf8e79b025a45ca9134ef Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Proch=C3=A1zka?=
 <90197375+P-R-O-C-H-Y@users.noreply.github.com>
Date: Wed, 23 Jul 2025 00:44:36 +0200
Subject: [PATCH 074/105] fix(zigbee): Fix RGB color calculation (#11624)

---
 cores/esp32/ColorFormat.c                            | 12 +++++++-----
 cores/esp32/ColorFormat.h                            |  3 ++-
 libraries/Zigbee/src/ep/ZigbeeColorDimmableLight.cpp |  5 ++---
 3 files changed, 11 insertions(+), 9 deletions(-)

diff --git a/cores/esp32/ColorFormat.c b/cores/esp32/ColorFormat.c
index a01123545b3..052249f2127 100644
--- a/cores/esp32/ColorFormat.c
+++ b/cores/esp32/ColorFormat.c
@@ -119,10 +119,10 @@ espHsvColor_t espRgbColorToHsvColor(espRgbColor_t rgb) {
 }
 
 espRgbColor_t espXYColorToRgbColor(uint8_t Level, espXyColor_t xy) {
-  return espXYToRgbColor(Level, xy.x, xy.y);
+  return espXYToRgbColor(Level, xy.x, xy.y, true);
 }
 
-espRgbColor_t espXYToRgbColor(uint8_t Level, uint16_t current_X, uint16_t current_Y) {
+espRgbColor_t espXYToRgbColor(uint8_t Level, uint16_t current_X, uint16_t current_Y, bool addXYZScaling) {
   // convert xyY color space to RGB
 
   // https://www.easyrgb.com/en/math.php
@@ -156,9 +156,11 @@ espRgbColor_t espXYToRgbColor(uint8_t Level, uint16_t current_X, uint16_t curren
   // X, Y and Z input refer to a D65/2° standard illuminant.
   // sR, sG and sB (standard RGB) output range = 0 ÷ 255
   // convert XYZ to RGB - CIE XYZ to sRGB
-  X = X / 100.0f;
-  Y = Y / 100.0f;
-  Z = Z / 100.0f;
+  if (addXYZScaling) {
+    X = X / 100.0f;
+    Y = Y / 100.0f;
+    Z = Z / 100.0f;
+  }
 
   r = (X * 3.2406f) - (Y * 1.5372f) - (Z * 0.4986f);
   g = -(X * 0.9689f) + (Y * 1.8758f) + (Z * 0.0415f);
diff --git a/cores/esp32/ColorFormat.h b/cores/esp32/ColorFormat.h
index 0bb87145d16..288b79b5714 100644
--- a/cores/esp32/ColorFormat.h
+++ b/cores/esp32/ColorFormat.h
@@ -19,6 +19,7 @@
 #pragma once
 
 #include <stdint.h>
+#include <stdbool.h>
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -49,7 +50,7 @@ typedef struct HsvColor_t espHsvColor_t;
 typedef struct XyColor_t espXyColor_t;
 typedef struct CtColor_t espCtColor_t;
 
-espRgbColor_t espXYToRgbColor(uint8_t Level, uint16_t current_X, uint16_t current_Y);
+espRgbColor_t espXYToRgbColor(uint8_t Level, uint16_t current_X, uint16_t current_Y, bool addXYZScaling);
 espRgbColor_t espXYColorToRgb(uint8_t Level, espXyColor_t xy);
 espXyColor_t espRgbColorToXYColor(espRgbColor_t rgb);
 espXyColor_t espRgbToXYColor(uint8_t r, uint8_t g, uint8_t b);
diff --git a/libraries/Zigbee/src/ep/ZigbeeColorDimmableLight.cpp b/libraries/Zigbee/src/ep/ZigbeeColorDimmableLight.cpp
index 2fb07fc2187..3611c232c20 100644
--- a/libraries/Zigbee/src/ep/ZigbeeColorDimmableLight.cpp
+++ b/libraries/Zigbee/src/ep/ZigbeeColorDimmableLight.cpp
@@ -76,14 +76,13 @@ void ZigbeeColorDimmableLight::zbAttributeSet(const esp_zb_zcl_set_attr_value_me
       return;
     } else {
       log_w("Received message ignored. Attribute ID: %d not supported for Level Control", message->attribute.id);
-      //TODO: implement more attributes -> includes/zcl/esp_zigbee_zcl_level.h
     }
   } else if (message->info.cluster == ESP_ZB_ZCL_CLUSTER_ID_COLOR_CONTROL) {
     if (message->attribute.id == ESP_ZB_ZCL_ATTR_COLOR_CONTROL_CURRENT_X_ID && message->attribute.data.type == ESP_ZB_ZCL_ATTR_TYPE_U16) {
       uint16_t light_color_x = (*(uint16_t *)message->attribute.data.value);
       uint16_t light_color_y = getCurrentColorY();
       //calculate RGB from XY and call setColor()
-      _current_color = espXYToRgbColor(255, light_color_x, light_color_y);  //TODO: Check if level is correct
+      _current_color = espXYToRgbColor(255, light_color_x, light_color_y, false);
       lightChanged();
       return;
 
@@ -91,7 +90,7 @@ void ZigbeeColorDimmableLight::zbAttributeSet(const esp_zb_zcl_set_attr_value_me
       uint16_t light_color_x = getCurrentColorX();
       uint16_t light_color_y = (*(uint16_t *)message->attribute.data.value);
       //calculate RGB from XY and call setColor()
-      _current_color = espXYToRgbColor(255, light_color_x, light_color_y);  //TODO: Check if level is correct
+      _current_color = espXYToRgbColor(255, light_color_x, light_color_y, false);
       lightChanged();
       return;
     } else if (message->attribute.id == ESP_ZB_ZCL_ATTR_COLOR_CONTROL_CURRENT_HUE_ID && message->attribute.data.type == ESP_ZB_ZCL_ATTR_TYPE_U8) {

From 6fdfccf21b1532dede0e886dd4ab904581a036f3 Mon Sep 17 00:00:00 2001
From: "pre-commit-ci-lite[bot]"
 <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Date: Tue, 22 Jul 2025 22:46:36 +0000
Subject: [PATCH 075/105] ci(pre-commit): Apply automatic fixes

---
 cores/esp32/esp32-hal-i2c-slave.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/cores/esp32/esp32-hal-i2c-slave.c b/cores/esp32/esp32-hal-i2c-slave.c
index 79c994869e2..da3a819387a 100644
--- a/cores/esp32/esp32-hal-i2c-slave.c
+++ b/cores/esp32/esp32-hal-i2c-slave.c
@@ -338,8 +338,7 @@ esp_err_t i2cSlaveInit(uint8_t num, int sda, int scl, uint16_t slaveID, uint32_t
   }
 #endif  // !defined(CONFIG_IDF_TARGET_ESP32P4)
 
-#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)) \
-  || (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 2) && ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 5, 0)) \
+#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)) || (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 2) && ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 5, 0)) \
   || (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 3) && ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 4, 0))
   i2c_ll_set_mode(i2c->dev, I2C_BUS_MODE_SLAVE);
   i2c_ll_enable_pins_open_drain(i2c->dev, true);

From e92e631811002adba98eb1e8e0ce167755e0864f Mon Sep 17 00:00:00 2001
From: Angel Nunez Mencias <git@angelnu.com>
Date: Wed, 23 Jul 2025 07:11:11 +0200
Subject: [PATCH 076/105] feat: Allow calls to timer functions within ISR

---
 cores/esp32/esp32-hal-timer.c | 19 +++++++------------
 1 file changed, 7 insertions(+), 12 deletions(-)

diff --git a/cores/esp32/esp32-hal-timer.c b/cores/esp32/esp32-hal-timer.c
index ec6c507358e..508d510508e 100644
--- a/cores/esp32/esp32-hal-timer.c
+++ b/cores/esp32/esp32-hal-timer.c
@@ -36,9 +36,8 @@ struct timer_struct_t {
   bool timer_started;
 };
 
-inline uint64_t timerRead(hw_timer_t *timer) {
+inline IRAM_ATTR uint64_t timerRead(hw_timer_t *timer) {
   if (timer == NULL) {
-    log_e("Timer handle is NULL");
     return 0;
   }
   uint64_t value;
@@ -46,15 +45,14 @@ inline uint64_t timerRead(hw_timer_t *timer) {
   return value;
 }
 
-void timerWrite(hw_timer_t *timer, uint64_t val) {
+void IRAM_ATTR timerWrite(hw_timer_t *timer, uint64_t val) {
   if (timer == NULL) {
-    log_e("Timer handle is NULL");
     return;
   }
   gptimer_set_raw_count(timer->timer_handle, val);
 }
 
-void timerAlarm(hw_timer_t *timer, uint64_t alarm_value, bool autoreload, uint64_t reload_count) {
+void IRAM_ATTR timerAlarm(hw_timer_t *timer, uint64_t alarm_value, bool autoreload, uint64_t reload_count) {
   if (timer == NULL) {
     log_e("Timer handle is NULL");
     return;
@@ -67,7 +65,7 @@ void timerAlarm(hw_timer_t *timer, uint64_t alarm_value, bool autoreload, uint64
   };
   err = gptimer_set_alarm_action(timer->timer_handle, &alarm_cfg);
   if (err != ESP_OK) {
-    log_e("Timer Alarm Write failed, error num=%d", err);
+    ; // Ignore
   }
 }
 
@@ -80,27 +78,24 @@ uint32_t timerGetFrequency(hw_timer_t *timer) {
   return frequency;
 }
 
-void timerStart(hw_timer_t *timer) {
+void IRAM_ATTR timerStart(hw_timer_t *timer) {
   if (timer == NULL) {
-    log_e("Timer handle is NULL");
     return;
   }
   gptimer_start(timer->timer_handle);
   timer->timer_started = true;
 }
 
-void timerStop(hw_timer_t *timer) {
+void IRAM_ATTR timerStop(hw_timer_t *timer) {
   if (timer == NULL) {
-    log_e("Timer handle is NULL");
     return;
   }
   gptimer_stop(timer->timer_handle);
   timer->timer_started = false;
 }
 
-void timerRestart(hw_timer_t *timer) {
+void IRAM_ATTR timerRestart(hw_timer_t *timer) {
   if (timer == NULL) {
-    log_e("Timer handle is NULL");
     return;
   }
   gptimer_set_raw_count(timer->timer_handle, 0);

From 67c59a202196abe0029b868c34e57faf4032f0c5 Mon Sep 17 00:00:00 2001
From: Angel Nunez Mencias <git@angelnu.com>
Date: Wed, 23 Jul 2025 07:26:03 +0200
Subject: [PATCH 077/105] fix: remove log from IRAM function

---
 cores/esp32/esp32-hal-timer.c | 1 -
 1 file changed, 1 deletion(-)

diff --git a/cores/esp32/esp32-hal-timer.c b/cores/esp32/esp32-hal-timer.c
index 508d510508e..6875b5b2d8f 100644
--- a/cores/esp32/esp32-hal-timer.c
+++ b/cores/esp32/esp32-hal-timer.c
@@ -54,7 +54,6 @@ void IRAM_ATTR timerWrite(hw_timer_t *timer, uint64_t val) {
 
 void IRAM_ATTR timerAlarm(hw_timer_t *timer, uint64_t alarm_value, bool autoreload, uint64_t reload_count) {
   if (timer == NULL) {
-    log_e("Timer handle is NULL");
     return;
   }
   esp_err_t err = ESP_OK;

From 3da3ad2f2d38badab90524c7c647681acbd8274e Mon Sep 17 00:00:00 2001
From: Wulu <wulu@wulu.zone>
Date: Wed, 23 Jul 2025 20:28:19 +0800
Subject: [PATCH 078/105] feat(board): Add onboard LED support for Waveshare
 ESP32-S3 Zero (#11630)

Defines the standard LED_BUILTIN and RGB_BUILTIN macros for the Waveshare ESP32-S3 Zero, allowing its onboard WS2812 RGB LED to be controlled via standard Arduino APIs.
---
 variants/waveshare_esp32_s3_zero/pins_arduino.h | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/variants/waveshare_esp32_s3_zero/pins_arduino.h b/variants/waveshare_esp32_s3_zero/pins_arduino.h
index 0d73bee16d0..20ce1c88859 100644
--- a/variants/waveshare_esp32_s3_zero/pins_arduino.h
+++ b/variants/waveshare_esp32_s3_zero/pins_arduino.h
@@ -2,6 +2,7 @@
 #define Pins_Arduino_h
 
 #include <stdint.h>
+#include "soc/soc_caps.h"
 
 #define USB_VID          0x303a
 #define USB_PID          0x822B
@@ -9,9 +10,17 @@
 #define USB_PRODUCT      "ESP32-S3-Zero"
 #define USB_SERIAL       ""  // Empty string for MAC address
 
-// Partial voltage measurement method
+// Onboard WS2812 RGB LED
 #define WS_RGB 21
 
+// BUILTIN_LED can be used in new Arduino API digitalWrite() like in Blink.ino
+static const uint8_t LED_BUILTIN = SOC_GPIO_PIN_COUNT + WS_RGB;
+#define BUILTIN_LED LED_BUILTIN  // backward compatibility
+#define LED_BUILTIN LED_BUILTIN  // allow testing #ifdef LED_BUILTIN
+// RGB_BUILTIN and RGB_BRIGHTNESS can be used in new Arduino API rgbLedWrite()
+#define RGB_BUILTIN    LED_BUILTIN
+#define RGB_BRIGHTNESS 64
+
 // Mapping based on the ESP32S3 data sheet - alternate for OUTPUT
 static const uint8_t OUTPUT_IO1 = 1;
 static const uint8_t OUTPUT_IO2 = 2;

From c7520ccef0c343611d7f9eb0afb3576f612de2f2 Mon Sep 17 00:00:00 2001
From: Me No Dev <me-no-dev@users.noreply.github.com>
Date: Wed, 23 Jul 2025 17:15:59 +0300
Subject: [PATCH 079/105] fix(report): Update Issue-report.yml for version
 3.3.0

---
 .github/ISSUE_TEMPLATE/Issue-report.yml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/.github/ISSUE_TEMPLATE/Issue-report.yml b/.github/ISSUE_TEMPLATE/Issue-report.yml
index 6dc1b0de171..a16a6ae3d44 100644
--- a/.github/ISSUE_TEMPLATE/Issue-report.yml
+++ b/.github/ISSUE_TEMPLATE/Issue-report.yml
@@ -43,6 +43,7 @@ body:
         - latest stable Release (if not listed below)
         - latest development Release Candidate (RC-X)
         - latest master (checkout manually)
+        - v3.3.0
         - v3.2.1
         - v3.2.0
         - v3.1.3

From 126039663f83b3d6f5868a30f7dc2093812ee7b4 Mon Sep 17 00:00:00 2001
From: Angel Nunez Mencias <git@angelnu.com>
Date: Thu, 24 Jul 2025 00:09:17 +0200
Subject: [PATCH 080/105] fix: conditional logs when not ISR

---
 cores/esp32/esp32-hal-timer.c | 40 +++++++++++++++++++++++++++++------
 1 file changed, 33 insertions(+), 7 deletions(-)

diff --git a/cores/esp32/esp32-hal-timer.c b/cores/esp32/esp32-hal-timer.c
index 6875b5b2d8f..38575fc9799 100644
--- a/cores/esp32/esp32-hal-timer.c
+++ b/cores/esp32/esp32-hal-timer.c
@@ -22,6 +22,12 @@
 #include "esp_clk_tree.h"
 #endif
 
+#if CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+#define TIMER_IRAM IRAM_ATTR
+#else
+#define TIMER_IRAM
+#endif
+
 typedef void (*voidFuncPtr)(void);
 typedef void (*voidFuncPtrArg)(void *);
 
@@ -36,8 +42,11 @@ struct timer_struct_t {
   bool timer_started;
 };
 
-inline IRAM_ATTR uint64_t timerRead(hw_timer_t *timer) {
+inline TIMER_IRAM uint64_t timerRead(hw_timer_t *timer) {
   if (timer == NULL) {
+    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+    log_e("Timer handle is NULL");
+    #endif
     return 0;
   }
   uint64_t value;
@@ -45,15 +54,21 @@ inline IRAM_ATTR uint64_t timerRead(hw_timer_t *timer) {
   return value;
 }
 
-void IRAM_ATTR timerWrite(hw_timer_t *timer, uint64_t val) {
+void TIMER_IRAM timerWrite(hw_timer_t *timer, uint64_t val) {
   if (timer == NULL) {
+    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+    log_e("Timer handle is NULL");
+    #endif
     return;
   }
   gptimer_set_raw_count(timer->timer_handle, val);
 }
 
-void IRAM_ATTR timerAlarm(hw_timer_t *timer, uint64_t alarm_value, bool autoreload, uint64_t reload_count) {
+void TIMER_IRAM timerAlarm(hw_timer_t *timer, uint64_t alarm_value, bool autoreload, uint64_t reload_count) {
   if (timer == NULL) {
+    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+    log_e("Timer handle is NULL");
+    #endif
     return;
   }
   esp_err_t err = ESP_OK;
@@ -64,7 +79,9 @@ void IRAM_ATTR timerAlarm(hw_timer_t *timer, uint64_t alarm_value, bool autorelo
   };
   err = gptimer_set_alarm_action(timer->timer_handle, &alarm_cfg);
   if (err != ESP_OK) {
-    ; // Ignore
+    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+    log_e("Timer Alarm Write failed, error num=%d", err);
+    #endif
   }
 }
 
@@ -77,24 +94,33 @@ uint32_t timerGetFrequency(hw_timer_t *timer) {
   return frequency;
 }
 
-void IRAM_ATTR timerStart(hw_timer_t *timer) {
+void TIMER_IRAM timerStart(hw_timer_t *timer) {
   if (timer == NULL) {
+    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+    log_e("Timer handle is NULL");
+    #endif
     return;
   }
   gptimer_start(timer->timer_handle);
   timer->timer_started = true;
 }
 
-void IRAM_ATTR timerStop(hw_timer_t *timer) {
+void TIMER_IRAM timerStop(hw_timer_t *timer) {
   if (timer == NULL) {
+    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+    log_e("Timer handle is NULL");
+    #endif
     return;
   }
   gptimer_stop(timer->timer_handle);
   timer->timer_started = false;
 }
 
-void IRAM_ATTR timerRestart(hw_timer_t *timer) {
+void TIMER_IRAM timerRestart(hw_timer_t *timer) {
   if (timer == NULL) {
+    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+    log_e("Timer handle is NULL");
+    #endif
     return;
   }
   gptimer_set_raw_count(timer->timer_handle, 0);

From e3a0a3a6c58eca709dacf6f1d2e7cd169f522e86 Mon Sep 17 00:00:00 2001
From: "pre-commit-ci-lite[bot]"
 <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Date: Thu, 24 Jul 2025 11:22:13 +0000
Subject: [PATCH 081/105] ci(pre-commit): Apply automatic fixes

---
 cores/esp32/esp32-hal-timer.c | 28 ++++++++++++++--------------
 1 file changed, 14 insertions(+), 14 deletions(-)

diff --git a/cores/esp32/esp32-hal-timer.c b/cores/esp32/esp32-hal-timer.c
index 38575fc9799..85e007143bd 100644
--- a/cores/esp32/esp32-hal-timer.c
+++ b/cores/esp32/esp32-hal-timer.c
@@ -44,9 +44,9 @@ struct timer_struct_t {
 
 inline TIMER_IRAM uint64_t timerRead(hw_timer_t *timer) {
   if (timer == NULL) {
-    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+#ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
     log_e("Timer handle is NULL");
-    #endif
+#endif
     return 0;
   }
   uint64_t value;
@@ -56,9 +56,9 @@ inline TIMER_IRAM uint64_t timerRead(hw_timer_t *timer) {
 
 void TIMER_IRAM timerWrite(hw_timer_t *timer, uint64_t val) {
   if (timer == NULL) {
-    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+#ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
     log_e("Timer handle is NULL");
-    #endif
+#endif
     return;
   }
   gptimer_set_raw_count(timer->timer_handle, val);
@@ -66,9 +66,9 @@ void TIMER_IRAM timerWrite(hw_timer_t *timer, uint64_t val) {
 
 void TIMER_IRAM timerAlarm(hw_timer_t *timer, uint64_t alarm_value, bool autoreload, uint64_t reload_count) {
   if (timer == NULL) {
-    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+#ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
     log_e("Timer handle is NULL");
-    #endif
+#endif
     return;
   }
   esp_err_t err = ESP_OK;
@@ -79,9 +79,9 @@ void TIMER_IRAM timerAlarm(hw_timer_t *timer, uint64_t alarm_value, bool autorel
   };
   err = gptimer_set_alarm_action(timer->timer_handle, &alarm_cfg);
   if (err != ESP_OK) {
-    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+#ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
     log_e("Timer Alarm Write failed, error num=%d", err);
-    #endif
+#endif
   }
 }
 
@@ -96,9 +96,9 @@ uint32_t timerGetFrequency(hw_timer_t *timer) {
 
 void TIMER_IRAM timerStart(hw_timer_t *timer) {
   if (timer == NULL) {
-    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+#ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
     log_e("Timer handle is NULL");
-    #endif
+#endif
     return;
   }
   gptimer_start(timer->timer_handle);
@@ -107,9 +107,9 @@ void TIMER_IRAM timerStart(hw_timer_t *timer) {
 
 void TIMER_IRAM timerStop(hw_timer_t *timer) {
   if (timer == NULL) {
-    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+#ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
     log_e("Timer handle is NULL");
-    #endif
+#endif
     return;
   }
   gptimer_stop(timer->timer_handle);
@@ -118,9 +118,9 @@ void TIMER_IRAM timerStop(hw_timer_t *timer) {
 
 void TIMER_IRAM timerRestart(hw_timer_t *timer) {
   if (timer == NULL) {
-    #ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
+#ifndef CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM
     log_e("Timer handle is NULL");
-    #endif
+#endif
     return;
   }
   gptimer_set_raw_count(timer->timer_handle, 0);

From 5c24611b913e90d65d75b5208359f6364a2509f9 Mon Sep 17 00:00:00 2001
From: Parsaabasi <mohammadabbasi970@gmail.com>
Date: Fri, 25 Jul 2025 12:35:55 +0200
Subject: [PATCH 082/105] feat(github): remove ESP32 forum from issue template

---
 .github/ISSUE_TEMPLATE/config.yml | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index e879b09bec2..060397abd1e 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -3,6 +3,3 @@ contact_links:
   - name: Arduino Core for Espressif Discord Server
     url: https://discord.gg/8xY6e9crwv
     about: Community Discord server for questions and help
-  - name: ESP32 Forum - Arduino
-    url: https://esp32.com/viewforum.php?f=19
-    about: Official Forum for questions

From 10e73be7146d6b6d80777016bdc4ddb810cf56a7 Mon Sep 17 00:00:00 2001
From: Parsaabasi <mohammadabbasi970@gmail.com>
Date: Fri, 25 Jul 2025 12:49:46 +0200
Subject: [PATCH 083/105] feat(github): Update template type

---
 .github/ISSUE_TEMPLATE/Issue-report.yml | 11 +++++++++++
 1 file changed, 11 insertions(+)

diff --git a/.github/ISSUE_TEMPLATE/Issue-report.yml b/.github/ISSUE_TEMPLATE/Issue-report.yml
index a16a6ae3d44..864ef65b92b 100644
--- a/.github/ISSUE_TEMPLATE/Issue-report.yml
+++ b/.github/ISSUE_TEMPLATE/Issue-report.yml
@@ -80,6 +80,17 @@ body:
         - other
     validations:
       required: true
+ - type: dropdown
+    id: type
+    attributes:
+      label: Type
+      description: How would you define the type of the issue? Please select from the types below.
+      options:
+        - Task
+        - Bug
+        - Question
+    validations:
+      required: true
   - type: input
     id: IDE
     attributes:

From b3152a4ffc38f374cb70ff999f3c64a9bef75297 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Proch=C3=A1zka?=
 <90197375+P-R-O-C-H-Y@users.noreply.github.com>
Date: Fri, 25 Jul 2025 14:10:32 +0200
Subject: [PATCH 084/105] feat(zigbee): Update SDK to latest

---
 idf_component.yml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/idf_component.yml b/idf_component.yml
index 82f14ea554a..f9357a401f9 100644
--- a/idf_component.yml
+++ b/idf_component.yml
@@ -54,12 +54,12 @@ dependencies:
   espressif/esp_modem:
     version: "^1.1.0"
   espressif/esp-zboss-lib:
-    version: "==1.6.4" # compatible with esp-zigbee-lib 1.6.5
+    version: "==1.6.4" # compatible with esp-zigbee-lib 1.6.6
     require: public
     rules:
       - if: "target not in [esp32c2, esp32p4]"
   espressif/esp-zigbee-lib:
-    version: "==1.6.5"
+    version: "==1.6.6"
     require: public
     rules:
       - if: "target not in [esp32c2, esp32p4]"

From b139bae5028ac2be25cd91943f62c7546b307ea1 Mon Sep 17 00:00:00 2001
From: Wulu <wulu@wulu.zone>
Date: Sun, 27 Jul 2025 19:50:20 +0800
Subject: [PATCH 085/105] docs: Remove incorrect statement on ESP32-S3 default
 resolution

---
 docs/en/api/adc.rst | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/docs/en/api/adc.rst b/docs/en/api/adc.rst
index 434384f8d9b..9c16db54ec1 100644
--- a/docs/en/api/adc.rst
+++ b/docs/en/api/adc.rst
@@ -52,8 +52,7 @@ This function will return analog value in millivolts (calibrated).
 analogReadResolution
 ^^^^^^^^^^^^^^^^^^^^
 
-This function is used to set the resolution of ``analogRead`` return value. Default is 12 bits (range from 0 to 4095)
-for all chips except ESP32-S3 where default is 13 bits (range from 0 to 8191).
+This function is used to set the resolution of ``analogRead`` return value. Default is 12 bits (range from 0 to 4095).
 When different resolution is set, the values read will be shifted to match the given resolution.
 
 Range is 1 - 16 .The default value will be used, if this function is not used.

From ed6e95d4fc207575d932dc12a7783eff724280f4 Mon Sep 17 00:00:00 2001
From: Paula Scharf <paulascharf@gmx.de>
Date: Mon, 28 Jul 2025 08:46:14 +0200
Subject: [PATCH 086/105] feat(board): use existing led API

---
 variants/sensebox_eye/variant.cpp | 46 +++----------------------------
 1 file changed, 4 insertions(+), 42 deletions(-)

diff --git a/variants/sensebox_eye/variant.cpp b/variants/sensebox_eye/variant.cpp
index d8a37f58758..23bc1d385f7 100644
--- a/variants/sensebox_eye/variant.cpp
+++ b/variants/sensebox_eye/variant.cpp
@@ -1,50 +1,12 @@
 #include "esp32-hal-gpio.h"
 #include "pins_arduino.h"
-#include "driver/rmt_tx.h"
 
 extern "C" {
 
-void blinkLED(uint8_t color[3], rmt_channel_handle_t led_chan, rmt_encoder_handle_t ws2812_encoder, rmt_transmit_config_t tx_config) {
-  ESP_ERROR_CHECK(rmt_transmit(led_chan, ws2812_encoder, color, sizeof(color), &tx_config));
-  rmt_tx_wait_all_done(led_chan, portMAX_DELAY);
-
-  // Wait a moment
-  delay(50);
-
-  // Turn LED off
-  uint8_t pixel_off[3] = { 0x00, 0x00, 0x00 };
-  ESP_ERROR_CHECK(rmt_transmit(led_chan, ws2812_encoder, pixel_off, sizeof(pixel_off), &tx_config));
-  rmt_tx_wait_all_done(led_chan, portMAX_DELAY);
-}
-
 void initVariant(void) {
-  rmt_channel_handle_t led_chan = NULL;
-  rmt_tx_channel_config_t tx_chan_config = {};
-  tx_chan_config.clk_src = RMT_CLK_SRC_DEFAULT;
-  tx_chan_config.resolution_hz = 10 * 1000 * 1000;
-  tx_chan_config.mem_block_symbols = 64;
-  tx_chan_config.trans_queue_depth = 4;
-  tx_chan_config.gpio_num = (gpio_num_t)PIN_LED;
-  tx_chan_config.flags.invert_out = false;
-  tx_chan_config.flags.with_dma = false;
-  ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &led_chan));
-
-  // WS2812 encoder config (available in `esp-rmt`)
-  rmt_encoder_handle_t ws2812_encoder = NULL;
-  rmt_bytes_encoder_config_t bytes_encoder_config = {
-    .bit0 = { .duration0 = 4, .level0 = 1, .duration1 = 9, .level1 = 0 },
-    .bit1 = { .duration0 = 8, .level0 = 1, .duration1 = 5, .level1 = 0 },
-    .flags = { .msb_first = true }
-  };
-  ESP_ERROR_CHECK(rmt_new_bytes_encoder(&bytes_encoder_config, &ws2812_encoder));
-
-  ESP_ERROR_CHECK(rmt_enable(led_chan));
-
-  rmt_transmit_config_t tx_config = {
-    .loop_count = 0
-  };
-
-  uint8_t pixel[3] = { 0x10, 0x00, 0x00 }; // green
-  blinkLED(pixel, led_chan, ws2812_encoder, tx_config);
+  // blink the RGB LED
+  rgbLedWrite(PIN_LED, 0x00, 0x10, 0x00); // green
+  delay(20);
+  rgbLedWrite(PIN_LED, 0x00, 0x00, 0x00); // off
 }
 }

From 0dcb1d1178c0d8c73870a83f892fada1114d8fc0 Mon Sep 17 00:00:00 2001
From: "pre-commit-ci-lite[bot]"
 <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Date: Mon, 28 Jul 2025 06:56:12 +0000
Subject: [PATCH 087/105] ci(pre-commit): Apply automatic fixes

---
 .../sensebox_eye/partitions-16MB-tinyuf2.csv  |  2 +-
 variants/sensebox_eye/pins_arduino.h          | 26 +++++++++----------
 variants/sensebox_eye/variant.cpp             |  4 +--
 variants/sensebox_mcu_esp32s2/APOTA.ino       |  4 +--
 4 files changed, 18 insertions(+), 18 deletions(-)

diff --git a/variants/sensebox_eye/partitions-16MB-tinyuf2.csv b/variants/sensebox_eye/partitions-16MB-tinyuf2.csv
index 960f3fbbd71..55dc6213161 100644
--- a/variants/sensebox_eye/partitions-16MB-tinyuf2.csv
+++ b/variants/sensebox_eye/partitions-16MB-tinyuf2.csv
@@ -7,4 +7,4 @@ otadata,  data, ota,      0xe000,  8K,
 ota_0,    0,    ota_0,   0x10000,  2048K,
 ota_1,    0,    ota_1,  0x210000,  2048K,
 uf2,      app,  factory,0x410000,  256K,
-ffat,     data, fat,    0x450000,  11968K,
\ No newline at end of file
+ffat,     data, fat,    0x450000,  11968K,
diff --git a/variants/sensebox_eye/pins_arduino.h b/variants/sensebox_eye/pins_arduino.h
index 99984dbc6a4..70c2bd880c9 100644
--- a/variants/sensebox_eye/pins_arduino.h
+++ b/variants/sensebox_eye/pins_arduino.h
@@ -10,15 +10,15 @@
 #define USB_SERIAL       ""  // Empty string for MAC address
 
 // Default USB FirmwareMSC Settings
-#define USB_FW_MSC_VENDOR_ID        "senseBox"        // max 8 chars
+#define USB_FW_MSC_VENDOR_ID        "senseBox"     // max 8 chars
 #define USB_FW_MSC_PRODUCT_ID       "Eye ESP32S3"  // max 16 chars
-#define USB_FW_MSC_PRODUCT_REVISION "1.00"            // max 4 chars
-#define USB_FW_MSC_VOLUME_NAME      "senseBox"        // max 11 chars
+#define USB_FW_MSC_PRODUCT_REVISION "1.00"         // max 4 chars
+#define USB_FW_MSC_VOLUME_NAME      "senseBox"     // max 11 chars
 #define USB_FW_MSC_SERIAL_NUMBER    0x00000000
 
 #define PIN_RGB_LED 45  // RGB LED
 #define RGBLED_PIN  45  // RGB LED
-#define PIN_LED   45
+#define PIN_LED     45
 #define RGBLED_NUM  1  // number of RGB LEDs
 
 // Default I2C QWIIC-Ports
@@ -28,14 +28,14 @@ static const uint8_t SCL = 1;
 #define PIN_QWIIC_SCL 1
 
 // IO Pins
-#define PIN_IO14   14
-static const uint8_t A14 = PIN_IO14; // Analog
-static const uint8_t D14 = PIN_IO14; // Digital
-static const uint8_t T14 = PIN_IO14; // Touch
-#define PIN_IO48   48
-static const uint8_t A48 = PIN_IO48; // Analog
-static const uint8_t D48 = PIN_IO48; // Digital
-static const uint8_t T48 = PIN_IO48; // Touch
+#define PIN_IO14 14
+static const uint8_t A14 = PIN_IO14;  // Analog
+static const uint8_t D14 = PIN_IO14;  // Digital
+static const uint8_t T14 = PIN_IO14;  // Touch
+#define PIN_IO48 48
+static const uint8_t A48 = PIN_IO48;  // Analog
+static const uint8_t D48 = PIN_IO48;  // Digital
+static const uint8_t T48 = PIN_IO48;  // Touch
 
 // Button
 #define PIN_BUTTON 47
@@ -87,4 +87,4 @@ static const uint8_t RX = 44;
 #define LORA_TX 43
 #define LORA_RX 44
 
-#endif /* Pins_Arduino_h */
\ No newline at end of file
+#endif /* Pins_Arduino_h */
diff --git a/variants/sensebox_eye/variant.cpp b/variants/sensebox_eye/variant.cpp
index 23bc1d385f7..4d6e38e73e0 100644
--- a/variants/sensebox_eye/variant.cpp
+++ b/variants/sensebox_eye/variant.cpp
@@ -5,8 +5,8 @@ extern "C" {
 
 void initVariant(void) {
   // blink the RGB LED
-  rgbLedWrite(PIN_LED, 0x00, 0x10, 0x00); // green
+  rgbLedWrite(PIN_LED, 0x00, 0x10, 0x00);  // green
   delay(20);
-  rgbLedWrite(PIN_LED, 0x00, 0x00, 0x00); // off
+  rgbLedWrite(PIN_LED, 0x00, 0x00, 0x00);  // off
 }
 }
diff --git a/variants/sensebox_mcu_esp32s2/APOTA.ino b/variants/sensebox_mcu_esp32s2/APOTA.ino
index afb741499b2..114f0325e92 100644
--- a/variants/sensebox_mcu_esp32s2/APOTA.ino
+++ b/variants/sensebox_mcu_esp32s2/APOTA.ino
@@ -1,5 +1,5 @@
-// APOTA is a arduino fallback sketch that is written to OTA1_Partition. 
-// APOTA opens an access point which waits to receive a .binfile on /sketch. 
+// APOTA is a arduino fallback sketch that is written to OTA1_Partition.
+// APOTA opens an access point which waits to receive a .binfile on /sketch.
 // After succesful upload, the file is written to OTA0_Partition and the microcontroller reboots to the newly uploaded sketch.
 
 #define DISPLAY_ENABLED

From e375698adeb0d3ef306782b1a669bf7a60d6b190 Mon Sep 17 00:00:00 2001
From: Paula Scharf <paulascharf@gmx.de>
Date: Mon, 28 Jul 2025 09:44:04 +0200
Subject: [PATCH 088/105] feat(board): spelling

---
 variants/sensebox_mcu_esp32s2/APOTA.ino | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/variants/sensebox_mcu_esp32s2/APOTA.ino b/variants/sensebox_mcu_esp32s2/APOTA.ino
index 114f0325e92..a1fbab402ca 100644
--- a/variants/sensebox_mcu_esp32s2/APOTA.ino
+++ b/variants/sensebox_mcu_esp32s2/APOTA.ino
@@ -1,6 +1,6 @@
-// APOTA is a arduino fallback sketch that is written to OTA1_Partition.
-// APOTA opens an access point which waits to receive a .binfile on /sketch.
-// After succesful upload, the file is written to OTA0_Partition and the microcontroller reboots to the newly uploaded sketch.
+// APOTA is an Arduino fallback sketch that is written to OTA1_Partition. 
+// APOTA opens an access point which waits to receive a .bin file on /sketch. 
+// After successful upload, the file is written to OTA0_Partition, and the microcontroller reboots to the newly uploaded sketch.
 
 #define DISPLAY_ENABLED
 

From a5e85f675e09aa9e5532dd9e4e24019e243f3ee8 Mon Sep 17 00:00:00 2001
From: "pre-commit-ci-lite[bot]"
 <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Date: Mon, 28 Jul 2025 07:44:47 +0000
Subject: [PATCH 089/105] ci(pre-commit): Apply automatic fixes

---
 variants/sensebox_mcu_esp32s2/APOTA.ino | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/variants/sensebox_mcu_esp32s2/APOTA.ino b/variants/sensebox_mcu_esp32s2/APOTA.ino
index a1fbab402ca..67348d0b20f 100644
--- a/variants/sensebox_mcu_esp32s2/APOTA.ino
+++ b/variants/sensebox_mcu_esp32s2/APOTA.ino
@@ -1,5 +1,5 @@
-// APOTA is an Arduino fallback sketch that is written to OTA1_Partition. 
-// APOTA opens an access point which waits to receive a .bin file on /sketch. 
+// APOTA is an Arduino fallback sketch that is written to OTA1_Partition.
+// APOTA opens an access point which waits to receive a .bin file on /sketch.
 // After successful upload, the file is written to OTA0_Partition, and the microcontroller reboots to the newly uploaded sketch.
 
 #define DISPLAY_ENABLED

From 311955ccbb0fa657ff6e03fcdd553bd5094c826a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Proch=C3=A1zka?=
 <90197375+P-R-O-C-H-Y@users.noreply.github.com>
Date: Mon, 28 Jul 2025 11:59:01 +0200
Subject: [PATCH 090/105] fix(component): Use external diag logs to avoid error

---
 idf_component_examples/esp_matter_light/sdkconfig.defaults   | 5 +++++
 idf_component_examples/hello_world/sdkconfig.defaults        | 5 +++++
 idf_component_examples/hw_cdc_hello_world/sdkconfig.defaults | 5 +++++
 3 files changed, 15 insertions(+)

diff --git a/idf_component_examples/esp_matter_light/sdkconfig.defaults b/idf_component_examples/esp_matter_light/sdkconfig.defaults
index 43871661856..8688318fa36 100644
--- a/idf_component_examples/esp_matter_light/sdkconfig.defaults
+++ b/idf_component_examples/esp_matter_light/sdkconfig.defaults
@@ -60,3 +60,8 @@ CONFIG_MBEDTLS_HKDF_C=y
 # Increase LwIP IPv6 address number to 6 (MAX_FABRIC + 1)
 # unique local addresses for fabrics(MAX_FABRIC), a link local address(1)
 CONFIG_LWIP_IPV6_NUM_ADDRESSES=6
+
+#
+# DIAGNOSTICS
+#
+CONFIG_DIAG_USE_EXTERNAL_LOG_WRAP=y
diff --git a/idf_component_examples/hello_world/sdkconfig.defaults b/idf_component_examples/hello_world/sdkconfig.defaults
index bb723653f8a..a604d9767fd 100644
--- a/idf_component_examples/hello_world/sdkconfig.defaults
+++ b/idf_component_examples/hello_world/sdkconfig.defaults
@@ -10,3 +10,8 @@ CONFIG_AUTOSTART_ARDUINO=y
 CONFIG_FREERTOS_HZ=1000
 # end of FREERTOS
 # end of Component config
+
+#
+# DIAGNOSTICS
+#
+CONFIG_DIAG_USE_EXTERNAL_LOG_WRAP=y
diff --git a/idf_component_examples/hw_cdc_hello_world/sdkconfig.defaults b/idf_component_examples/hw_cdc_hello_world/sdkconfig.defaults
index bb723653f8a..a604d9767fd 100644
--- a/idf_component_examples/hw_cdc_hello_world/sdkconfig.defaults
+++ b/idf_component_examples/hw_cdc_hello_world/sdkconfig.defaults
@@ -10,3 +10,8 @@ CONFIG_AUTOSTART_ARDUINO=y
 CONFIG_FREERTOS_HZ=1000
 # end of FREERTOS
 # end of Component config
+
+#
+# DIAGNOSTICS
+#
+CONFIG_DIAG_USE_EXTERNAL_LOG_WRAP=y

From 6cc7a63cd021e6cd457d086dc1efb6b550554c65 Mon Sep 17 00:00:00 2001
From: Wulu <wulu@wulu.zone>
Date: Mon, 28 Jul 2025 22:43:55 +0800
Subject: [PATCH 091/105] docs: Change ADC default resolution exception to
 ESP32-S2

---
 docs/en/api/adc.rst | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/docs/en/api/adc.rst b/docs/en/api/adc.rst
index 9c16db54ec1..416a8afd803 100644
--- a/docs/en/api/adc.rst
+++ b/docs/en/api/adc.rst
@@ -52,7 +52,8 @@ This function will return analog value in millivolts (calibrated).
 analogReadResolution
 ^^^^^^^^^^^^^^^^^^^^
 
-This function is used to set the resolution of ``analogRead`` return value. Default is 12 bits (range from 0 to 4095).
+This function is used to set the resolution of ``analogRead`` return value. Default is 12 bits (range from 0 to 4095)
+for all chips except ESP32-S2 where default is 13 bits (range from 0 to 8191).
 When different resolution is set, the values read will be shifted to match the given resolution.
 
 Range is 1 - 16 .The default value will be used, if this function is not used.

From f5b08cd81297136fbf0121835858bca39bd4d394 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Mon, 28 Jul 2025 13:38:14 -0300
Subject: [PATCH 092/105] feat(codeql): Add CodeQL analysis for interpreted
 languages (#11662)

---
 .github/CODEOWNERS                   |  1 +
 .github/codeql/codeql-config.yml     | 26 +++++++++++++++++++++++
 .github/workflows/codeql_actions.yml | 31 ++++++++++++++++++++++++++++
 .github/workflows/codeql_python.yml  | 30 +++++++++++++++++++++++++++
 4 files changed, 88 insertions(+)
 create mode 100644 .github/codeql/codeql-config.yml
 create mode 100644 .github/workflows/codeql_actions.yml
 create mode 100644 .github/workflows/codeql_python.yml

diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 64d241ba20a..d07ef88044d 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -11,6 +11,7 @@
 
 # CI
 /.github/ @lucasssvaz @me-no-dev @P-R-O-C-H-Y
+/.github/codeql/ @lucasssvaz
 /.gitlab/ @lucasssvaz
 /tests/ @lucasssvaz @P-R-O-C-H-Y
 
diff --git a/.github/codeql/codeql-config.yml b/.github/codeql/codeql-config.yml
new file mode 100644
index 00000000000..c640d7bd6ef
--- /dev/null
+++ b/.github/codeql/codeql-config.yml
@@ -0,0 +1,26 @@
+name: "CodeQL config"
+
+packs:
+  - trailofbits/cpp-queries
+  - githubsecuritylab/codeql-cpp-queries
+  - githubsecuritylab/codeql-python-queries
+
+queries:
+  - uses: security-extended
+  - uses: security-and-quality
+
+query-filters:
+  - exclude:
+      query path:
+        - /^experimental\/.*/
+  - exclude:
+      tags contain:
+        - experimental
+  - exclude:
+      problem.severity:
+        - recommendation
+  - exclude:
+      id: tob/cpp/use-of-legacy-algorithm
+
+paths-ignore:
+  - tests/**
diff --git a/.github/workflows/codeql_actions.yml b/.github/workflows/codeql_actions.yml
new file mode 100644
index 00000000000..07688f896ba
--- /dev/null
+++ b/.github/workflows/codeql_actions.yml
@@ -0,0 +1,31 @@
+name: CodeQL Actions Analysis
+
+on:
+  workflow_dispatch:
+  push:
+    branches:
+      - master
+  pull_request:
+    paths:
+      - ".github/workflows/*.yml"
+      - ".github/workflows/*.yaml"
+
+jobs:
+  codeql-analysis:
+    name: CodeQL Actions Analysis
+    runs-on: ubuntu-latest
+
+    steps:
+      - name: Checkout repository
+        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+
+      - name: Initialize CodeQL
+        uses: github/codeql-action/init@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
+        with:
+          languages: actions
+          config-file: ./.github/codeql/codeql-config.yml
+
+      - name: Run CodeQL Analysis
+        uses: github/codeql-action/analyze@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
+        with:
+          category: "Analysis: Actions"
diff --git a/.github/workflows/codeql_python.yml b/.github/workflows/codeql_python.yml
new file mode 100644
index 00000000000..312974cd3c1
--- /dev/null
+++ b/.github/workflows/codeql_python.yml
@@ -0,0 +1,30 @@
+name: CodeQL Python Analysis
+
+on:
+  workflow_dispatch:
+  push:
+    branches:
+      - master
+  pull_request:
+    paths:
+      - "**/*.py"
+
+jobs:
+  codeql-analysis:
+    name: CodeQL Python Analysis
+    runs-on: ubuntu-latest
+
+    steps:
+      - name: Checkout repository
+        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+
+      - name: Initialize CodeQL
+        uses: github/codeql-action/init@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
+        with:
+          languages: python
+          config-file: ./.github/codeql/codeql-config.yml
+
+      - name: Run CodeQL Analysis
+        uses: github/codeql-action/analyze@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
+        with:
+          category: "Analysis: Python"

From 18daf31211eaba8ea7108263a938c6672e4c036a Mon Sep 17 00:00:00 2001
From: Parsaabasi <mohammadabbasi970@gmail.com>
Date: Tue, 29 Jul 2025 14:22:58 +0200
Subject: [PATCH 093/105] fix(github-template): indentation

---
 .github/ISSUE_TEMPLATE/Issue-report.yml | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/.github/ISSUE_TEMPLATE/Issue-report.yml b/.github/ISSUE_TEMPLATE/Issue-report.yml
index 864ef65b92b..e1c13413764 100644
--- a/.github/ISSUE_TEMPLATE/Issue-report.yml
+++ b/.github/ISSUE_TEMPLATE/Issue-report.yml
@@ -81,14 +81,14 @@ body:
     validations:
       required: true
  - type: dropdown
-    id: type
-    attributes:
-      label: Type
-      description: How would you define the type of the issue? Please select from the types below.
-      options:
-        - Task
-        - Bug
-        - Question
+   id: type
+   attributes:
+     label: Type
+     description: How would you define the type of the issue? Please select from the types below.
+     options:
+        - "Task"
+        - "Bug"
+        - "Question"
     validations:
       required: true
   - type: input

From 866359a0e38f726b539093237d6d688003f8ba96 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Tue, 29 Jul 2025 11:54:40 -0300
Subject: [PATCH 094/105] fix(codeql): Merge CodeQL workflows to avoid errors
 in PRs

---
 .../{codeql_actions.yml => codeql.yml}        | 12 +++++---
 .github/workflows/codeql_python.yml           | 30 -------------------
 2 files changed, 8 insertions(+), 34 deletions(-)
 rename .github/workflows/{codeql_actions.yml => codeql.yml} (72%)
 delete mode 100644 .github/workflows/codeql_python.yml

diff --git a/.github/workflows/codeql_actions.yml b/.github/workflows/codeql.yml
similarity index 72%
rename from .github/workflows/codeql_actions.yml
rename to .github/workflows/codeql.yml
index 07688f896ba..fb0badd78ec 100644
--- a/.github/workflows/codeql_actions.yml
+++ b/.github/workflows/codeql.yml
@@ -1,4 +1,4 @@
-name: CodeQL Actions Analysis
+name: CodeQL Analysis
 
 on:
   workflow_dispatch:
@@ -7,13 +7,17 @@ on:
       - master
   pull_request:
     paths:
+      - "**/*.py"
       - ".github/workflows/*.yml"
       - ".github/workflows/*.yaml"
 
 jobs:
   codeql-analysis:
-    name: CodeQL Actions Analysis
+    name: CodeQL ${{ matrix.language }} analysis
     runs-on: ubuntu-latest
+    strategy:
+      matrix:
+        language: [python, actions]
 
     steps:
       - name: Checkout repository
@@ -22,10 +26,10 @@ jobs:
       - name: Initialize CodeQL
         uses: github/codeql-action/init@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
         with:
-          languages: actions
+          languages: ${{ matrix.language }}
           config-file: ./.github/codeql/codeql-config.yml
 
       - name: Run CodeQL Analysis
         uses: github/codeql-action/analyze@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
         with:
-          category: "Analysis: Actions"
+          category: "/language:${{ matrix.language }}"
diff --git a/.github/workflows/codeql_python.yml b/.github/workflows/codeql_python.yml
deleted file mode 100644
index 312974cd3c1..00000000000
--- a/.github/workflows/codeql_python.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-name: CodeQL Python Analysis
-
-on:
-  workflow_dispatch:
-  push:
-    branches:
-      - master
-  pull_request:
-    paths:
-      - "**/*.py"
-
-jobs:
-  codeql-analysis:
-    name: CodeQL Python Analysis
-    runs-on: ubuntu-latest
-
-    steps:
-      - name: Checkout repository
-        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
-
-      - name: Initialize CodeQL
-        uses: github/codeql-action/init@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
-        with:
-          languages: python
-          config-file: ./.github/codeql/codeql-config.yml
-
-      - name: Run CodeQL Analysis
-        uses: github/codeql-action/analyze@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
-        with:
-          category: "Analysis: Python"

From 4eff7f9ae408a9fdd5d15c86184bda785d881aa3 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Tue, 29 Jul 2025 14:43:25 -0300
Subject: [PATCH 095/105] fix(template): Fix issue report template

---
 .github/ISSUE_TEMPLATE/Issue-report.yml | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/.github/ISSUE_TEMPLATE/Issue-report.yml b/.github/ISSUE_TEMPLATE/Issue-report.yml
index e1c13413764..97834925020 100644
--- a/.github/ISSUE_TEMPLATE/Issue-report.yml
+++ b/.github/ISSUE_TEMPLATE/Issue-report.yml
@@ -80,12 +80,12 @@ body:
         - other
     validations:
       required: true
- - type: dropdown
-   id: type
-   attributes:
-     label: Type
-     description: How would you define the type of the issue? Please select from the types below.
-     options:
+  - type: dropdown
+    id: type
+    attributes:
+      label: Type
+      description: How would you define the type of the issue? Please select from the types below.
+      options:
         - "Task"
         - "Bug"
         - "Question"

From 2b9d7576fa918e3f27ebd743690489c0874c2309 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Wed, 30 Jul 2025 10:27:31 -0300
Subject: [PATCH 096/105] ci(component): Move component compilation to a
 separate workflow

---
 .github/scripts/set_push_chunks.sh    |   1 -
 .github/workflows/build_component.yml | 133 ++++++++++++++++++++++++++
 .github/workflows/push.yml            | 120 +++++------------------
 .github/workflows/tests.yml           |  11 +--
 4 files changed, 159 insertions(+), 106 deletions(-)
 create mode 100644 .github/workflows/build_component.yml

diff --git a/.github/scripts/set_push_chunks.sh b/.github/scripts/set_push_chunks.sh
index ff0af7da6e8..69cd9a7f7de 100644
--- a/.github/scripts/set_push_chunks.sh
+++ b/.github/scripts/set_push_chunks.sh
@@ -78,7 +78,6 @@ chunks+="]"
     echo "build_all=$build_all"
     echo "build_libraries=$BUILD_LIBRARIES"
     echo "build_static_sketches=$BUILD_STATIC_SKETCHES"
-    echo "build_idf=$BUILD_IDF"
     echo "chunk_count=$chunks_count"
     echo "chunks=$chunks"
 } >> "$GITHUB_OUTPUT"
diff --git a/.github/workflows/build_component.yml b/.github/workflows/build_component.yml
new file mode 100644
index 00000000000..5553b4b2024
--- /dev/null
+++ b/.github/workflows/build_component.yml
@@ -0,0 +1,133 @@
+name: Arduino as ESP-IDF Component
+
+on:
+  workflow_dispatch:
+    inputs:
+      idf_ver:
+        description: "IDF Versions"
+        default: "release-v5.3,release-v5.4,release-v5.5"
+        type: "string"
+        required: true
+      idf_targets:
+        description: "IDF Targets"
+        default: "esp32,esp32s2,esp32s3,esp32c2,esp32c3,esp32c6,esp32h2,esp32p4"
+        type: "string"
+        required: true
+  push:
+    branches:
+      - master
+      - release/*
+  pull_request:
+    paths:
+      - "cores/**"
+      - "libraries/**/*.cpp"
+      - "libraries/**/*.c"
+      - "libraries/**/*.h"
+      - "libraries/**/*.ino"
+      - "libraries/**/ci.json"
+      - "idf_component_examples/**"
+      - "idf_component.yml"
+      - "Kconfig.projbuild"
+      - "CMakeLists.txt"
+      - ".github/workflows/build_component.yml"
+      - ".github/scripts/check-cmakelists.sh"
+      - ".github/scripts/on-push-idf.sh"
+      - ".github/scripts/sketch_utils.sh"
+      - "variants/esp32/**"
+      - "variants/esp32c2/**"
+      - "variants/esp32c3/**"
+      - "variants/esp32c6/**"
+      - "variants/esp32h2/**"
+      - "variants/esp32p4/**"
+      - "variants/esp32s2/**"
+      - "variants/esp32s3/**"
+      - "!*.md"
+      - "!*.txt"
+      - "!*.properties"
+
+concurrency:
+  group: build-component-${{github.event.pull_request.number || github.ref}}
+  cancel-in-progress: true
+
+jobs:
+  cmake-check:
+    name: Check CMakeLists
+    runs-on: ubuntu-latest
+    if: ${{ !(github.event_name == 'pull_request' && startsWith(github.head_ref, 'release/')) }}
+    steps:
+      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+      - run: bash ./.github/scripts/check-cmakelists.sh
+
+  set-matrix:
+    name: Set Matrix
+    runs-on: ubuntu-latest
+    if: ${{ !(github.event_name == 'pull_request' && startsWith(github.head_ref, 'release/')) }}
+    outputs:
+      idf_ver: ${{ steps.set-matrix.outputs.idf_ver }}
+      idf_target: ${{ steps.set-matrix.outputs.idf_target }}
+    steps:
+      - name: Get IDF Version and Targets
+        id: set-matrix
+        run: |
+          # Default values
+          idf_ver="release-v5.3,release-v5.4,release-v5.5"
+          idf_targets="esp32,esp32s2,esp32s3,esp32c2,esp32c3,esp32c6,esp32h2,esp32p4"
+
+          # Override with inputs if provided
+          if [[ -n "${{ inputs.idf_ver }}" ]]; then
+            idf_ver="${{ inputs.idf_ver }}"
+          fi
+          if [[ -n "${{ inputs.idf_targets }}" ]]; then
+            idf_targets="${{ inputs.idf_targets }}"
+          fi
+
+          # Convert comma-separated strings to JSON arrays using a more robust method
+          idf_ver_json=$(printf '%s\n' "$idf_ver" | tr ',' '\n' | jq -R . | jq -s . | jq -c .)
+          idf_targets_json=$(printf '%s\n' "$idf_targets" | tr ',' '\n' | jq -R . | jq -s . | jq -c .)
+
+          # Debug: Print the JSON for verification
+          echo "Debug - idf_ver_json: $idf_ver_json"
+          echo "Debug - idf_targets_json: $idf_targets_json"
+
+          # Set outputs - ensure no extra whitespace
+          printf "idf_ver=%s\n" "$idf_ver_json" >> $GITHUB_OUTPUT
+          printf "idf_target=%s\n" "$idf_targets_json" >> $GITHUB_OUTPUT
+
+  build-esp-idf-component:
+    name: Build IDF ${{ matrix.idf_ver }} for ${{ matrix.idf_target }}
+    runs-on: ubuntu-latest
+    needs: set-matrix
+    strategy:
+      fail-fast: false
+      matrix:
+        # The version names here correspond to the versions of espressif/idf Docker image.
+        # See https://hub.docker.com/r/espressif/idf/tags and
+        # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/tools/idf-docker-image.html
+        # for details.
+        idf_ver: ${{ fromJson(needs.set-matrix.outputs.idf_ver) }}
+        idf_target: ${{ fromJson(needs.set-matrix.outputs.idf_target) }}
+    container: espressif/idf:${{ matrix.idf_ver }}
+    steps:
+      - name: Check out arduino-esp32 as a component
+        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+        with:
+          submodules: recursive
+          path: components/arduino-esp32
+
+      - name: Setup jq
+        uses: dcarbone/install-jq-action@e397bd87438d72198f81efd21f876461183d383a # v3.0.1
+
+      - name: Build
+        env:
+          IDF_TARGET: ${{ matrix.idf_target }}
+        shell: bash
+        run: |
+          chmod a+x ./components/arduino-esp32/.github/scripts/*
+          ./components/arduino-esp32/.github/scripts/on-push-idf.sh
+
+      - name: Upload generated sdkconfig files for debugging
+        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+        if: always()
+        with:
+          name: sdkconfig-${{ matrix.idf_ver }}-${{ matrix.idf_target }}
+          path: ./components/arduino-esp32/idf_component_examples/**/sdkconfig
diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml
index 1523b7231be..fc85566aa8b 100644
--- a/.github/workflows/push.yml
+++ b/.github/workflows/push.yml
@@ -25,34 +25,32 @@ on:
   pull_request:
     paths:
       - "cores/**"
-      - "libraries/**"
-      - "!libraries/**.md"
-      - "!libraries/**.txt"
-      - "!libraries/**.properties"
-      - "!libraries/**.py"
+      - "libraries/**/*.cpp"
+      - "libraries/**/*.c"
+      - "libraries/**/*.h"
+      - "libraries/**/*.ino"
+      - "libraries/**/ci.json"
       - "package/**"
-      - "idf_component_examples/**"
-      - "tools/**.py"
+      - "tools/get.*"
       - "platform.txt"
       - "programmers.txt"
-      - "idf_component.yml"
-      - "Kconfig.projbuild"
       - "package.json"
-      - "CMakeLists.txt"
       - ".github/workflows/push.yml"
-      - ".github/scripts/**"
-      - "!.github/scripts/find_*"
-      - "!.github/scripts/on-release.sh"
-      - "!.github/scripts/tests_*"
-      - "!.github/scripts/upload_*"
-      - "variants/esp32/**/*"
-      - "variants/esp32c3/**/*"
-      - "variants/esp32c5/**/*"
-      - "variants/esp32c6/**/*"
-      - "variants/esp32h2/**/*"
-      - "variants/esp32p4/**/*"
-      - "variants/esp32s2/**/*"
-      - "variants/esp32s3/**/*"
+      - ".github/scripts/install-*"
+      - ".github/scripts/on-push.sh"
+      - ".github/scripts/set_push_chunks.sh"
+      - ".github/scripts/sketch_utils.sh"
+      - "variants/esp32/**"
+      - "variants/esp32c3/**"
+      - "variants/esp32c5/**"
+      - "variants/esp32c6/**"
+      - "variants/esp32h2/**"
+      - "variants/esp32p4/**"
+      - "variants/esp32s2/**"
+      - "variants/esp32s3/**"
+      - "!*.md"
+      - "!*.txt"
+      - "!*.properties"
 
 concurrency:
   group: build-${{github.event.pull_request.number || github.ref}}
@@ -62,14 +60,6 @@ env:
   MAX_CHUNKS: 15
 
 jobs:
-  cmake-check:
-    name: Check cmake file
-    runs-on: ubuntu-latest
-    if: ${{ !(github.event_name == 'pull_request' && startsWith(github.head_ref, 'release/')) }}
-    steps:
-      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
-      - run: bash ./.github/scripts/check-cmakelists.sh
-
   gen-chunks:
     name: Generate chunks
     runs-on: ubuntu-latest
@@ -78,7 +68,6 @@ jobs:
       build_all: ${{ steps.set-chunks.outputs.build_all }}
       build_libraries: ${{ steps.set-chunks.outputs.build_libraries }}
       build_static_sketches: ${{ steps.set-chunks.outputs.build_static_sketches }}
-      build_idf: ${{ steps.set-chunks.outputs.build_idf }}
       chunk_count: ${{ steps.set-chunks.outputs.chunk_count }}
       chunks: ${{ steps.set-chunks.outputs.chunks }}
     steps:
@@ -99,13 +88,7 @@ jobs:
               - 'tools/**'
               - 'platform.txt'
               - 'programmers.txt'
-              - "variants/esp32/**/*"
-              - "variants/esp32c3/**/*"
-              - "variants/esp32c6/**/*"
-              - "variants/esp32h2/**/*"
-              - "variants/esp32p4/**/*"
-              - "variants/esp32s2/**/*"
-              - "variants/esp32s3/**/*"
+              - "variants/**"
             libraries:
               - 'libraries/**/examples/**'
               - 'libraries/**/src/**'
@@ -121,11 +104,6 @@ jobs:
               - 'libraries/NetworkClientSecure/src/**'
               - 'libraries/BLE/src/**'
               - 'libraries/Insights/src/**'
-            idf:
-              - 'idf_component.yml'
-              - 'Kconfig.projbuild'
-              - 'CMakeLists.txt'
-              - "idf_component_examples/**"
 
       - name: Set chunks
         id: set-chunks
@@ -133,7 +111,6 @@ jobs:
           LIB_FILES: ${{ steps.changed-files.outputs.libraries_all_changed_files }}
           IS_PR: ${{ github.event_name == 'pull_request' }}
           MAX_CHUNKS: ${{ env.MAX_CHUNKS }}
-          BUILD_IDF: ${{ steps.changed-files.outputs.idf_any_changed == 'true' }}
           BUILD_LIBRARIES: ${{ steps.changed-files.outputs.libraries_any_changed == 'true' }}
           BUILD_STATIC_SKETCHES: ${{ steps.changed-files.outputs.static_sketeches_any_changed == 'true' }}
           FS_CHANGED: ${{ steps.changed-files.outputs.fs_any_changed == 'true' }}
@@ -233,59 +210,6 @@ jobs:
       - name: Build Sketches
         run: bash ./.github/scripts/on-push.sh
 
-  build-esp-idf-component:
-    name: Build with ESP-IDF ${{ matrix.idf_ver }} for ${{ matrix.idf_target }}
-    needs: gen-chunks
-    if: |
-      needs.gen-chunks.outputs.build_all == 'true' ||
-      needs.gen-chunks.outputs.build_libraries == 'true' ||
-      needs.gen-chunks.outputs.build_idf == 'true'
-    runs-on: ubuntu-latest
-    strategy:
-      fail-fast: false
-      matrix:
-        # The version names here correspond to the versions of espressif/idf Docker image.
-        # See https://hub.docker.com/r/espressif/idf/tags and
-        # https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/tools/idf-docker-image.html
-        # for details.
-        idf_ver: ["release-v5.3","release-v5.4","release-v5.5"]
-        idf_target:
-          [
-            "esp32",
-            "esp32s2",
-            "esp32s3",
-            "esp32c2",
-            "esp32c3",
-            "esp32c6",
-            "esp32h2",
-            "esp32p4"
-          ]
-    container: espressif/idf:${{ matrix.idf_ver }}
-    steps:
-      - name: Check out arduino-esp32 as a component
-        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
-        with:
-          submodules: recursive
-          path: components/arduino-esp32
-
-      - name: Setup jq
-        uses: dcarbone/install-jq-action@e397bd87438d72198f81efd21f876461183d383a # v3.0.1
-
-      - name: Build
-        env:
-          IDF_TARGET: ${{ matrix.idf_target }}
-        shell: bash
-        run: |
-          chmod a+x ./components/arduino-esp32/.github/scripts/*
-          ./components/arduino-esp32/.github/scripts/on-push-idf.sh
-
-      - name: Upload generated sdkconfig files for debugging
-        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
-        if: always()
-        with:
-          name: sdkconfig-${{ matrix.idf_ver }}-${{ matrix.idf_target }}
-          path: ./components/arduino-esp32/idf_component_examples/**/sdkconfig
-
   # Save artifacts to gh-pages
   save-master-artifacts:
     name: Save master artifacts
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index ddc9b64aace..058d9a3a793 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -16,20 +16,17 @@ on:
   pull_request:
     types: [opened, reopened, closed, synchronize, labeled, unlabeled]
     paths:
+      - ".github/scripts/install*.sh"
       - ".github/workflows/tests*"
-      - ".github/scripts/*.sh"
-      - "!.github/scripts/check-cmakelists.sh"
-      - "!.github/scripts/find_*"
-      - "!.github/scripts/on-*.sh"
-      - "!.github/scripts/set_push_chunks.sh"
-      - "!.github/scripts/update-version.sh"
-      - "!.github/scripts/upload_py_tools.sh"
+      - ".github/scripts/sketch_utils.sh"
       - "tests/**"
       - "cores/**"
       - "libraries/*/src/**.cpp"
       - "libraries/*/src/**.h"
       - "libraries/*/src/**.c"
       - "package/**"
+      - "!*.md"
+      - "!*.properties"
   schedule:
     - cron: "0 2 * * *"
 

From b9c0f689ae3bdb7e40cc34b69ae2a8681a060af5 Mon Sep 17 00:00:00 2001
From: wulu <wulu@wulu.zone>
Date: Wed, 30 Jul 2025 22:36:29 +0800
Subject: [PATCH 097/105] docs: Specify ADC resolution errata for ESP32-S2 v0.0

---
 docs/en/api/adc.rst | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/docs/en/api/adc.rst b/docs/en/api/adc.rst
index 416a8afd803..f2245cc1e5d 100644
--- a/docs/en/api/adc.rst
+++ b/docs/en/api/adc.rst
@@ -52,10 +52,12 @@ This function will return analog value in millivolts (calibrated).
 analogReadResolution
 ^^^^^^^^^^^^^^^^^^^^
 
-This function is used to set the resolution of ``analogRead`` return value. Default is 12 bits (range from 0 to 4095)
-for all chips except ESP32-S2 where default is 13 bits (range from 0 to 8191).
+This function is used to set the resolution of ``analogRead`` return value. Default is 12 bits (range from 0 to 4095) for all chips.
 When different resolution is set, the values read will be shifted to match the given resolution.
 
+.. note::
+   For **ESP32-S2 chip revision v0.0**, the default ADC resolution is 13 bits (0-8191) due to the `ADC-112 errata <https://docs.espressif.com/projects/esp-chip-errata/en/latest/esp32s2/03-errata-description/esp32s2/sar-adc-bit1-no-flip.html>`_. This is fixed in later revisions (v1.0+), which use the standard 12-bit resolution.
+
 Range is 1 - 16 .The default value will be used, if this function is not used.
 
 .. note:: For the ESP32, the resolution is between 9 to12 and it will change the ADC hardware resolution. Else value will be shifted.

From 673048f73e41cfddccfdbc676f38f7ff7b146dfc Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Thu, 31 Jul 2025 08:21:11 -0300
Subject: [PATCH 098/105] change(esptool): Upgrade esptool to 5.0.2

---
 package/package_esp32_index.template.json | 60 +++++++++++------------
 1 file changed, 30 insertions(+), 30 deletions(-)

diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json
index 3909c833c56..1b4b005dd34 100644
--- a/package/package_esp32_index.template.json
+++ b/package/package_esp32_index.template.json
@@ -81,7 +81,7 @@
             {
               "packager": "esp32",
               "name": "esptool_py",
-              "version": "5.0.0"
+              "version": "5.0.2"
             },
             {
               "packager": "esp32",
@@ -469,56 +469,56 @@
         },
         {
           "name": "esptool_py",
-          "version": "5.0.0",
+          "version": "5.0.2",
           "systems": [
             {
               "host": "aarch64-linux-gnu",
-              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-linux-aarch64.tar.gz",
-              "archiveFileName": "esptool-v5.0.0-linux-aarch64.tar.gz",
-              "checksum": "SHA-256:2bf239f3ed76141a957cadb205b94414ec6da9ace4e85f285e247d20a92b83e3",
-              "size": "58231895"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.2/esptool-v5.0.2-linux-aarch64.tar.gz",
+              "archiveFileName": "esptool-v5.0.2-linux-aarch64.tar.gz",
+              "checksum": "SHA-256:0c1fa4f5e96f715133fa65572063fa65bd120cd941b667cecd3360436a62b97b",
+              "size": "57815944"
             },
             {
               "host": "x86_64-pc-linux-gnu",
-              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-linux-amd64.tar.gz",
-              "archiveFileName": "esptool-v5.0.0-linux-amd64.tar.gz",
-              "checksum": "SHA-256:3b3835d266ac61f3242758f2fe34e3b33dbe6ee4b5acde005da793356f9f7043",
-              "size": "100783748"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.2/esptool-v5.0.2-linux-amd64.tar.gz",
+              "archiveFileName": "esptool-v5.0.2-linux-amd64.tar.gz",
+              "checksum": "SHA-256:519e0015872d527bdca850b18575d4f635fa88ccdffe47a14c99a80a90b780c5",
+              "size": "100787554"
             },
             {
               "host": "arm-linux-gnueabihf",
-              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-linux-armv7.tar.gz",
-              "archiveFileName": "esptool-v5.0.0-linux-armv7.tar.gz",
-              "checksum": "SHA-256:e55cd321abecfcf27f72a2bff5d5e19a5365fd400de66d71c5e7218e77556315",
-              "size": "53461760"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.2/esptool-v5.0.2-linux-armv7.tar.gz",
+              "archiveFileName": "esptool-v5.0.2-linux-armv7.tar.gz",
+              "checksum": "SHA-256:8df698d46a64b0b4a36d2a5bbd6bae58f81ca0a5e6451cd3f2d69a33340cc0f1",
+              "size": "53046401"
             },
             {
               "host": "x86_64-apple-darwin",
-              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-macos-amd64.tar.gz",
-              "archiveFileName": "esptool-v5.0.0-macos-amd64.tar.gz",
-              "checksum": "SHA-256:424da2bdf0435257ad81bcb7eae6fd8dd7f675ce5b2ee60032f4ecec4d6a5d45",
-              "size": "59629533"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.2/esptool-v5.0.2-macos-amd64.tar.gz",
+              "archiveFileName": "esptool-v5.0.2-macos-amd64.tar.gz",
+              "checksum": "SHA-256:5c27295975515b97a9280f46845bd3acd5fc9e6a0583cfe03efa66cc50195ab0",
+              "size": "59619952"
             },
             {
               "host": "arm64-apple-darwin",
-              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-macos-arm64.tar.gz",
-              "archiveFileName": "esptool-v5.0.0-macos-arm64.tar.gz",
-              "checksum": "SHA-256:b91dfe1da7b0041376683dec10a91dfb266fbda2fb86ed87c4a034ff7182ee56",
-              "size": "56343104"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.2/esptool-v5.0.2-macos-arm64.tar.gz",
+              "archiveFileName": "esptool-v5.0.2-macos-arm64.tar.gz",
+              "checksum": "SHA-256:93f0d9ef169f9bc6e32ed6f381977f63a5df7483b8002a5676dddf055bdbf775",
+              "size": "56344929"
             },
             {
               "host": "x86_64-mingw32",
-              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-windows-amd64.zip",
-              "archiveFileName": "esptool-v5.0.0-windows-amd64.zip",
-              "checksum": "SHA-256:2294107f66db6f09b886b337728a981173c9e7eab45a030928a8a5a1370611ca",
-              "size": "59105322"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.2/esptool-v5.0.2-windows-amd64.zip",
+              "archiveFileName": "esptool-v5.0.2-windows-amd64.zip",
+              "checksum": "SHA-256:1caef993a16c5915714a0da772d93f2e3239f316c06223981b262b838287268c",
+              "size": "59097582"
             },
             {
               "host": "i686-mingw32",
-              "url": "https://github.com/espressif/esptool/releases/download/v5.0.0/esptool-v5.0.0-windows-amd64.zip",
-              "archiveFileName": "esptool-v5.0.0-windows-amd64.zip",
-              "checksum": "SHA-256:2294107f66db6f09b886b337728a981173c9e7eab45a030928a8a5a1370611ca",
-              "size": "59105322"
+              "url": "https://github.com/espressif/esptool/releases/download/v5.0.2/esptool-v5.0.2-windows-amd64.zip",
+              "archiveFileName": "esptool-v5.0.2-windows-amd64.zip",
+              "checksum": "SHA-256:1caef993a16c5915714a0da772d93f2e3239f316c06223981b262b838287268c",
+              "size": "59097582"
             }
           ]
         },

From 30847588bc8909334479e4ee1ba48f43d051f8d0 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Thu, 31 Jul 2025 21:50:52 -0300
Subject: [PATCH 099/105] feat(codeql): Add CPP analysis

---
 .github/scripts/process_sarif.py | 129 +++++++++++++++++++++++++++++++
 .github/workflows/codeql.yml     |  55 ++++++++++++-
 2 files changed, 183 insertions(+), 1 deletion(-)
 create mode 100644 .github/scripts/process_sarif.py

diff --git a/.github/scripts/process_sarif.py b/.github/scripts/process_sarif.py
new file mode 100644
index 00000000000..fad689b6390
--- /dev/null
+++ b/.github/scripts/process_sarif.py
@@ -0,0 +1,129 @@
+#!/usr/bin/env python3
+
+# This script is used to process the SARIF file generated by CodeQL and
+# to rename files back to .ino and adjust line numbers to match the original .ino files.
+
+import json
+import sys
+import os
+
+def process_artifact_location(artifact_location, renamed_files):
+    """
+    Process a single artifact location to rename .cpp files back to .ino
+    """
+    if 'uri' in artifact_location:
+        uri = artifact_location['uri']
+        if uri in renamed_files:
+            print(f"Renaming file: {uri} -> {renamed_files[uri]}")
+            artifact_location['uri'] = renamed_files[uri]
+            return True
+    return False
+
+def process_region(region):
+    """
+    Adjust line numbers in a region by decreasing them by 1
+    """
+    if 'startLine' in region:
+        region['startLine'] = max(1, region['startLine'] - 1)
+    if 'endLine' in region:
+        region['endLine'] = max(1, region['endLine'] - 1)
+
+def process_physical_location(physical_location, renamed_files):
+    """
+    Process a physical location to rename files and adjust line numbers
+    """
+    file_renamed = False
+
+    if 'artifactLocation' in physical_location:
+        if process_artifact_location(physical_location['artifactLocation'], renamed_files):
+            file_renamed = True
+
+    # Adjust line numbers if the file was renamed
+    if file_renamed and 'region' in physical_location:
+        process_region(physical_location['region'])
+
+    return file_renamed
+
+
+def process_sarif_file(sarif_file, renamed_files_file):
+    """
+    Process SARIF file to rename files back to .ino and adjust line numbers
+    """
+    # Read the renamed files mapping
+    with open(renamed_files_file, 'r') as f:
+        renamed_files = json.load(f)
+
+    print(f"Loaded {len(renamed_files)} file mappings:")
+    for cpp_file, ino_file in renamed_files.items():
+        print(f"  {cpp_file} -> {ino_file}")
+
+
+    # Read the SARIF file
+    with open(sarif_file, 'r') as f:
+        sarif_data = json.load(f)
+
+    files_processed = 0
+
+    # Process each run
+    if 'runs' in sarif_data:
+        for run in sarif_data['runs']:
+            # Process results
+            if 'results' in run:
+                for result in run['results']:
+                    # Process all locations in the result
+                    if 'locations' in result:
+                        for location in result['locations']:
+                            if 'physicalLocation' in location:
+                                if process_physical_location(location['physicalLocation'], renamed_files):
+                                    files_processed += 1
+
+                    # Process related locations if they exist
+                    if 'relatedLocations' in result:
+                        for location in result['relatedLocations']:
+                            if 'physicalLocation' in location:
+                                if process_physical_location(location['physicalLocation'], renamed_files):
+                                    files_processed += 1
+
+            # Process artifacts if they exist
+            if 'artifacts' in run:
+                for artifact in run['artifacts']:
+                    if 'location' in artifact and 'uri' in artifact['location']:
+                        uri = artifact['location']['uri']
+                        if uri in renamed_files:
+                            artifact['location']['uri'] = renamed_files[uri]
+                            files_processed += 1
+
+    print(f"Processed {files_processed} file references")
+
+    # Write the processed SARIF file
+    with open(sarif_file, 'w') as f:
+        json.dump(sarif_data, f, indent=2)
+
+def main():
+    if len(sys.argv) != 3:
+        print("Usage: python3 sarif_nobuild.py <sarif_file> <renamed_files_file>")
+        sys.exit(1)
+
+    sarif_file = sys.argv[1]
+    renamed_files_file = sys.argv[2]
+
+    # Check if files exist
+    if not os.path.exists(sarif_file):
+        print(f"SARIF file not found: {sarif_file}")
+        sys.exit(1)
+
+    if not os.path.exists(renamed_files_file):
+        print(f"Renamed files mapping not found: {renamed_files_file}")
+        sys.exit(1)
+
+    try:
+        process_sarif_file(sarif_file, renamed_files_file)
+        print("SARIF file processed successfully")
+    except Exception as e:
+        print(f"Error processing SARIF file: {e}")
+        import traceback
+        traceback.print_exc()
+        sys.exit(1)
+
+if __name__ == "__main__":
+    main()
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index fb0badd78ec..9b2c6bccab1 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -7,6 +7,10 @@ on:
       - master
   pull_request:
     paths:
+      - "**/*.c"
+      - "**/*.cpp"
+      - "**/*.h"
+      - "**/*.ino"
       - "**/*.py"
       - ".github/workflows/*.yml"
       - ".github/workflows/*.yaml"
@@ -17,15 +21,48 @@ jobs:
     runs-on: ubuntu-latest
     strategy:
       matrix:
-        language: [python, actions]
+        language: [python, actions, cpp]
 
     steps:
       - name: Checkout repository
         uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
 
+      - name: Process .ino files
+        if: matrix.language == 'cpp'
+        run: |
+          # Create a mapping file to track renamed files
+          echo "{}" > renamed_files.json
+
+          # Find all .ino files and process them
+          find . -name "*.ino" -type f | while read -r file; do
+            echo "Processing $file"
+
+            # Get the relative path from repository root
+            rel_path=$(realpath --relative-to=. "$file")
+            cpp_path="${rel_path%.ino}.cpp"
+
+            # Create new .cpp file with Arduino.h include
+            echo "#include <Arduino.h>" > "$cpp_path"
+
+            # Append the original content
+            cat "$file" >> "$cpp_path"
+
+            # Update the mapping file
+            jq --arg ino "$rel_path" --arg cpp "$cpp_path" '. += {($cpp): $ino}' renamed_files.json > temp.json && mv temp.json renamed_files.json
+
+            # Remove the original .ino file
+            rm "$file"
+
+            echo "Converted $file to $cpp_path"
+          done
+
+          echo "Renamed files mapping:"
+          cat renamed_files.json
+
       - name: Initialize CodeQL
         uses: github/codeql-action/init@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
         with:
+          build-mode: none
           languages: ${{ matrix.language }}
           config-file: ./.github/codeql/codeql-config.yml
 
@@ -33,3 +70,19 @@ jobs:
         uses: github/codeql-action/analyze@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
         with:
           category: "/language:${{ matrix.language }}"
+          output: sarif-results
+          upload: failure-only
+
+      - name: Process SARIF file
+        if: matrix.language == 'cpp'
+        run: |
+          sarif_file="sarif-results/${{ matrix.language }}.sarif"
+
+          # Run the Python script to process the SARIF file
+          python3 .github/scripts/process_sarif.py "$sarif_file" "renamed_files.json"
+
+      - name: Upload SARIF file
+        uses: github/codeql-action/upload-sarif@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2
+        with:
+          sarif_file: sarif-results/${{ matrix.language }}.sarif
+          category: "/language:${{ matrix.language }}"

From 81cc594e63f50d5f3c2045b0cb069f06ff46fc27 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Sun, 3 Aug 2025 17:32:18 -0300
Subject: [PATCH 100/105] fix(push): Fix typo in yaml

---
 .github/workflows/push.yml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml
index fc85566aa8b..48530e30bc9 100644
--- a/.github/workflows/push.yml
+++ b/.github/workflows/push.yml
@@ -96,7 +96,7 @@ jobs:
               - 'libraries/Network/src/**'
             fs:
               - 'libraries/FS/src/**'
-            static_sketeches:
+            static_sketches:
               - 'libraries/NetworkClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino'
               - 'libraries/BLE/examples/Server/Server.ino'
               - 'libraries/ESP32/examples/Camera/CameraWebServer/CameraWebServer.ino'
@@ -112,7 +112,7 @@ jobs:
           IS_PR: ${{ github.event_name == 'pull_request' }}
           MAX_CHUNKS: ${{ env.MAX_CHUNKS }}
           BUILD_LIBRARIES: ${{ steps.changed-files.outputs.libraries_any_changed == 'true' }}
-          BUILD_STATIC_SKETCHES: ${{ steps.changed-files.outputs.static_sketeches_any_changed == 'true' }}
+          BUILD_STATIC_SKETCHES: ${{ steps.changed-files.outputs.static_sketches_any_changed == 'true' }}
           FS_CHANGED: ${{ steps.changed-files.outputs.fs_any_changed == 'true' }}
           NETWORKING_CHANGED: ${{ steps.changed-files.outputs.networking_any_changed == 'true' }}
           CORE_CHANGED: ${{ steps.changed-files.outputs.core_any_changed == 'true' }}

From f6b1910e8ba5a9aff99fa00b2133b10f34f85e4f Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Fri, 8 Aug 2025 10:22:19 -0300
Subject: [PATCH 101/105] fix(codeql): Remove rule causing false positives

---
 .github/codeql/codeql-config.yml | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/.github/codeql/codeql-config.yml b/.github/codeql/codeql-config.yml
index c640d7bd6ef..1c284c9d68e 100644
--- a/.github/codeql/codeql-config.yml
+++ b/.github/codeql/codeql-config.yml
@@ -20,7 +20,9 @@ query-filters:
       problem.severity:
         - recommendation
   - exclude:
-      id: tob/cpp/use-of-legacy-algorithm
+      id: tob/cpp/use-of-legacy-algorithm # We use legacy algorithms in many places for integrity checks
+  - exclude:
+      id: cpp/dead-code-goto # Too many false positives in no-build mode
 
 paths-ignore:
   - tests/**

From 9d13bcc674bb7176df5d52f319a6cb1b16e17653 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Wed, 13 Aug 2025 22:15:41 -0300
Subject: [PATCH 102/105] fix(tests): Change results folder

---
 .github/PULL_REQUEST_TEMPLATE.md    |  2 +-
 .github/workflows/tests.yml         | 36 ++++++++++++++++++++++++++++-
 .github/workflows/tests_build.yml   |  6 ++---
 .github/workflows/tests_hw.yml      | 31 +++++++++++++++++++++----
 .github/workflows/tests_qemu.yml    |  8 +++----
 .github/workflows/tests_results.yml | 12 +++++-----
 .github/workflows/tests_wokwi.yml   | 22 +++++++++++++-----
 README.md                           |  2 +-
 8 files changed, 93 insertions(+), 26 deletions(-)

diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 5e0d99c0457..6a803943690 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -13,7 +13,7 @@
 ## Description of Change
 Please describe your proposed Pull Request and it's impact.
 
-## Tests scenarios
+## Test Scenarios
 Please describe on what Hardware and Software combinations you have tested this Pull Request and how.
 
 (*eg. I have tested my Pull Request on Arduino-esp32 core v2.0.2 with ESP32 and ESP32-S2 Board with this scenario*)
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 058d9a3a793..925855844ac 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -28,7 +28,7 @@ on:
       - "!*.md"
       - "!*.properties"
   schedule:
-    - cron: "0 2 * * *"
+    - cron: "0 0 * * *"
 
 concurrency:
   group: tests-${{ github.event.pull_request.number || github.ref }}
@@ -45,9 +45,43 @@ jobs:
           name: event_file
           path: ${{ github.event_path }}
 
+  check-last-run:
+    name: Check last run
+    runs-on: ubuntu-latest
+    outputs:
+      run_tests: ${{ steps.last-run.outputs.run_tests }}
+    steps:
+      - name: Checkout
+        if: github.event_name != 'pull_request'
+        # if: github.event_name == 'schedule'
+        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+        with:
+          ref: gh-pages
+
+      - name: Get last run commit and compare with current commit
+        id: last-run
+        run: |
+          if [ ${{ github.event_name }} != 'pull_request' ]; then
+          # if [ ${{ github.event_name }} == 'schedule' ]; then
+            last_run_commit=$(jq -r '.commit_sha' ./runtime-test-results/test_results.json)
+            current_commit=${{ github.sha }}
+            if [ "$last_run_commit" == "$current_commit" ]; then
+              echo "Last run commit and current commit are the same. Skipping tests..."
+              echo "run_tests=false" >> $GITHUB_OUTPUT
+            else
+              echo "Last run commit and current commit are different. Running tests..."
+              echo "run_tests=true" >> $GITHUB_OUTPUT
+            fi
+          else
+            echo "Not a schedule event. Continuing..."
+            echo "run_tests=true" >> $GITHUB_OUTPUT
+          fi
+
   gen-matrix:
     name: Generate matrix
     runs-on: ubuntu-latest
+    if: ${{ needs.check-last-run.outputs.run_tests }}
+    needs: check-last-run
     outputs:
       build-types: ${{ steps.set-matrix.outputs.build-types }}
       hw-types: ${{ steps.set-matrix.outputs.hw-types }}
diff --git a/.github/workflows/tests_build.yml b/.github/workflows/tests_build.yml
index ac1f40644ed..c74224941af 100644
--- a/.github/workflows/tests_build.yml
+++ b/.github/workflows/tests_build.yml
@@ -24,7 +24,7 @@ jobs:
         if: github.event.pull_request.number != null
         uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
         with:
-          key: tests-${{ env.id }}-bin
+          key: test-${{ env.id }}-bin
           path: |
             ~/.arduino/tests/${{ inputs.chip }}/**/build*.tmp/*.bin
             ~/.arduino/tests/${{ inputs.chip }}/**/build*.tmp/*.elf
@@ -71,7 +71,7 @@ jobs:
         uses: actions/cache/save@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
         if: steps.check-build.outputs.enabled == 'true' && github.event.pull_request.number != null
         with:
-          key: tests-${{ env.id }}-bin
+          key: test-${{ env.id }}-bin
           path: |
             ~/.arduino/tests/${{ inputs.chip }}/**/build*.tmp/*.bin
             ~/.arduino/tests/${{ inputs.chip }}/**/build*.tmp/*.elf
@@ -81,7 +81,7 @@ jobs:
       - name: Upload ${{ inputs.chip }} ${{ inputs.type }} binaries as artifacts
         uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
         with:
-          name: tests-bin-${{ inputs.chip }}-${{ inputs.type }}
+          name: test-bin-${{ inputs.chip }}-${{ inputs.type }}
           overwrite: true
           path: |
             ~/.arduino/tests/${{ inputs.chip }}/**/build*.tmp/*.bin
diff --git a/.github/workflows/tests_hw.yml b/.github/workflows/tests_hw.yml
index 6f5fc67f7b9..d9fb755c94a 100644
--- a/.github/workflows/tests_hw.yml
+++ b/.github/workflows/tests_hw.yml
@@ -39,7 +39,7 @@ jobs:
         if: github.event.pull_request.number != null
         uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
         with:
-          key: tests-${{ env.id }}-results-hw
+          key: test-${{ env.id }}-results-hw
           path: |
             tests/**/*.xml
             tests/**/result_*.json
@@ -61,6 +61,7 @@ jobs:
         if: ${{ steps.check-tests.outputs.enabled == 'true' }}
         uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
         with:
+          # Workaround for missing files in checkout
           sparse-checkout: |
             *
 
@@ -84,7 +85,7 @@ jobs:
         if: ${{ steps.check-tests.outputs.enabled == 'true' }}
         uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1
         with:
-          name: tests-bin-${{ inputs.chip }}-${{ inputs.type }}
+          name: test-bin-${{ inputs.chip }}-${{ inputs.type }}
           path: |
             ~/.arduino/tests/${{ inputs.chip }}
 
@@ -102,7 +103,7 @@ jobs:
         uses: actions/cache/save@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
         if: steps.check-tests.outputs.enabled == 'true' && github.event.pull_request.number != null
         with:
-          key: tests-${{ env.id }}-results-hw
+          key: test-${{ env.id }}-results-hw
           path: |
             tests/**/*.xml
             tests/**/result_*.json
@@ -111,7 +112,29 @@ jobs:
         uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
         if: always()
         with:
-          name: tests-results-hw-${{ inputs.chip }}-${{ inputs.type }}
+          name: test-results-hw-${{ inputs.chip }}-${{ inputs.type }}
+          overwrite: true
+          path: |
+            tests/**/*.xml
+            tests/**/result_*.json
+
+  gitlab-tests:
+    name: Internal Hardware tests
+    runs-on: ubuntu-latest
+    if: false
+    # if: github.event_name == 'schedule'
+    steps:
+      # The decision to run the tests will be made inside GitLab
+      # GitLab should only perform the actual test execution and save the results as artifacts in
+      # a format that can be downloaded and parsed by this GitHub Actions workflow.
+
+
+
+      - name: Upload Internal Hardware test results as artifacts
+        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+        if: always()
+        with:
+          name: test-results-gitlab
           overwrite: true
           path: |
             tests/**/*.xml
diff --git a/.github/workflows/tests_qemu.yml b/.github/workflows/tests_qemu.yml
index fa3f874cbbb..d9ddf6e1b0c 100644
--- a/.github/workflows/tests_qemu.yml
+++ b/.github/workflows/tests_qemu.yml
@@ -23,7 +23,7 @@ jobs:
         if: github.event.pull_request.number != null
         uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
         with:
-          key: tests-${{ env.id }}-results-qemu
+          key: test-${{ env.id }}-results-qemu
           path: |
             tests/**/*.xml
             tests/**/result_*.json
@@ -115,7 +115,7 @@ jobs:
         if: ${{ steps.check-tests.outputs.enabled == 'true' }}
         uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1
         with:
-          name: tests-bin-${{ inputs.chip }}-${{ inputs.type }}
+          name: test-bin-${{ inputs.chip }}-${{ inputs.type }}
           path: |
             ~/.arduino/tests/${{ inputs.chip }}
 
@@ -127,7 +127,7 @@ jobs:
         uses: actions/cache/save@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
         if: steps.check-tests.outputs.enabled == 'true' && github.event.pull_request.number != null
         with:
-          key: tests-${{ env.id }}-results-qemu
+          key: test-${{ env.id }}-results-qemu
           path: |
             tests/**/*.xml
             tests/**/result_*.json
@@ -136,7 +136,7 @@ jobs:
         uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
         if: always()
         with:
-          name: tests-results-qemu-${{ inputs.chip }}-${{ inputs.type }}
+          name: test-results-qemu-${{ inputs.chip }}-${{ inputs.type }}
           overwrite: true
           path: |
             tests/**/*.xml
diff --git a/.github/workflows/tests_results.yml b/.github/workflows/tests_results.yml
index ebba2a3aa08..28227bfd3b1 100644
--- a/.github/workflows/tests_results.yml
+++ b/.github/workflows/tests_results.yml
@@ -113,7 +113,7 @@ jobs:
         with:
           script: |
             const ref = process.env.original_ref;
-            const key_prefix = 'tests-' + ref + '-';
+            const key_prefix = 'test-' + ref + '-';
 
             if (process.env.original_event == 'pull_request' && process.env.original_action != 'closed') {
               console.log('Skipping cache cleanup for open PR');
@@ -163,15 +163,15 @@ jobs:
       - name: Generate report
         if: ${{ !cancelled() && (env.original_event == 'schedule' || env.original_event == 'workflow_dispatch') }} # codespell:ignore cancelled
         env:
-          REPORT_FILE: ./runtime-tests-results/RUNTIME_TESTS_REPORT.md
+          REPORT_FILE: ./runtime-test-results/RUNTIME_TESTS_REPORT.md
           WOKWI_RUN_ID: ${{ github.event.workflow_run.id }}
           BUILD_RUN_ID: ${{ env.original_run_id }}
           IS_FAILING: ${{ env.original_conclusion == 'failure' || env.original_conclusion == 'timed_out' || github.event.workflow_run.conclusion == 'failure' || github.event.workflow_run.conclusion == 'timed_out' || job.status == 'failure' }}
         run: |
           rm -rf artifacts $REPORT_FILE
-          mv -f ./unity_results.json ./runtime-tests-results/unity_results.json
+          mv -f ./unity_results.json ./runtime-test-results/unity_results.json
           touch $REPORT_FILE
-          python3 ./runtime-tests-results/table_generator.py ./runtime-tests-results/unity_results.json >> $REPORT_FILE
+          python3 ./runtime-test-results/table_generator.py ./runtime-test-results/unity_results.json >> $REPORT_FILE
 
       - name: Generate badge
         if: ${{ !cancelled() && (env.original_event == 'schedule' || env.original_event == 'workflow_dispatch') }} # codespell:ignore cancelled
@@ -179,7 +179,7 @@ jobs:
         with:
           label: Runtime Tests
           status: ${{ job.status == 'success' && 'passing' || 'failing' }}
-          output: runtime-tests-results/badge.svg
+          output: runtime-test-results/badge.svg
           color: ${{ job.status == 'success' && 'green' || 'red' }}
           style: flat
 
@@ -190,6 +190,6 @@ jobs:
           git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
           if [[ `git status --porcelain` ]]; then
             git add --all
-            git commit -m "Updated runtime tests report"
+            git commit -m "Updated runtime test results"
             git push origin HEAD:gh-pages
           fi
diff --git a/.github/workflows/tests_wokwi.yml b/.github/workflows/tests_wokwi.yml
index 03dd64fc0fb..6af66cf0e42 100644
--- a/.github/workflows/tests_wokwi.yml
+++ b/.github/workflows/tests_wokwi.yml
@@ -135,17 +135,27 @@ jobs:
         with:
           github-token: ${{ secrets.GITHUB_TOKEN }}
           run-id: ${{ github.event.workflow_run.id }}
-          pattern: tests-results-hw-*
+          pattern: test-results-hw-*
           merge-multiple: true
           path: artifacts/results/hw
 
+      - name: Download and extract parent GitLab results
+        uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1
+        continue-on-error: true
+        with:
+          github-token: ${{ secrets.GITHUB_TOKEN }}
+          run-id: ${{ github.event.workflow_run.id }}
+          pattern: test-results-gitlab
+          merge-multiple: true
+          path: artifacts/results/gitlab
+
       - name: Download and extract parent QEMU results
         uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e # v4.2.1
         continue-on-error: true
         with:
           github-token: ${{ secrets.GITHUB_TOKEN }}
           run-id: ${{ github.event.workflow_run.id }}
-          pattern: tests-results-qemu-*
+          pattern: test-results-qemu-*
           merge-multiple: true
           path: artifacts/results/qemu
 
@@ -221,7 +231,7 @@ jobs:
         if: needs.get-artifacts.outputs.pr_num
         uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
         with:
-          key: tests-${{ env.id }}-results-wokwi
+          key: test-${{ env.id }}-results-wokwi
           path: |
             tests/**/*.xml
             tests/**/result_*.json
@@ -274,7 +284,7 @@ jobs:
         with:
           github-token: ${{ secrets.GITHUB_TOKEN }}
           run-id: ${{ github.event.workflow_run.id }}
-          name: tests-bin-${{ matrix.chip }}-${{ matrix.type }}
+          name: test-bin-${{ matrix.chip }}-${{ matrix.type }}
           path: |
             ~/.arduino/tests/${{ matrix.chip }}
 
@@ -289,7 +299,7 @@ jobs:
         uses: actions/cache/save@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
         if: steps.check-tests.outputs.enabled == 'true' && needs.get-artifacts.outputs.pr_num
         with:
-          key: tests-${{ env.id }}-results-wokwi
+          key: test-${{ env.id }}-results-wokwi
           path: |
             tests/**/*.xml
             tests/**/result_*.json
@@ -298,7 +308,7 @@ jobs:
         uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
         if: always()
         with:
-          name: tests-results-wokwi-${{ matrix.chip }}-${{ matrix.type }}
+          name: test-results-wokwi-${{ matrix.chip }}-${{ matrix.type }}
           overwrite: true
           path: |
             tests/**/*.xml
diff --git a/README.md b/README.md
index f40315c03cc..f8ff1f28eaa 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
 [![Build Status](https://img.shields.io/github/actions/workflow/status/espressif/arduino-esp32/push.yml?branch=master&event=push&label=Compilation%20Tests)](https://github.com/espressif/arduino-esp32/actions/workflows/push.yml?query=branch%3Amaster+event%3Apush)
 [![Verbose Build Status](https://img.shields.io/github/actions/workflow/status/espressif/arduino-esp32/push.yml?branch=master&event=schedule&label=Compilation%20Tests%20(Verbose))](https://github.com/espressif/arduino-esp32/actions/workflows/push.yml?query=branch%3Amaster+event%3Aschedule)
 [![External Libraries Test](https://img.shields.io/github/actions/workflow/status/espressif/arduino-esp32/lib.yml?branch=master&event=schedule&label=External%20Libraries%20Test)](https://github.com/espressif/arduino-esp32/blob/gh-pages/LIBRARIES_TEST.md)
-[![Runtime Tests](https://github.com/espressif/arduino-esp32/blob/gh-pages/runtime-tests-results/badge.svg)](https://github.com/espressif/arduino-esp32/blob/gh-pages/runtime-tests-results/RUNTIME_TESTS_REPORT.md)
+[![Runtime Tests](https://github.com/espressif/arduino-esp32/blob/gh-pages/runtime-test-results/badge.svg)](https://github.com/espressif/arduino-esp32/blob/gh-pages/runtime-test-results/RUNTIME_TEST_RESULTS.md)
 
 ### Need help or have a question? Join the chat at [Discord](https://discord.gg/8xY6e9crwv) or [open a new Discussion](https://github.com/espressif/arduino-esp32/discussions)
 

From e38dba808f2a189e53d2e683f2d0faa8085e7605 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Wed, 13 Aug 2025 22:22:53 -0300
Subject: [PATCH 103/105] fix(tests): Fix last commit check

---
 .github/workflows/tests.yml | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 925855844ac..4b915cf36de 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -63,13 +63,19 @@ jobs:
         run: |
           if [ ${{ github.event_name }} != 'pull_request' ]; then
           # if [ ${{ github.event_name }} == 'schedule' ]; then
-            last_run_commit=$(jq -r '.commit_sha' ./runtime-test-results/test_results.json)
+            if [ -f ./runtime-test-results/test_results.json ]; then
+              last_run_commit=$(jq -r '.commit_sha' ./runtime-test-results/test_results.json)
+              last_run_failed=$(jq -r '.tests_failed' ./runtime-test-results/test_results.json)
+            else
+              last_run_commit="none"
+              last_run_failed="true"
+            fi
             current_commit=${{ github.sha }}
-            if [ "$last_run_commit" == "$current_commit" ]; then
+            if [ "$last_run_commit" == "$current_commit" ] && [ "$last_run_failed" == "false" ]; then
               echo "Last run commit and current commit are the same. Skipping tests..."
               echo "run_tests=false" >> $GITHUB_OUTPUT
             else
-              echo "Last run commit and current commit are different. Running tests..."
+              echo "Last run commit and current commit are different or last run failed. Running tests..."
               echo "run_tests=true" >> $GITHUB_OUTPUT
             fi
           else

From ead6c1cc9485d1f68d369c643c3efd8358f2a283 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Wed, 13 Aug 2025 23:52:27 -0300
Subject: [PATCH 104/105] fix(tests): Move results to proper folder

---
 .github/workflows/tests_hw.yml      | 22 ----------------------
 .github/workflows/tests_results.yml |  1 +
 2 files changed, 1 insertion(+), 22 deletions(-)

diff --git a/.github/workflows/tests_hw.yml b/.github/workflows/tests_hw.yml
index d9fb755c94a..e095ebe6dc8 100644
--- a/.github/workflows/tests_hw.yml
+++ b/.github/workflows/tests_hw.yml
@@ -117,25 +117,3 @@ jobs:
           path: |
             tests/**/*.xml
             tests/**/result_*.json
-
-  gitlab-tests:
-    name: Internal Hardware tests
-    runs-on: ubuntu-latest
-    if: false
-    # if: github.event_name == 'schedule'
-    steps:
-      # The decision to run the tests will be made inside GitLab
-      # GitLab should only perform the actual test execution and save the results as artifacts in
-      # a format that can be downloaded and parsed by this GitHub Actions workflow.
-
-
-
-      - name: Upload Internal Hardware test results as artifacts
-        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
-        if: always()
-        with:
-          name: test-results-gitlab
-          overwrite: true
-          path: |
-            tests/**/*.xml
-            tests/**/result_*.json
diff --git a/.github/workflows/tests_results.yml b/.github/workflows/tests_results.yml
index 28227bfd3b1..56883ecf52e 100644
--- a/.github/workflows/tests_results.yml
+++ b/.github/workflows/tests_results.yml
@@ -172,6 +172,7 @@ jobs:
           mv -f ./unity_results.json ./runtime-test-results/unity_results.json
           touch $REPORT_FILE
           python3 ./runtime-test-results/table_generator.py ./runtime-test-results/unity_results.json >> $REPORT_FILE
+          mv -f ./test_results.json ./runtime-test-results/test_results.json
 
       - name: Generate badge
         if: ${{ !cancelled() && (env.original_event == 'schedule' || env.original_event == 'workflow_dispatch') }} # codespell:ignore cancelled

From faa9388d203071f63ef75c59875381623ca5ed36 Mon Sep 17 00:00:00 2001
From: Lucas Saavedra Vaz <32426024+lucasssvaz@users.noreply.github.com>
Date: Thu, 14 Aug 2025 09:23:24 -0300
Subject: [PATCH 105/105] fix(tests): Remove useless check

---
 .github/workflows/tests.yml         | 40 -----------------------------
 .github/workflows/tests_results.yml |  2 +-
 2 files changed, 1 insertion(+), 41 deletions(-)

diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 4b915cf36de..bd41f2ec61f 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -45,49 +45,9 @@ jobs:
           name: event_file
           path: ${{ github.event_path }}
 
-  check-last-run:
-    name: Check last run
-    runs-on: ubuntu-latest
-    outputs:
-      run_tests: ${{ steps.last-run.outputs.run_tests }}
-    steps:
-      - name: Checkout
-        if: github.event_name != 'pull_request'
-        # if: github.event_name == 'schedule'
-        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
-        with:
-          ref: gh-pages
-
-      - name: Get last run commit and compare with current commit
-        id: last-run
-        run: |
-          if [ ${{ github.event_name }} != 'pull_request' ]; then
-          # if [ ${{ github.event_name }} == 'schedule' ]; then
-            if [ -f ./runtime-test-results/test_results.json ]; then
-              last_run_commit=$(jq -r '.commit_sha' ./runtime-test-results/test_results.json)
-              last_run_failed=$(jq -r '.tests_failed' ./runtime-test-results/test_results.json)
-            else
-              last_run_commit="none"
-              last_run_failed="true"
-            fi
-            current_commit=${{ github.sha }}
-            if [ "$last_run_commit" == "$current_commit" ] && [ "$last_run_failed" == "false" ]; then
-              echo "Last run commit and current commit are the same. Skipping tests..."
-              echo "run_tests=false" >> $GITHUB_OUTPUT
-            else
-              echo "Last run commit and current commit are different or last run failed. Running tests..."
-              echo "run_tests=true" >> $GITHUB_OUTPUT
-            fi
-          else
-            echo "Not a schedule event. Continuing..."
-            echo "run_tests=true" >> $GITHUB_OUTPUT
-          fi
-
   gen-matrix:
     name: Generate matrix
     runs-on: ubuntu-latest
-    if: ${{ needs.check-last-run.outputs.run_tests }}
-    needs: check-last-run
     outputs:
       build-types: ${{ steps.set-matrix.outputs.build-types }}
       hw-types: ${{ steps.set-matrix.outputs.hw-types }}
diff --git a/.github/workflows/tests_results.yml b/.github/workflows/tests_results.yml
index 56883ecf52e..d33221c129d 100644
--- a/.github/workflows/tests_results.yml
+++ b/.github/workflows/tests_results.yml
@@ -163,7 +163,7 @@ jobs:
       - name: Generate report
         if: ${{ !cancelled() && (env.original_event == 'schedule' || env.original_event == 'workflow_dispatch') }} # codespell:ignore cancelled
         env:
-          REPORT_FILE: ./runtime-test-results/RUNTIME_TESTS_REPORT.md
+          REPORT_FILE: ./runtime-test-results/RUNTIME_TEST_RESULTS.md
           WOKWI_RUN_ID: ${{ github.event.workflow_run.id }}
           BUILD_RUN_ID: ${{ env.original_run_id }}
           IS_FAILING: ${{ env.original_conclusion == 'failure' || env.original_conclusion == 'timed_out' || github.event.workflow_run.conclusion == 'failure' || github.event.workflow_run.conclusion == 'timed_out' || job.status == 'failure' }}
