feat(zigbee): upgrade zigbee example to v2.0

This commit is contained in:
xieqinan@espressif.com
2026-09-09 11:34:28 +08:00
parent a8a5106421
commit 256403fe73
53 changed files with 1880 additions and 1251 deletions
@@ -3,6 +3,9 @@
cmake_minimum_required(VERSION 3.22)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
list(PREPEND SDKCONFIG_DEFAULTS
"${IDF_PATH}/examples/zigbee/zb_common_components/example_common/sdkconfig.mbedtls_minimal"
"sdkconfig.defaults")
# "Trim" the build. Include the minimal set of components, main, and anything it depends on.
idf_build_set_property(MINIMAL_BUILD ON)
project(light_bulb)
@@ -1,9 +1,9 @@
| Supported Targets | ESP32-C5 | ESP32-C6 | ESP32-H2 |
| ----------------- | -------- | -------- | -------- |
| Supported Targets | ESP32-C5 | ESP32-C6 | ESP32-H2 | ESP32-H21 | ESP32-H4 | ESP32-S31 |
| ----------------- | -------- | -------- | -------- | --------- | -------- | --------- |
# Light Bulb Example
This test code shows how to configure Zigbee end device and use it as HA on/off light bulb.
This example demonstrates how to configure a Home Automation on/off light on a Zigbee Coordinator using ESP Zigbee SDK v2.
The ESP Zigbee SDK provides more examples and tools for productization:
* [ESP Zigbee SDK Docs](https://docs.espressif.com/projects/esp-zigbee-sdk)
@@ -11,13 +11,13 @@ The ESP Zigbee SDK provides more examples and tools for productization:
## Hardware Required
* One development board with ESP32-H2 SoC acting as Zigbee end-device (loaded with HA_on_off_light example)
* One 802.15.4-enabled development board running this example as a Zigbee Coordinator
* A USB cable for power supply and programming
* Choose another ESP32-H2 as Zigbee coordinator (see [HA_on_off_switch example](../HA_on_off_switch))
* A second board running as a Zigbee Router/End Device (see [HA_on_off_switch](../HA_on_off_switch))
## Configure the project
Before project configuration and build, make sure to set the correct chip target using `idf.py --preview set-target TARGET` command.
Before project configuration and build, make sure to set the correct chip target using `idf.py set-target TARGET`.
## Erase the NVRAM
@@ -31,36 +31,28 @@ Build the project, flash it to the board, and start the monitor tool to view the
## Example Output
As you run the example, you will see the following log:
When the program starts, the board forms a Zigbee network and opens it for joining. As you run the example, you will see output similar to:
```
I (403) app_start: Starting scheduler on CPU0
I (408) main_task: Started on CPU0
I (408) main_task: Calling app_main()
I (428) phy: phy_version: 230,2, 9aae6ea, Jan 15 2024, 11:17:12
I (428) phy: libbtbb version: 944f18e, Jan 15 2024, 11:17:25
I (438) main_task: Returned from app_main()
I (548) ESP_ZB_ON_OFF_LIGHT: ZDO signal: ZDO Config Ready (0x17), status: ESP_FAIL
I (548) ESP_ZB_ON_OFF_LIGHT: Initialize Zigbee stack
W (548) rmt: channel resolution loss, real=10666666
I (558) gpio: GPIO[8]| InputEn: 0| OutputEn: 1| OpenDrain: 0| Pullup: 1| Pulldown: 0| Intr:0
I (548) ESP_ZB_ON_OFF_LIGHT: Deferred driver initialization successful
I (568) ESP_ZB_ON_OFF_LIGHT: Device started up in factory-reset mode
I (578) ESP_ZB_ON_OFF_LIGHT: Start network steering
I (3558) ESP_ZB_ON_OFF_LIGHT: Joined network successfully (Extended PAN ID: 74:4d:bd:ff:fe:63:f7:30, PAN ID: 0x13af, Channel:13, Short Address: 0x7c16)
I (10238) ESP_ZB_ON_OFF_LIGHT: Received message: endpoint(10), cluster(0x6), attribute(0x0), data size(1)
I (10238) ESP_ZB_ON_OFF_LIGHT: Light sets to On
I (10798) ESP_ZB_ON_OFF_LIGHT: Received message: endpoint(10), cluster(0x6), attribute(0x0), data size(1)
I (10798) ESP_ZB_ON_OFF_LIGHT: Light sets to Off
I (11228) ESP_ZB_ON_OFF_LIGHT: Received message: endpoint(10), cluster(0x6), attribute(0x0), data size(1)
I (11228) ESP_ZB_ON_OFF_LIGHT: Light sets to On
I (11618) ESP_ZB_ON_OFF_LIGHT: Received message: endpoint(10), cluster(0x6), attribute(0x0), data size(1)
I (11618) ESP_ZB_ON_OFF_LIGHT: Light sets to Off
I (435) ON_OFF_LIGHT: Start ESP Zigbee Stack
I (475) ON_OFF_LIGHT: Initialize Zigbee stack
I (475) ON_OFF_LIGHT: Deferred driver initialization successful
I (485) ON_OFF_LIGHT: Device started up in factory-reset mode
I (795) ON_OFF_LIGHT: Formed network successfully: PAN ID(0x3051, EXT: 0x4831b7fffec183f0), Channel(13), Short Address(0x0000)
I (1175) ON_OFF_LIGHT: Network steering completed
I (3705) ON_OFF_LIGHT: New device commissioned or rejoined(short: 0xa515)
```
## Light Control Functions
* By toggling the switch button (BOOT) on the ESP32-H2 board loaded with the `HA_on_off_switch` example, the LED on this board loaded with `HA_on_off_light` example will be on and off.
* By toggling the switch button (BOOT) on the board loaded with the `HA_on_off_switch` example, the LED on this board will turn on and off.
```
I (26905) ON_OFF_LIGHT: ZCL SetAttributeValue message for endpoint(10) cluster(0x0006) server with status(0x00)
I (26905) ON_OFF_LIGHT: Set On/Off: 1
I (27535) ON_OFF_LIGHT: ZCL SetAttributeValue message for endpoint(10) cluster(0x0006) server with status(0x00)
I (27535) ON_OFF_LIGHT: Set On/Off: 0
```
## Troubleshooting
@@ -1,5 +1,3 @@
idf_component_register(
SRC_DIRS "."
INCLUDE_DIRS "."
PRIV_REQUIRES nvs_flash esp_driver_uart ieee802154
)
idf_component_register(SRC_DIRS "."
PRIV_INCLUDE_DIRS "."
PRIV_REQUIRES nvs_flash esp_driver_uart ieee802154)
@@ -1,7 +1,7 @@
/*
* SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD
* SPDX-FileCopyrightText: 2021-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: LicenseRef-Included
* SPDX-License-Identifier: LicenseRef-Included
*
* Zigbee HA_on_off_light Example
*
@@ -11,141 +11,188 @@
* software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied.
*/
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_check.h"
#include "esp_err.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "ha/esp_zigbee_ha_standard.h"
#include "zcl_utility.h"
#include "light_driver.h"
#include "alarm_timer.h"
#include "esp_zigbee.h"
#include "ezbee/zha.h"
#include "esp_zb_light.h"
#if !defined ZB_ED_ROLE
#error Define ZB_ED_ROLE in idf.py menuconfig to compile light (End Device) source code.
#endif
static const char *TAG = "ON_OFF_LIGHT";
static const char *TAG = "ESP_ZB_ON_OFF_LIGHT";
/********************* Define functions **************************/
static esp_err_t deferred_driver_init(void)
esp_err_t deferred_driver_init(void)
{
light_driver_init(LIGHT_DEFAULT_OFF);
static bool is_inited = false;
ESP_RETURN_ON_FALSE(!is_inited, ESP_OK, TAG, "Deferred driver already initialized");
light_driver_init(false);
is_inited = true;
return ESP_OK;
}
static void bdb_start_top_level_commissioning_cb(uint8_t mode_mask)
static void esp_zigbee_alarm_bdb_commissioning(alarm_timer_arg_t arg)
{
ESP_RETURN_ON_FALSE(esp_zb_bdb_start_top_level_commissioning(mode_mask) == ESP_OK, , TAG, "Failed to start Zigbee commissioning");
esp_zigbee_lock_acquire(portMAX_DELAY);
(void)ezb_bdb_start_top_level_commissioning(arg);
esp_zigbee_lock_release();
}
void esp_zb_app_signal_handler(esp_zb_app_signal_t *signal_struct)
static bool esp_zigbee_app_signal_handler(const ezb_app_signal_t *app_signal)
{
uint32_t *p_sg_p = signal_struct->p_app_signal;
esp_err_t err_status = signal_struct->esp_err_status;
esp_zb_app_signal_type_t sig_type = *p_sg_p;
switch (sig_type) {
case ESP_ZB_ZDO_SIGNAL_SKIP_STARTUP:
ezb_app_signal_type_t signal_type = ezb_app_signal_get_type(app_signal);
switch (signal_type) {
case EZB_ZDO_SIGNAL_SKIP_STARTUP:
ESP_LOGI(TAG, "Initialize Zigbee stack");
esp_zb_bdb_start_top_level_commissioning(ESP_ZB_BDB_MODE_INITIALIZATION);
ezb_bdb_start_top_level_commissioning(EZB_BDB_MODE_INITIALIZATION);
break;
case ESP_ZB_BDB_SIGNAL_DEVICE_FIRST_START:
case ESP_ZB_BDB_SIGNAL_DEVICE_REBOOT:
if (err_status == ESP_OK) {
case EZB_BDB_SIGNAL_DEVICE_FIRST_START:
case EZB_BDB_SIGNAL_DEVICE_REBOOT: {
ezb_bdb_comm_status_t status = *((ezb_bdb_comm_status_t *)ezb_app_signal_get_params(app_signal));
if (status == EZB_BDB_STATUS_SUCCESS) {
ESP_LOGI(TAG, "Deferred driver initialization %s", deferred_driver_init() ? "failed" : "successful");
ESP_LOGI(TAG, "Device started up in %s factory-reset mode", esp_zb_bdb_is_factory_new() ? "" : "non");
if (esp_zb_bdb_is_factory_new()) {
ESP_LOGI(TAG, "Start network steering");
esp_zb_bdb_start_top_level_commissioning(ESP_ZB_BDB_MODE_NETWORK_STEERING);
ESP_LOGI(TAG, "Device started up in%s factory-reset mode", ezb_bdb_is_factory_new() ? "" : " non");
if (ezb_bdb_is_factory_new()) {
ezb_bdb_start_top_level_commissioning(EZB_BDB_MODE_NETWORK_FORMATION);
} else {
ESP_LOGI(TAG, "Device rebooted");
ezb_bdb_open_network(180);
ESP_LOGI(TAG, "Device reboot");
}
} else {
/* commissioning failed */
ESP_LOGW(TAG, "Failed to initialize Zigbee stack (status: %s)", esp_err_to_name(err_status));
ESP_LOGW(TAG, "%s failed with status(0x%02x), please retry", ezb_app_signal_to_string(signal_type), status);
alarm_timer_schedule(esp_zigbee_alarm_bdb_commissioning, EZB_BDB_MODE_INITIALIZATION, 1000);
}
break;
case ESP_ZB_BDB_SIGNAL_STEERING:
if (err_status == ESP_OK) {
esp_zb_ieee_addr_t extended_pan_id;
esp_zb_get_extended_pan_id(extended_pan_id);
ESP_LOGI(TAG, "Joined network successfully (Extended PAN ID: %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x, PAN ID: 0x%04hx, Channel:%d, Short Address: 0x%04hx)",
extended_pan_id[7], extended_pan_id[6], extended_pan_id[5], extended_pan_id[4],
extended_pan_id[3], extended_pan_id[2], extended_pan_id[1], extended_pan_id[0],
esp_zb_get_pan_id(), esp_zb_get_current_channel(), esp_zb_get_short_address());
} break;
case EZB_BDB_SIGNAL_FORMATION: {
ezb_bdb_comm_status_t status = *((ezb_bdb_comm_status_t *)ezb_app_signal_get_params(app_signal));
if (status == EZB_BDB_STATUS_SUCCESS) {
ezb_extpanid_t extended_pan_id;
ezb_nwk_get_extended_panid(&extended_pan_id);
ESP_LOGI(TAG, "Formed network successfully: PAN ID(0x%04hx, EXT: 0x%llx), Channel(%d), Short Address(0x%04hx)",
ezb_nwk_get_panid(), extended_pan_id.u64, ezb_nwk_get_current_channel(), ezb_nwk_get_short_address());
ezb_bdb_start_top_level_commissioning(EZB_BDB_MODE_NETWORK_STEERING);
} else {
ESP_LOGI(TAG, "Network steering was not successful (status: %s)", esp_err_to_name(err_status));
esp_zb_scheduler_alarm((esp_zb_callback_t)bdb_start_top_level_commissioning_cb, ESP_ZB_BDB_MODE_NETWORK_STEERING, 1000);
ESP_LOGW(TAG, "Failed to form network with status(0x%02x)", status);
alarm_timer_schedule(esp_zigbee_alarm_bdb_commissioning, EZB_BDB_MODE_NETWORK_FORMATION, 1000);
}
break;
} break;
case EZB_BDB_SIGNAL_STEERING: {
ezb_bdb_comm_status_t status = *((ezb_bdb_comm_status_t *)ezb_app_signal_get_params(app_signal));
if (status == EZB_BDB_STATUS_SUCCESS) {
ESP_LOGI(TAG, "Network steering completed");
} else {
ESP_LOGW(TAG, "Failed to steering network with status(0x%02x)", status);
alarm_timer_schedule(esp_zigbee_alarm_bdb_commissioning, EZB_BDB_MODE_NETWORK_STEERING, 1000);
}
} break;
case EZB_ZDO_SIGNAL_DEVICE_ANNCE: {
const ezb_zdo_signal_device_annce_params_t *dev_annce_params = ezb_app_signal_get_params(app_signal);
ESP_LOGI(TAG, "New device commissioned or rejoined(short: 0x%04hx)", dev_annce_params->short_addr);
} break;
case EZB_NWK_SIGNAL_PERMIT_JOIN_STATUS: {
uint8_t duration = *(uint8_t *)ezb_app_signal_get_params(app_signal);
if (duration) {
ESP_LOGI(TAG, "Network(0x%04hx) is open for %d seconds", ezb_nwk_get_panid(), duration);
} else {
ESP_LOGW(TAG, "Network(0x%04hx) closed, devices joining not allowed.", ezb_nwk_get_panid());
}
} break;
default:
ESP_LOGI(TAG, "ZDO signal: %s (0x%x), status: %s", esp_zb_zdo_signal_to_string(sig_type), sig_type,
esp_err_to_name(err_status));
ESP_LOGI(TAG, "Zigbee APP Signal: %s(type: 0x%02x)", ezb_app_signal_to_string(signal_type), signal_type);
break;
}
return true;
}
static esp_err_t zb_attribute_handler(const esp_zb_zcl_set_attr_value_message_t *message)
static void zcl_core_set_attr_value_handler(ezb_zcl_set_attr_value_message_t *message)
{
esp_err_t ret = ESP_OK;
bool light_state = 0;
ESP_RETURN_ON_FALSE(message, ESP_FAIL, TAG, "Empty message");
ESP_RETURN_ON_FALSE(message->info.status == ESP_ZB_ZCL_STATUS_SUCCESS, ESP_ERR_INVALID_ARG, TAG, "Received message: error status(%d)",
message->info.status);
ESP_LOGI(TAG, "Received message: endpoint(%d), cluster(0x%x), attribute(0x%x), data size(%d)", message->info.dst_endpoint, message->info.cluster,
message->attribute.id, message->attribute.data.size);
if (message->info.dst_endpoint == HA_ESP_LIGHT_ENDPOINT) {
if (message->info.cluster == ESP_ZB_ZCL_CLUSTER_ID_ON_OFF) {
if (message->attribute.id == ESP_ZB_ZCL_ATTR_ON_OFF_ON_OFF_ID && message->attribute.data.type == ESP_ZB_ZCL_ATTR_TYPE_BOOL) {
light_state = message->attribute.data.value ? *(bool *)message->attribute.data.value : light_state;
ESP_LOGI(TAG, "Light sets to %s", light_state ? "On" : "Off");
light_driver_set_power(light_state);
}
}
ESP_RETURN_ON_FALSE(message, , TAG, "message is empty");
ESP_LOGI(TAG, "ZCL SetAttributeValue message for endpoint(%d) cluster(0x%04x) %s with status(0x%02x)", message->info.dst_ep,
message->info.cluster_id, message->info.cluster_role == EZB_ZCL_CLUSTER_SERVER ? "server" : "client",
message->info.status);
if (message->info.cluster_id == EZB_ZCL_CLUSTER_ID_ON_OFF) {
light_driver_set_power(*(uint8_t *)message->in.attribute.data.value);
ESP_LOGI(TAG, "Set On/Off: %d", *(uint8_t *)message->in.attribute.data.value);
} else {
ESP_LOGW(TAG, "Unsupported cluster ID(0x%04x)", message->info.cluster_id);
}
return ret;
}
static esp_err_t zb_action_handler(esp_zb_core_action_callback_id_t callback_id, const void *message)
static void esp_zigbee_zcl_core_action_handler(ezb_zcl_core_action_callback_id_t callback_id, void *message)
{
esp_err_t ret = ESP_OK;
switch (callback_id) {
case ESP_ZB_CORE_SET_ATTR_VALUE_CB_ID:
ret = zb_attribute_handler((esp_zb_zcl_set_attr_value_message_t *)message);
case EZB_ZCL_CORE_SET_ATTR_VALUE_CB_ID:
zcl_core_set_attr_value_handler(message);
break;
case EZB_ZCL_CORE_DEFAULT_RSP_CB_ID: {
ezb_zcl_cmd_default_rsp_message_t *default_rsp = (ezb_zcl_cmd_default_rsp_message_t *)message;
ESP_LOGI(TAG, "Received ZCL Default Response with status(0x%02x)", default_rsp->in.status_code);
} break;
default:
ESP_LOGW(TAG, "Receive Zigbee action(0x%x) callback", callback_id);
ESP_LOGW(TAG, "ZCL Core Action: ID(0x%04lx)", callback_id);
break;
}
return ret;
}
static void esp_zb_task(void *pvParameters)
esp_err_t esp_zigbee_create_zha_on_off_light_device(void)
{
/* initialize Zigbee stack */
esp_zb_cfg_t zb_nwk_cfg = ESP_ZB_ZED_CONFIG();
esp_zb_init(&zb_nwk_cfg);
esp_zb_on_off_light_cfg_t light_cfg = ESP_ZB_DEFAULT_ON_OFF_LIGHT_CONFIG();
esp_zb_ep_list_t *esp_zb_on_off_light_ep = esp_zb_on_off_light_ep_create(HA_ESP_LIGHT_ENDPOINT, &light_cfg);
zcl_basic_manufacturer_info_t info = {
.manufacturer_name = ESP_MANUFACTURER_NAME,
.model_identifier = ESP_MODEL_IDENTIFIER,
};
ezb_af_device_desc_t dev_desc = ezb_af_create_device_desc();
ezb_zha_on_off_light_config_t light_cfg = EZB_ZHA_ON_OFF_LIGHT_CONFIG();
ezb_af_ep_desc_t ep_desc = ezb_zha_create_on_off_light(ESP_ZIGBEE_HA_ON_OFF_LIGHT_EP_ID, &light_cfg);
ezb_zcl_cluster_desc_t basic_desc = {0};
esp_zcl_utility_add_ep_basic_manufacturer_info(esp_zb_on_off_light_ep, HA_ESP_LIGHT_ENDPOINT, &info);
esp_zb_device_register(esp_zb_on_off_light_ep);
esp_zb_core_action_handler_register(zb_action_handler);
esp_zb_set_primary_network_channel_set(ESP_ZB_PRIMARY_CHANNEL_MASK);
ESP_ERROR_CHECK(esp_zb_start(false));
esp_zb_stack_main_loop();
basic_desc = ezb_af_endpoint_get_cluster_desc(ep_desc, EZB_ZCL_CLUSTER_ID_BASIC, EZB_ZCL_CLUSTER_SERVER);
ezb_zcl_basic_cluster_desc_add_attr(basic_desc, EZB_ZCL_ATTR_BASIC_MANUFACTURER_NAME_ID, (void *)ESP_MANUFACTURER_NAME);
ezb_zcl_basic_cluster_desc_add_attr(basic_desc, EZB_ZCL_ATTR_BASIC_MODEL_IDENTIFIER_ID, (void *)ESP_MODEL_IDENTIFIER);
ESP_ERROR_CHECK(ezb_af_device_add_endpoint_desc(dev_desc, ep_desc));
ESP_ERROR_CHECK(ezb_af_device_desc_register(dev_desc));
ezb_zcl_core_action_handler_register(esp_zigbee_zcl_core_action_handler);
return ESP_OK;
}
esp_err_t esp_zigbee_setup_commissioning(void)
{
ezb_aps_secur_enable_distributed_security(false);
ESP_ERROR_CHECK(ezb_bdb_set_primary_channel_set(ESP_ZIGBEE_PRIMARY_CHANNEL_MASK));
ESP_ERROR_CHECK(ezb_bdb_set_secondary_channel_set(ESP_ZIGBEE_SECONDARY_CHANNEL_MASK));
ESP_ERROR_CHECK(ezb_app_signal_add_handler(esp_zigbee_app_signal_handler));
return ESP_OK;
}
static void esp_zigbee_stack_main_task(void *pvParameters)
{
esp_zigbee_config_t config = ESP_ZIGBEE_DEFAULT_CONFIG();
ESP_ERROR_CHECK(esp_zigbee_init(&config));
ESP_ERROR_CHECK(esp_zigbee_setup_commissioning());
ESP_ERROR_CHECK(esp_zigbee_create_zha_on_off_light_device());
ESP_ERROR_CHECK(esp_zigbee_start(false));
esp_zigbee_launch_mainloop();
esp_zigbee_deinit();
vTaskDelete(NULL);
}
void app_main(void)
{
esp_zb_platform_config_t config = {
.radio_config = ESP_ZB_DEFAULT_RADIO_CONFIG(),
.host_config = ESP_ZB_DEFAULT_HOST_CONFIG(),
};
ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_zb_platform_config(&config));
xTaskCreate(esp_zb_task, "Zigbee_main", 4096, NULL, 5, NULL);
ESP_LOGI(TAG, "Start ESP Zigbee Stack");
xTaskCreate(esp_zigbee_stack_main_task, "Zigbee_main", 4096, NULL, 5, NULL);
}
@@ -1,7 +1,7 @@
/*
* SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD
* SPDX-FileCopyrightText: 2021-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: LicenseRef-Included
* SPDX-License-Identifier: LicenseRef-Included
*
* Zigbee HA_on_off_light Example
*
@@ -12,36 +12,41 @@
* CONDITIONS OF ANY KIND, either express or implied.
*/
#include "esp_zigbee_core.h"
#include "light_driver.h"
#pragma once
/* Zigbee configuration */
#define INSTALLCODE_POLICY_ENABLE false /* enable the install code policy for security */
#define ED_AGING_TIMEOUT ESP_ZB_ED_AGING_TIMEOUT_64MIN /* aging timeout of device */
#define ED_KEEP_ALIVE 3000 /* 3000 millisecond */
#define HA_ESP_LIGHT_ENDPOINT 10 /* esp light bulb device endpoint, used to process light controlling commands */
#define ESP_ZB_PRIMARY_CHANNEL_MASK ESP_ZB_TRANSCEIVER_ALL_CHANNELS_MASK /* Zigbee primary channel mask use in the example */
#define ESP_ZIGBEE_PRIMARY_CHANNEL_MASK (1U << CONFIG_ZB_EXAMPLE_PRIMARY_CHANNEL)
#define ESP_ZIGBEE_SECONDARY_CHANNEL_MASK CONFIG_ZB_EXAMPLE_SECONDARY_CHANNEL_MASK
/* Basic manufacturer information */
#define ESP_MANUFACTURER_NAME "\x09""ESPRESSIF" /* Customized manufacturer name */
#define ESP_MODEL_IDENTIFIER "\x07"CONFIG_IDF_TARGET /* Customized model identifier */
#define ESP_ZIGBEE_HA_ON_OFF_LIGHT_EP_ID (10)
#define ESP_ZB_ZED_CONFIG() \
{ \
.esp_zb_role = ESP_ZB_DEVICE_TYPE_ED, \
.install_code_policy = INSTALLCODE_POLICY_ENABLE, \
.nwk_cfg.zed_cfg = { \
.ed_timeout = ED_AGING_TIMEOUT, \
.keep_alive = ED_KEEP_ALIVE, \
}, \
#define ESP_ZIGBEE_STORAGE_PARTITION_NAME "nvs"
#define ESP_MANUFACTURER_NAME "\x09""ESPRESSIF"
#define ESP_MODEL_IDENTIFIER "\x07"CONFIG_IDF_TARGET
#define ESP_ZIGBEE_ZC_CONFIG() \
{ \
.device_type = EZB_NWK_DEVICE_TYPE_COORDINATOR, \
.install_code_policy = false, \
.zczr_config = { \
.max_children = 10, \
}, \
}
#define ESP_ZB_DEFAULT_RADIO_CONFIG() \
{ \
.radio_mode = ZB_RADIO_MODE_NATIVE, \
#if CONFIG_SOC_IEEE802154_SUPPORTED
#define ESP_ZIGBEE_PLATFORM_CONFIG() \
{ \
.storage_partition_name = ESP_ZIGBEE_STORAGE_PARTITION_NAME, \
.radio_config = { \
.radio_mode = ESP_ZIGBEE_RADIO_MODE_NATIVE, \
}, \
}
#else
#warning "The example is not for IEEE 802.15.4-disabled SoC usage, please refer to esp_zigbee_gateway for RCP configuration"
#endif
#define ESP_ZB_DEFAULT_HOST_CONFIG() \
{ \
.host_connection_mode = ZB_HOST_CONNECTION_MODE_NONE, \
}
#define ESP_ZIGBEE_DEFAULT_CONFIG() \
{ \
.device_config = ESP_ZIGBEE_ZC_CONFIG(), \
.platform_config = ESP_ZIGBEE_PLATFORM_CONFIG(), \
};
@@ -1,10 +1,11 @@
## IDF Component Manager Manifest File
dependencies:
espressif/esp-zboss-lib: "~1.6.0"
espressif/esp-zigbee-lib: "~1.6.0"
espressif/led_strip: "~3.0.0"
## Required IDF version
idf:
version: ">=5.0.0"
examples_utils:
path: ${IDF_PATH}/examples/zigbee/zb_common_components/examples_utils
version: ">=5.2"
espressif/esp-zigbee-lib:
version: ">=2.0.0"
example_common:
path: ${IDF_PATH}/examples/zigbee/zb_common_components/example_common
light_driver:
path: ${IDF_PATH}/examples/zigbee/zb_common_components/light_driver
@@ -1,62 +0,0 @@
/*
* SPDX-FileCopyrightText: 2021-2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: LicenseRef-Included
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Espressif Systems
* integrated circuit in a product or a software update for such product,
* must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* 4. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "esp_log.h"
#include "led_strip.h"
#include "light_driver.h"
static led_strip_handle_t s_led_strip;
static uint8_t s_red = 255, s_green = 255, s_blue = 255;
void light_driver_set_power(bool power)
{
ESP_ERROR_CHECK(led_strip_set_pixel(s_led_strip, 0, s_red * power, s_green * power, s_blue * power));
ESP_ERROR_CHECK(led_strip_refresh(s_led_strip));
}
void light_driver_init(bool power)
{
led_strip_config_t led_strip_conf = {
.max_leds = CONFIG_EXAMPLE_STRIP_LED_NUMBER,
.strip_gpio_num = CONFIG_EXAMPLE_STRIP_LED_GPIO,
};
led_strip_rmt_config_t rmt_conf = {
.resolution_hz = 10 * 1000 * 1000, // 10MHz
};
ESP_ERROR_CHECK(led_strip_new_rmt_device(&led_strip_conf, &rmt_conf, &s_led_strip));
light_driver_set_power(power);
}
@@ -1,70 +0,0 @@
/*
* SPDX-FileCopyrightText: 2021-2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: LicenseRef-Included
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Espressif Systems
* integrated circuit in a product or a software update for such product,
* must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* 4. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
/* light intensity level */
#define LIGHT_DEFAULT_ON 1
#define LIGHT_DEFAULT_OFF 0
/* LED strip configuration */
#define CONFIG_EXAMPLE_STRIP_LED_GPIO 8
#define CONFIG_EXAMPLE_STRIP_LED_NUMBER 1
/**
* @brief Set light power (on/off).
*
* @param power The light power to be set
*/
void light_driver_set_power(bool power);
/**
* @brief color light driver init, be invoked where you want to use color light
*
* @param power power on/off
*/
void light_driver_init(bool power);
#ifdef __cplusplus
} // extern "C"
#endif
@@ -1,7 +1,7 @@
# Name, Type, SubType, Offset, Size, Flags
# Note: if you have increased the bootloader size, make sure to update the offsets to avoid overlap
nvs, data, nvs, 0x9000, 0x6000,
phy_init, data, phy, 0xf000, 0x1000,
factory, app, factory, 0x10000, 900K,
zb_storage, data, fat, 0xf1000, 16K,
zb_fct, data, fat, 0xf5000, 1K,
nvs, data, nvs, , 0x6000,
otadata, data, ota, , 0x2000,
phy_init, data, phy, , 0x1000,
factory, app, factory, , 940K,
zb_fct, data, fat, , 1K,
1 # Name, Type, SubType, Offset, Size, Flags
2 # Note: if you have increased the bootloader size, make sure to update the offsets to avoid overlap
3 nvs, data, nvs, 0x9000, 0x6000, nvs, data, nvs, , 0x6000,
4 phy_init, data, phy, 0xf000, 0x1000, otadata, data, ota, , 0x2000,
5 factory, app, factory, 0x10000, 900K, phy_init, data, phy, , 0x1000,
6 zb_storage, data, fat, 0xf1000, 16K, factory, app, factory, , 940K,
7 zb_fct, data, fat, 0xf5000, 1K, zb_fct, data, fat, , 1K,
@@ -3,15 +3,10 @@
#
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x8000
CONFIG_PARTITION_TABLE_MD5=y
# end of Partition Table
#
# Zboss
# Zigbee
#
CONFIG_ZB_ENABLED=y
CONFIG_ZB_ZED=y
# end of Zboss
# end of Component config
# end of Zigbee
@@ -2,6 +2,9 @@
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.22)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
list(PREPEND SDKCONFIG_DEFAULTS
"${IDF_PATH}/examples/zigbee/zb_common_components/example_common/sdkconfig.mbedtls_minimal"
"sdkconfig.defaults")
# "Trim" the build. Include the minimal set of components, main, and anything it depends on.
idf_build_set_property(MINIMAL_BUILD ON)
project(light_switch)
@@ -1,9 +1,9 @@
| Supported Targets | ESP32-C5 | ESP32-C6 | ESP32-H2 |
| ----------------- | -------- | -------- | -------- |
| Supported Targets | ESP32-C5 | ESP32-C6 | ESP32-H2 | ESP32-H21 | ESP32-H4 | ESP32-S31 |
| ----------------- | -------- | -------- | -------- | --------- | -------- | --------- |
# Light Switch Example
This test code shows how to configure Zigbee Coordinator and use it as an HA on/off_switch.
This example demonstrates how to configure a Home Automation On/Off switch on a Zigbee End Device.
The ESP Zigbee SDK provides more examples and tools for productization:
* [ESP Zigbee SDK Docs](https://docs.espressif.com/projects/esp-zigbee-sdk)
@@ -11,64 +11,53 @@ The ESP Zigbee SDK provides more examples and tools for productization:
## Hardware Required
* One development board with ESP32-H2 SoC acting as Zigbee Coordinator (loaded with HA_on_off_switch)
* A USB cable for power supply and programming
* Choose another ESP32-H2 as Zigbee end-device (see [HA_on_off_light](../HA_on_off_light/))
* One 802.15.4-enabled development board running this example.
* A second board running as a Zigbee Coordinator (see the [HA_on_off_light](../HA_on_off_light/) example).
* A USB cable for power supply and programming.
## Configure the project
Before project configuration and build, make sure to set the correct chip target using `idf.py --preview set-target TARGET` command.
Before project configuration and build, set the correct chip target using `idf.py set-target TARGET`.
## Erase the NVRAM
Before flash it to the board, it is recommended to erase NVRAM if user doesn't want to keep the previous examples or other projects stored info using `idf.py -p PORT erase-flash`
Before flashing the board, erase the NVRAM with `idf.py -p PORT erase-flash` if you do not want to retain
information stored by previous examples or projects.
## Build and Flash
Build the project, flash it to the board, and start the monitor tool to view the serial output by running `idf.py -p PORT flash monitor`.
Build the project, flash it to the board, and start the monitor tool to view the serial output by running
`idf.py -p PORT flash monitor`.
(To exit the serial monitor, type ``Ctrl-]``.)
## Example Output
## Application Functions
As you run the example, you will see the following log:
When the program starts, the board attempts to join an available Zigbee network:
```
I (441) main_task: Started on CPU0
I (441) main_task: Calling app_main()
I (461) phy: phy_version: 230,2, 9aae6ea, Jan 15 2024, 11:17:12
I (461) phy: libbtbb version: 944f18e, Jan 15 2024, 11:17:25
I (471) main_task: Returned from app_main()
I (601) ESP_ZB_ON_OFF_SWITCH: ZDO signal: ZDO Config Ready (0x17), status: ESP_FAIL
I (601) ESP_ZB_ON_OFF_SWITCH: Initialize Zigbee stack
I (611) gpio: GPIO[9]| InputEn: 1| OutputEn: 0| OpenDrain: 0| Pullup: 1| Pulldown: 0| Intr:2
I (611) ESP_ZB_ON_OFF_SWITCH: Deferred driver initialization successful
I (621) ESP_ZB_ON_OFF_SWITCH: Device started up in factory-reset mode
I (621) ESP_ZB_ON_OFF_SWITCH: Start network formation
W (781) ESP_ZB_ON_OFF_SWITCH: Network(0x13af) closed, devices joining not allowed.
I (781) ESP_ZB_ON_OFF_SWITCH: Formed network successfully (Extended PAN ID: 74:4d:bd:ff:fe:63:f7:30, PAN ID: 0x13af, Channel:13, Short Address: 0x0000)
I (1391) ESP_ZB_ON_OFF_SWITCH: Network(0x13af) is open for 180 seconds
I (1391) ESP_ZB_ON_OFF_SWITCH: Network steering started
I (9561) ESP_ZB_ON_OFF_SWITCH: ZDO signal: NWK Device Associated (0x12), status: ESP_OK
I (9561) ESP_ZB_ON_OFF_SWITCH: ZDO signal: ZDO Device Update (0x30), status: ESP_OK
I (9601) ESP_ZB_ON_OFF_SWITCH: New device commissioned or rejoined (short: 0x7c16)
I (9671) ESP_ZB_ON_OFF_SWITCH: Found light
I (9671) ESP_ZB_ON_OFF_SWITCH: Try to bind On/Off
I (9681) ESP_ZB_ON_OFF_SWITCH: Bound successfully!
I (9681) ESP_ZB_ON_OFF_SWITCH: The light originating from address(0x7c16) on endpoint(10)
I (9751) ESP_ZB_ON_OFF_SWITCH: ZDO signal: ZDO Device Authorized (0x2f), status: ESP_OK
I (9781) ESP_ZB_ON_OFF_SWITCH: Network(0x13af) is open for 180 seconds
I (16451) ESP_ZB_ON_OFF_SWITCH: Send 'on_off toggle' command
I (17011) ESP_ZB_ON_OFF_SWITCH: Send 'on_off toggle' command
I (17441) ESP_ZB_ON_OFF_SWITCH: Send 'on_off toggle' command
I (17831) ESP_ZB_ON_OFF_SWITCH: Send 'on_off toggle' command
I (427) ON_OFF_SWITCH: Start ESP Zigbee Stack
I (467) ON_OFF_SWITCH: Initialize Zigbee stack
I (467) ON_OFF_SWITCH: Deferred driver initialization successful
I (467) ON_OFF_SWITCH: Device started up in factory-reset mode
I (1727) ON_OFF_SWITCH: Joined network successfully: PAN ID(0x3051, EXT: 0x4831b7fffec183f0), Channel(13), Short Address(0xe5e0)
```
## Light Control Functions
After joining, the switch finds and binds a Home Automation light:
* By toggling the switch button (BOOT) on this board, the LED on the board loaded with the `HA_on_off_light` example will turn on and off.
```
I (1727) ON_OFF_SWITCH: Attempt to find HA light device
I (1827) ON_OFF_SWITCH: Attempt to bind HA light device (short address: 0x0000)
I (1847) ON_OFF_SWITCH: Bound HA light device successfully
```
Pressing the `BOOT` button sends an On/Off Toggle command to the bound device:
```
I (24447) ON_OFF_SWITCH: Sent ZCL On/Off Toggle request
I (24517) ON_OFF_SWITCH: Received ZCL Default Response with status(0x00)
```
## Troubleshooting
For any technical queries, please open an [issue](https://github.com/espressif/esp-idf/issues) on GitHub. We will get back to you soon.
For any technical queries, please open an [issue](https://github.com/espressif/esp-idf/issues) on GitHub.
@@ -1,5 +1,3 @@
idf_component_register(
SRC_DIRS "."
INCLUDE_DIRS "."
PRIV_REQUIRES nvs_flash esp_driver_gpio esp_driver_uart ieee802154
)
idf_component_register(SRC_DIRS "."
PRIV_INCLUDE_DIRS "."
PRIV_REQUIRES nvs_flash esp_driver_gpio esp_driver_uart ieee802154)
@@ -1,7 +1,7 @@
/*
* SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD
* SPDX-FileCopyrightText: 2021-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: LicenseRef-Included
* SPDX-License-Identifier: LicenseRef-Included
*
* Zigbee HA_on_off_switch Example
*
@@ -12,189 +12,272 @@
* CONDITIONS OF ANY KIND, either express or implied.
*/
#include "string.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_err.h"
#include "esp_check.h"
#include "esp_err.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "ha/esp_zigbee_ha_standard.h"
#include "zcl_utility.h"
#include "switch_driver.h"
#include "alarm_timer.h"
#include "esp_zigbee.h"
#include "ezbee/zha.h"
#include "esp_zb_switch.h"
#if defined ZB_ED_ROLE
#error Define ZB_COORDINATOR_ROLE in idf.py menuconfig to compile light switch source code.
#endif
typedef struct light_bulb_device_params_s {
esp_zb_ieee_addr_t ieee_addr;
uint8_t endpoint;
uint16_t short_addr;
} light_bulb_device_params_t;
static const char *TAG = "ON_OFF_SWITCH";
static switch_func_pair_t button_func_pair[] = {
{GPIO_INPUT_IO_TOGGLE_SWITCH, SWITCH_ONOFF_TOGGLE_CONTROL}
};
static const char *TAG = "ESP_ZB_ON_OFF_SWITCH";
static void zb_buttons_handler(switch_func_pair_t *button_func_pair)
static void button_event_handler(switch_driver_handle_t handle)
{
if (button_func_pair->func == SWITCH_ONOFF_TOGGLE_CONTROL) {
/* implemented light switch toggle functionality */
esp_zb_zcl_on_off_cmd_t cmd_req;
cmd_req.zcl_basic_cmd.src_endpoint = HA_ONOFF_SWITCH_ENDPOINT;
cmd_req.address_mode = ESP_ZB_APS_ADDR_MODE_DST_ADDR_ENDP_NOT_PRESENT;
cmd_req.on_off_cmd_id = ESP_ZB_ZCL_CMD_ON_OFF_TOGGLE_ID;
esp_zb_lock_acquire(portMAX_DELAY);
esp_zb_zcl_on_off_cmd_req(&cmd_req);
esp_zb_lock_release();
ESP_EARLY_LOGI(TAG, "Send 'on_off toggle' command");
}
ESP_RETURN_ON_FALSE(handle != SWITCH_INV_HANDLE, , TAG, "Invalid switch handle");
ezb_zcl_on_off_cmd_t cmd_req = {
.cmd_ctrl =
{
.dst_addr.addr_mode = EZB_ADDR_MODE_NONE,
.src_ep = ESP_ZIGBEE_HA_ON_OFF_SWITCH_EP_ID,
},
};
esp_zigbee_lock_acquire(portMAX_DELAY);
ezb_zcl_on_off_toggle_cmd_req(&cmd_req);
esp_zigbee_lock_release();
ESP_EARLY_LOGI(TAG, "Sent ZCL On/Off Toggle request");
}
static esp_err_t deferred_driver_init(void)
{
ESP_RETURN_ON_FALSE(switch_driver_init(button_func_pair, PAIR_SIZE(button_func_pair), zb_buttons_handler), ESP_FAIL, TAG,
"Failed to initialize switch driver");
static bool is_inited = false;
ESP_RETURN_ON_FALSE(!is_inited, ESP_OK, TAG, "Deferred driver already initialized");
switch_driver_config_t config = {
.gpio_num = CONFIG_GPIO_BOOT_ON_DEVKIT,
.event_cb = button_event_handler,
};
switch_driver_handle_t handle = switch_driver_init(&config);
is_inited = handle == SWITCH_INV_HANDLE ? false : true;
return is_inited ? ESP_OK : ESP_FAIL;
}
static void zdo_bind_ha_light_device_result(const ezb_zdp_bind_req_result_t *result, void *user_ctx)
{
assert(result);
if (result->error == EZB_ERR_NONE) {
if (result->rsp && result->rsp->status == EZB_ZDP_STATUS_SUCCESS) {
ESP_LOGI(TAG, "Bound HA light device successfully");
} else {
ESP_LOGE(TAG, "Failed to bind HA light device with status (0x%02x)", result->rsp->status);
}
} else {
ESP_LOGE(TAG, "Failed to bind HA light device with error (0x%04x)", result->error);
}
}
static ezb_err_t zdo_bind_ha_light_device(uint16_t dst_short_addr, uint8_t dst_ep)
{
ezb_err_t ret = EZB_ERR_FAIL;
ezb_zdo_bind_req_t bind_req = {
.dst_nwk_addr = ezb_nwk_get_short_address(),
.field =
{
.src_ep = ESP_ZIGBEE_HA_ON_OFF_SWITCH_EP_ID,
.cluster_id = EZB_ZCL_CLUSTER_ID_ON_OFF,
.dst_addr_mode = EZB_ADDR_MODE_EXT,
.dst_ep = dst_ep,
},
.cb = zdo_bind_ha_light_device_result,
.user_ctx = NULL,
};
ezb_nwk_get_extended_address(&bind_req.field.src_addr);
ESP_RETURN_ON_ERROR(ezb_address_extended_by_short(dst_short_addr, &bind_req.field.dst_addr.extended_addr), TAG,
"Failed to get extended address for destination device(0x%04hx)", dst_short_addr);
ret = ezb_zdo_bind_req(&bind_req);
if (ret == EZB_ERR_NONE) {
ESP_LOGI(TAG, "Attempt to bind HA light device (short address: 0x%04hx)", dst_short_addr);
} else {
ESP_LOGE(TAG, "Failed to bind HA light device (short address: 0x%04hx) with error(0x%04x)", dst_short_addr, ret);
}
return ret;
}
static void zdo_find_ha_light_device_result(const ezb_zdo_match_desc_req_result_t *result, void *user_ctx)
{
assert(result);
if (result->error == EZB_ERR_NONE) {
if (result->rsp && result->rsp->status == EZB_ZDP_STATUS_SUCCESS && result->rsp->match_length > 0 &&
result->rsp->match_list) {
for (size_t i = 0; i < result->rsp->match_length; i++) {
zdo_bind_ha_light_device(result->rsp->nwk_addr_of_interest, result->rsp->match_list[i]);
}
}
} else {
ESP_LOGE(TAG, "Failed to find HA light device in the network with error(0x%04x)", result->error);
}
}
static ezb_err_t zdo_find_ha_light_device(void)
{
ezb_err_t ret = EZB_ERR_FAIL;
uint16_t cluster_list[1] = {EZB_ZCL_CLUSTER_ID_ON_OFF};
ezb_zdo_match_desc_req_t req = {
.dst_nwk_addr = 0xFFFD,
.field =
{
.nwk_addr_of_interest = 0xFFFD,
.profile_id = EZB_AF_HA_PROFILE_ID,
.num_in_clusters = 1,
.num_out_clusters = 0,
.cluster_list = cluster_list,
},
.cb = zdo_find_ha_light_device_result,
.user_ctx = NULL,
};
ret = ezb_zdo_match_desc_req(&req);
if (ret == EZB_ERR_NONE) {
ESP_LOGI(TAG, "Attempt to find HA light device");
} else {
ESP_LOGE(TAG, "Failed to find HA light device with error(0x%04x)", ret);
}
return ret;
}
static void esp_zigbee_alarm_bdb_commissioning(alarm_timer_arg_t arg)
{
esp_zigbee_lock_acquire(portMAX_DELAY);
(void)ezb_bdb_start_top_level_commissioning(arg);
esp_zigbee_lock_release();
}
static bool esp_zigbee_app_signal_handler(const ezb_app_signal_t *app_signal)
{
ezb_app_signal_type_t signal_type = ezb_app_signal_get_type(app_signal);
switch (signal_type) {
case EZB_ZDO_SIGNAL_SKIP_STARTUP:
ESP_LOGI(TAG, "Initialize Zigbee stack");
ezb_bdb_start_top_level_commissioning(EZB_BDB_MODE_INITIALIZATION);
break;
case EZB_BDB_SIGNAL_DEVICE_FIRST_START:
case EZB_BDB_SIGNAL_DEVICE_REBOOT: {
ezb_bdb_comm_status_t status = *((ezb_bdb_comm_status_t *)ezb_app_signal_get_params(app_signal));
if (status == EZB_BDB_STATUS_SUCCESS) {
ESP_LOGI(TAG, "Deferred driver initialization %s", deferred_driver_init() ? "failed" : "successful");
ESP_LOGI(TAG, "Device started up in%s factory-reset mode", ezb_bdb_is_factory_new() ? "" : " non");
if (ezb_bdb_is_factory_new()) {
ezb_bdb_start_top_level_commissioning(EZB_BDB_MODE_NETWORK_STEERING);
} else {
ESP_LOGI(TAG, "Device reboot");
}
} else {
ESP_LOGW(TAG, "The %s failed with status(0x%02x), please retry", ezb_app_signal_to_string(signal_type), status);
alarm_timer_schedule(esp_zigbee_alarm_bdb_commissioning, EZB_BDB_MODE_INITIALIZATION, 1000);
}
} break;
case EZB_BDB_SIGNAL_STEERING: {
ezb_bdb_comm_status_t status = *((ezb_bdb_comm_status_t *)ezb_app_signal_get_params(app_signal));
if (status == EZB_BDB_STATUS_SUCCESS) {
ezb_extpanid_t extended_pan_id;
ezb_nwk_get_extended_panid(&extended_pan_id);
ESP_LOGI(TAG, "Joined network successfully: PAN ID(0x%04hx, EXT: 0x%llx), Channel(%d), Short Address(0x%04hx)",
ezb_nwk_get_panid(), extended_pan_id.u64, ezb_nwk_get_current_channel(), ezb_nwk_get_short_address());
zdo_find_ha_light_device();
} else {
ESP_LOGW(TAG, "Failed to join network with status(0x%02x)", status);
alarm_timer_schedule(esp_zigbee_alarm_bdb_commissioning, EZB_BDB_MODE_NETWORK_STEERING, 1000);
}
} break;
case EZB_ZDO_SIGNAL_LEAVE: {
const ezb_zdo_signal_leave_params_t *leave_params = ezb_app_signal_get_params(app_signal);
ESP_LOGI(TAG, "Left network successfully with type(0x%02x)", leave_params->leave_type);
} break;
case EZB_NWK_SIGNAL_PERMIT_JOIN_STATUS: {
uint8_t duration = *(uint8_t *)ezb_app_signal_get_params(app_signal);
if (duration) {
ESP_LOGI(TAG, "Network(0x%04hx) is open for %d seconds", ezb_nwk_get_panid(), duration);
} else {
ESP_LOGW(TAG, "Network(0x%04hx) closed, devices joining not allowed.", ezb_nwk_get_panid());
}
} break;
case EZB_ZDO_SIGNAL_LEAVE_INDICATION: {
const ezb_zdo_signal_leave_indication_params_t *leave_ind_params = ezb_app_signal_get_params(app_signal);
ESP_LOGI(TAG, "Zigbee Node(0x%04hx) is leaving network", leave_ind_params->short_addr);
} break;
default:
ESP_LOGI(TAG, "Zigbee APP Signal: %s(type: 0x%02x)", ezb_app_signal_to_string(signal_type), signal_type);
break;
}
return true;
}
static void esp_zigbee_zcl_core_action_handler(ezb_zcl_core_action_callback_id_t callback_id, void *message)
{
switch (callback_id) {
case EZB_ZCL_CORE_DEFAULT_RSP_CB_ID: {
ezb_zcl_cmd_default_rsp_message_t *default_rsp = (ezb_zcl_cmd_default_rsp_message_t *)message;
ESP_LOGI(TAG, "Received ZCL Default Response with status(0x%02x)", default_rsp->in.status_code);
} break;
default:
ESP_LOGW(TAG, "ZCL Core Action: ID(0x%04lx)", callback_id);
break;
}
}
esp_err_t esp_zigbee_create_zha_on_off_switch_device(void)
{
ezb_af_device_desc_t dev_desc = ezb_af_create_device_desc();
ezb_zha_on_off_switch_config_t switch_cfg = EZB_ZHA_ON_OFF_SWITCH_CONFIG();
ezb_af_ep_desc_t ep_desc = ezb_zha_create_on_off_switch(ESP_ZIGBEE_HA_ON_OFF_SWITCH_EP_ID, &switch_cfg);
ezb_zcl_cluster_desc_t basic_desc = {0};
basic_desc = ezb_af_endpoint_get_cluster_desc(ep_desc, EZB_ZCL_CLUSTER_ID_BASIC, EZB_ZCL_CLUSTER_SERVER);
ezb_zcl_basic_cluster_desc_add_attr(basic_desc, EZB_ZCL_ATTR_BASIC_MANUFACTURER_NAME_ID, (void *)ESP_MANUFACTURER_NAME);
ezb_zcl_basic_cluster_desc_add_attr(basic_desc, EZB_ZCL_ATTR_BASIC_MODEL_IDENTIFIER_ID, (void *)ESP_MODEL_IDENTIFIER);
ESP_ERROR_CHECK(ezb_af_device_add_endpoint_desc(dev_desc, ep_desc));
ESP_ERROR_CHECK(ezb_af_device_desc_register(dev_desc));
ezb_zcl_core_action_handler_register(esp_zigbee_zcl_core_action_handler);
return ESP_OK;
}
static void bdb_start_top_level_commissioning_cb(uint8_t mode_mask)
esp_err_t esp_zigbee_setup_commissioning(void)
{
ESP_RETURN_ON_FALSE(esp_zb_bdb_start_top_level_commissioning(mode_mask) == ESP_OK, , TAG, "Failed to start Zigbee bdb commissioning");
ezb_aps_secur_enable_distributed_security(false);
ESP_ERROR_CHECK(ezb_bdb_set_primary_channel_set(ESP_ZIGBEE_PRIMARY_CHANNEL_MASK));
ESP_ERROR_CHECK(ezb_bdb_set_secondary_channel_set(ESP_ZIGBEE_SECONDARY_CHANNEL_MASK));
ESP_ERROR_CHECK(ezb_app_signal_add_handler(esp_zigbee_app_signal_handler));
return ESP_OK;
}
static void bind_cb(esp_zb_zdp_status_t zdo_status, void *user_ctx)
static void esp_zigbee_stack_main_task(void *pvParameters)
{
if (zdo_status == ESP_ZB_ZDP_STATUS_SUCCESS) {
ESP_LOGI(TAG, "Bound successfully!");
if (user_ctx) {
light_bulb_device_params_t *light = (light_bulb_device_params_t *)user_ctx;
ESP_LOGI(TAG, "The light originating from address(0x%x) on endpoint(%d)", light->short_addr, light->endpoint);
free(light);
}
}
}
esp_zigbee_config_t config = ESP_ZIGBEE_DEFAULT_CONFIG();
static void user_find_cb(esp_zb_zdp_status_t zdo_status, uint16_t addr, uint8_t endpoint, void *user_ctx)
{
if (zdo_status == ESP_ZB_ZDP_STATUS_SUCCESS) {
ESP_LOGI(TAG, "Found light");
esp_zb_zdo_bind_req_param_t bind_req;
light_bulb_device_params_t *light = (light_bulb_device_params_t *)malloc(sizeof(light_bulb_device_params_t));
light->endpoint = endpoint;
light->short_addr = addr;
esp_zb_ieee_address_by_short(light->short_addr, light->ieee_addr);
esp_zb_get_long_address(bind_req.src_address);
bind_req.src_endp = HA_ONOFF_SWITCH_ENDPOINT;
bind_req.cluster_id = ESP_ZB_ZCL_CLUSTER_ID_ON_OFF;
bind_req.dst_addr_mode = ESP_ZB_ZDO_BIND_DST_ADDR_MODE_64_BIT_EXTENDED;
memcpy(bind_req.dst_address_u.addr_long, light->ieee_addr, sizeof(esp_zb_ieee_addr_t));
bind_req.dst_endp = endpoint;
bind_req.req_dst_addr = esp_zb_get_short_address();
ESP_LOGI(TAG, "Try to bind On/Off");
esp_zb_zdo_device_bind_req(&bind_req, bind_cb, (void *)light);
}
}
ESP_ERROR_CHECK(esp_zigbee_init(&config));
void esp_zb_app_signal_handler(esp_zb_app_signal_t *signal_struct)
{
uint32_t *p_sg_p = signal_struct->p_app_signal;
esp_err_t err_status = signal_struct->esp_err_status;
esp_zb_app_signal_type_t sig_type = *p_sg_p;
esp_zb_zdo_signal_device_annce_params_t *dev_annce_params = NULL;
switch (sig_type) {
case ESP_ZB_ZDO_SIGNAL_SKIP_STARTUP:
ESP_LOGI(TAG, "Initialize Zigbee stack");
esp_zb_bdb_start_top_level_commissioning(ESP_ZB_BDB_MODE_INITIALIZATION);
break;
case ESP_ZB_BDB_SIGNAL_DEVICE_FIRST_START:
case ESP_ZB_BDB_SIGNAL_DEVICE_REBOOT:
if (err_status == ESP_OK) {
ESP_LOGI(TAG, "Deferred driver initialization %s", deferred_driver_init() ? "failed" : "successful");
ESP_LOGI(TAG, "Device started up in %s factory-reset mode", esp_zb_bdb_is_factory_new() ? "" : "non");
if (esp_zb_bdb_is_factory_new()) {
ESP_LOGI(TAG, "Start network formation");
esp_zb_bdb_start_top_level_commissioning(ESP_ZB_BDB_MODE_NETWORK_FORMATION);
} else {
esp_zb_bdb_open_network(180);
ESP_LOGI(TAG, "Device rebooted");
}
} else {
ESP_LOGE(TAG, "Failed to initialize Zigbee stack (status: %s)", esp_err_to_name(err_status));
}
break;
case ESP_ZB_BDB_SIGNAL_FORMATION:
if (err_status == ESP_OK) {
esp_zb_ieee_addr_t extended_pan_id;
esp_zb_get_extended_pan_id(extended_pan_id);
ESP_LOGI(TAG, "Formed network successfully (Extended PAN ID: %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x, PAN ID: 0x%04hx, Channel:%d, Short Address: 0x%04hx)",
extended_pan_id[7], extended_pan_id[6], extended_pan_id[5], extended_pan_id[4],
extended_pan_id[3], extended_pan_id[2], extended_pan_id[1], extended_pan_id[0],
esp_zb_get_pan_id(), esp_zb_get_current_channel(), esp_zb_get_short_address());
esp_zb_bdb_start_top_level_commissioning(ESP_ZB_BDB_MODE_NETWORK_STEERING);
} else {
ESP_LOGI(TAG, "Restart network formation (status: %s)", esp_err_to_name(err_status));
esp_zb_scheduler_alarm((esp_zb_callback_t)bdb_start_top_level_commissioning_cb, ESP_ZB_BDB_MODE_NETWORK_FORMATION, 1000);
}
break;
case ESP_ZB_BDB_SIGNAL_STEERING:
if (err_status == ESP_OK) {
ESP_LOGI(TAG, "Network steering started");
}
break;
case ESP_ZB_ZDO_SIGNAL_DEVICE_ANNCE:
dev_annce_params = (esp_zb_zdo_signal_device_annce_params_t *)esp_zb_app_signal_get_params(p_sg_p);
ESP_LOGI(TAG, "New device commissioned or rejoined (short: 0x%04hx)", dev_annce_params->device_short_addr);
esp_zb_zdo_match_desc_req_param_t cmd_req;
cmd_req.dst_nwk_addr = dev_annce_params->device_short_addr;
cmd_req.addr_of_interest = dev_annce_params->device_short_addr;
esp_zb_zdo_find_on_off_light(&cmd_req, user_find_cb, NULL);
break;
case ESP_ZB_NWK_SIGNAL_PERMIT_JOIN_STATUS:
if (err_status == ESP_OK) {
if (*(uint8_t *)esp_zb_app_signal_get_params(p_sg_p)) {
ESP_LOGI(TAG, "Network(0x%04hx) is open for %d seconds", esp_zb_get_pan_id(), *(uint8_t *)esp_zb_app_signal_get_params(p_sg_p));
} else {
ESP_LOGW(TAG, "Network(0x%04hx) closed, devices joining not allowed.", esp_zb_get_pan_id());
}
}
break;
default:
ESP_LOGI(TAG, "ZDO signal: %s (0x%x), status: %s", esp_zb_zdo_signal_to_string(sig_type), sig_type,
esp_err_to_name(err_status));
break;
}
}
ESP_ERROR_CHECK(esp_zigbee_setup_commissioning());
static void esp_zb_task(void *pvParameters)
{
/* initialize Zigbee stack */
esp_zb_cfg_t zb_nwk_cfg = ESP_ZB_ZC_CONFIG();
esp_zb_init(&zb_nwk_cfg);
esp_zb_on_off_switch_cfg_t switch_cfg = ESP_ZB_DEFAULT_ON_OFF_SWITCH_CONFIG();
esp_zb_ep_list_t *esp_zb_on_off_switch_ep = esp_zb_on_off_switch_ep_create(HA_ONOFF_SWITCH_ENDPOINT, &switch_cfg);
zcl_basic_manufacturer_info_t info = {
.manufacturer_name = ESP_MANUFACTURER_NAME,
.model_identifier = ESP_MODEL_IDENTIFIER,
};
ESP_ERROR_CHECK(esp_zigbee_create_zha_on_off_switch_device());
esp_zcl_utility_add_ep_basic_manufacturer_info(esp_zb_on_off_switch_ep, HA_ONOFF_SWITCH_ENDPOINT, &info);
esp_zb_device_register(esp_zb_on_off_switch_ep);
esp_zb_set_primary_network_channel_set(ESP_ZB_PRIMARY_CHANNEL_MASK);
ESP_ERROR_CHECK(esp_zb_start(false));
esp_zb_stack_main_loop();
ESP_ERROR_CHECK(esp_zigbee_start(false));
esp_zigbee_launch_mainloop();
esp_zigbee_deinit();
vTaskDelete(NULL);
}
void app_main(void)
{
esp_zb_platform_config_t config = {
.radio_config = ESP_ZB_DEFAULT_RADIO_CONFIG(),
.host_config = ESP_ZB_DEFAULT_HOST_CONFIG(),
};
ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_zb_platform_config(&config));
xTaskCreate(esp_zb_task, "Zigbee_main", 4096, NULL, 5, NULL);
ESP_LOGI(TAG, "Start ESP Zigbee Stack");
xTaskCreate(esp_zigbee_stack_main_task, "Zigbee_main", 4096, NULL, 5, NULL);
}
@@ -1,7 +1,7 @@
/*
* SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD
* SPDX-FileCopyrightText: 2021-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: LicenseRef-Included
* SPDX-License-Identifier: LicenseRef-Included
*
* Zigbee HA_on_off_switch Example
*
@@ -11,34 +11,43 @@
* software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied.
*/
#include "esp_zigbee_core.h"
#include "switch_driver.h"
/* Zigbee configuration */
#define MAX_CHILDREN 10 /* the max amount of connected devices */
#define INSTALLCODE_POLICY_ENABLE false /* enable the install code policy for security */
#define HA_ONOFF_SWITCH_ENDPOINT 1 /* esp light switch device endpoint */
#define ESP_ZB_PRIMARY_CHANNEL_MASK (1l << 13) /* Zigbee primary channel mask use in the example */
#pragma once
/* Basic manufacturer information */
#define ESP_MANUFACTURER_NAME "\x09""ESPRESSIF" /* Customized manufacturer name */
#define ESP_MODEL_IDENTIFIER "\x07"CONFIG_IDF_TARGET /* Customized model identifier */
#define ESP_ZIGBEE_PRIMARY_CHANNEL_MASK (1U << CONFIG_ZB_EXAMPLE_PRIMARY_CHANNEL)
#define ESP_ZIGBEE_SECONDARY_CHANNEL_MASK CONFIG_ZB_EXAMPLE_SECONDARY_CHANNEL_MASK
#define ESP_ZB_ZC_CONFIG() \
{ \
.esp_zb_role = ESP_ZB_DEVICE_TYPE_COORDINATOR, \
.install_code_policy = INSTALLCODE_POLICY_ENABLE, \
.nwk_cfg.zczr_cfg = { \
.max_children = MAX_CHILDREN, \
}, \
#define ESP_ZIGBEE_HA_ON_OFF_SWITCH_EP_ID (1)
#define ESP_ZIGBEE_STORAGE_PARTITION_NAME "nvs"
#define ESP_MANUFACTURER_NAME "\x09""ESPRESSIF"
#define ESP_MODEL_IDENTIFIER "\x07" CONFIG_IDF_TARGET
#define ESP_ZIGBEE_ZED_CONFIG() \
{ \
.device_type = EZB_NWK_DEVICE_TYPE_END_DEVICE, \
.install_code_policy = false, \
.zed_config = { \
.ed_timeout = EZB_NWK_ED_TIMEOUT_64MIN, \
.keep_alive = 4000, \
}, \
}
#define ESP_ZB_DEFAULT_RADIO_CONFIG() \
{ \
.radio_mode = ZB_RADIO_MODE_NATIVE, \
#if CONFIG_SOC_IEEE802154_SUPPORTED
#define ESP_ZIGBEE_PLATFORM_CONFIG() \
{ \
.storage_partition_name = ESP_ZIGBEE_STORAGE_PARTITION_NAME, \
.radio_config = { \
.radio_mode = ESP_ZIGBEE_RADIO_MODE_NATIVE, \
}, \
}
#else
#warning "The example is not for IEEE 802.15.4-disabled SoC usage, please refer to esp_zigbee_gateway for RCP configuration"
#endif
#define ESP_ZB_DEFAULT_HOST_CONFIG() \
{ \
.host_connection_mode = ZB_HOST_CONNECTION_MODE_NONE, \
}
#define ESP_ZIGBEE_DEFAULT_CONFIG() \
{ \
.device_config = ESP_ZIGBEE_ZED_CONFIG(), \
.platform_config = ESP_ZIGBEE_PLATFORM_CONFIG(), \
};
@@ -1,9 +1,11 @@
## IDF Component Manager Manifest File
dependencies:
espressif/esp-zboss-lib: "~1.6.0"
espressif/esp-zigbee-lib: "~1.6.0"
## Required IDF version
idf:
version: ">=5.0.0"
examples_utils:
path: ${IDF_PATH}/examples/zigbee/zb_common_components/examples_utils
version: ">=5.2"
espressif/esp-zigbee-lib:
version: ">=2.0.0"
example_common:
path: ${IDF_PATH}/examples/zigbee/zb_common_components/example_common
switch_driver:
path: ${IDF_PATH}/examples/zigbee/zb_common_components/switch_driver
@@ -1,178 +0,0 @@
/*
* SPDX-FileCopyrightText: 2021-2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: LicenseRef-Included
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Espressif Systems
* integrated circuit in a product or a software update for such product,
* must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* 4. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "switch_driver.h"
/**
* @brief:
* This example code shows how to configure light switch with attribute as well as button switch handler.
*
* @note:
Currently only support toggle switch functionality available
*
* @note:
* For other possible switch functions (on/off,level up/down,step up/down). User need to implement and create them by themselves
*/
static QueueHandle_t gpio_evt_queue = NULL;
/* button function pair, should be defined in switch example source file */
static switch_func_pair_t *switch_func_pair;
/* call back function pointer */
static esp_switch_callback_t func_ptr;
/* which button is pressed */
static uint8_t switch_num;
static const char *TAG = "ESP_ZB_SWITCH";
static void IRAM_ATTR gpio_isr_handler(void *arg)
{
xQueueSendFromISR(gpio_evt_queue, (switch_func_pair_t *)arg, NULL);
}
/**
* @brief Enable GPIO (switches refer to) isr
*
* @param enabled enable isr if true.
*/
static void switch_driver_gpios_intr_enabled(bool enabled)
{
for (int i = 0; i < switch_num; ++i) {
if (enabled) {
gpio_intr_enable((switch_func_pair + i)->pin);
} else {
gpio_intr_disable((switch_func_pair + i)->pin);
}
}
}
/**
* @brief Tasks for checking the button event and debounce the switch state
*
* @param arg Unused value.
*/
static void switch_driver_button_detected(void *arg)
{
gpio_num_t io_num = GPIO_NUM_NC;
switch_func_pair_t button_func_pair;
static switch_state_t switch_state = SWITCH_IDLE;
bool evt_flag = false;
for (;;) {
/* check if there is any queue received, if yes read out the button_func_pair */
if (xQueueReceive(gpio_evt_queue, &button_func_pair, portMAX_DELAY)) {
io_num = button_func_pair.pin;
switch_driver_gpios_intr_enabled(false);
evt_flag = true;
}
while (evt_flag) {
bool value = gpio_get_level(io_num);
switch (switch_state) {
case SWITCH_IDLE:
switch_state = (value == GPIO_INPUT_LEVEL_ON) ? SWITCH_PRESS_DETECTED : SWITCH_IDLE;
break;
case SWITCH_PRESS_DETECTED:
switch_state = (value == GPIO_INPUT_LEVEL_ON) ? SWITCH_PRESS_DETECTED : SWITCH_RELEASE_DETECTED;
break;
case SWITCH_RELEASE_DETECTED:
switch_state = SWITCH_IDLE;
/* callback to button_handler */
(*func_ptr)(&button_func_pair);
break;
default:
break;
}
if (switch_state == SWITCH_IDLE) {
switch_driver_gpios_intr_enabled(true);
evt_flag = false;
break;
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
}
/**
* @brief init GPIO configuration as well as isr
*
* @param button_func_pair pointer of the button pair.
* @param button_num number of button pair.
*/
static bool switch_driver_gpio_init(switch_func_pair_t *button_func_pair, uint8_t button_num)
{
gpio_config_t io_conf = {};
switch_func_pair = button_func_pair;
switch_num = button_num;
uint64_t pin_bit_mask = 0;
/* set up button func pair pin mask */
for (int i = 0; i < button_num; ++i) {
pin_bit_mask |= (1ULL << (button_func_pair + i)->pin);
}
/* interrupt of falling edge */
io_conf.intr_type = GPIO_INTR_NEGEDGE;
io_conf.pin_bit_mask = pin_bit_mask;
io_conf.mode = GPIO_MODE_INPUT;
io_conf.pull_up_en = GPIO_PULLUP_ENABLE;
/* configure GPIO with the given settings */
gpio_config(&io_conf);
/* create a queue to handle gpio event from isr */
gpio_evt_queue = xQueueCreate(10, sizeof(switch_func_pair_t));
if ( gpio_evt_queue == 0) {
ESP_LOGE(TAG, "Queue was not created and must not be used");
return false;
}
/* start gpio task */
xTaskCreate(switch_driver_button_detected, "button_detected", 4096, NULL, 10, NULL);
/* install gpio isr service */
gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT);
for (int i = 0; i < button_num; ++i) {
gpio_isr_handler_add((button_func_pair + i)->pin, gpio_isr_handler, (void *) (button_func_pair + i));
}
return true;
}
bool switch_driver_init(switch_func_pair_t *button_func_pair, uint8_t button_num, esp_switch_callback_t cb)
{
if (!switch_driver_gpio_init(button_func_pair, button_num)) {
return false;
}
func_ptr = cb;
return true;
}
@@ -1,94 +0,0 @@
/*
* SPDX-FileCopyrightText: 2021-2023 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: LicenseRef-Included
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Espressif Systems
* integrated circuit in a product or a software update for such product,
* must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* 4. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "driver/gpio.h"
#ifdef __cplusplus
extern "C" {
#endif
/* user should configure which I/O port as toggle switch input, default is GPIO9 */
#define GPIO_INPUT_IO_TOGGLE_SWITCH GPIO_NUM_9
/* config button level depends on the pull up/down setting
push button level is on level = 1 when pull-down enable
push button level is on level = 0 when pull-up enable
*/
#define GPIO_INPUT_LEVEL_ON 0
#define ESP_INTR_FLAG_DEFAULT 0
#define PAIR_SIZE(TYPE_STR_PAIR) (sizeof(TYPE_STR_PAIR) / sizeof(TYPE_STR_PAIR[0]))
typedef enum {
SWITCH_IDLE,
SWITCH_PRESS_ARMED,
SWITCH_PRESS_DETECTED,
SWITCH_PRESSED,
SWITCH_RELEASE_DETECTED,
} switch_state_t;
typedef enum {
SWITCH_ON_CONTROL,
SWITCH_OFF_CONTROL,
SWITCH_ONOFF_TOGGLE_CONTROL,
SWITCH_LEVEL_UP_CONTROL,
SWITCH_LEVEL_DOWN_CONTROL,
SWITCH_LEVEL_CYCLE_CONTROL,
SWITCH_COLOR_CONTROL,
} switch_func_t;
typedef struct {
uint32_t pin;
switch_func_t func;
} switch_func_pair_t;
typedef void (*esp_switch_callback_t)(switch_func_pair_t *param);
/**
* @brief init function for switch and callback setup
*
* @param button_func_pair pointer of the button pair.
* @param button_num number of button pair.
* @param cb callback pointer.
*/
bool switch_driver_init(switch_func_pair_t *button_func_pair, uint8_t button_num, esp_switch_callback_t cb);
#ifdef __cplusplus
} // extern "C"
#endif
@@ -1,7 +1,7 @@
# Name, Type, SubType, Offset, Size, Flags
# Note: if you have increased the bootloader size, make sure to update the offsets to avoid overlap
nvs, data, nvs, 0x9000, 0x6000,
phy_init, data, phy, 0xf000, 0x1000,
factory, app, factory, 0x10000, 900K,
zb_storage, data, fat, 0xf1000, 16K,
zb_fct, data, fat, 0xf5000, 1K,
nvs, data, nvs, , 0x6000,
otadata, data, ota, , 0x2000,
phy_init, data, phy, , 0x1000,
factory, app, factory, , 940K,
zb_fct, data, fat, , 1K,
1 # Name, Type, SubType, Offset, Size, Flags
2 # Note: if you have increased the bootloader size, make sure to update the offsets to avoid overlap
3 nvs, data, nvs, 0x9000, 0x6000, nvs, data, nvs, , 0x6000,
4 phy_init, data, phy, 0xf000, 0x1000, otadata, data, ota, , 0x2000,
5 factory, app, factory, 0x10000, 900K, phy_init, data, phy, , 0x1000,
6 zb_storage, data, fat, 0xf1000, 16K, factory, app, factory, , 940K,
7 zb_fct, data, fat, 0xf5000, 1K, zb_fct, data, fat, , 1K,
@@ -3,15 +3,11 @@
#
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x8000
CONFIG_PARTITION_TABLE_MD5=y
# end of Partition Table
#
# Zboss
# Zigbee
#
CONFIG_ZB_ENABLED=y
CONFIG_ZB_ZCZR=y
# end of Zboss
# end of Component config
CONFIG_ZB_ZED=y
# end of Zigbee
+4 -5
View File
@@ -1,12 +1,11 @@
# Light Switch and Bulb Control Example
(See the `README.md` file in the upper level 'examples' directory for more information about examples.)
See the [README.md](../README.md) file in the upper level [examples](../) directory for more information about examples.
## Overview
The folder contains examples demonstrating Zigbee Coordinator and End-Device roles
The folder contains two Zigbee examples demonstrating Coordinator and End Device roles.
* [HA_on_off_light](HA_on_off_light) is a standard HA on-off light bulb example demonstrating Zigbee End-device. It provides a simple on/off condition for a Zigbee light. It runs on an 802.15.4 SoC like ESP32-H2. For more details see the example readme file.
* [HA_on_off_switch](HA_on_off_switch) is a standard HA on-off switch example demonstrating Zigbee Coordinator role. It provides an on/off toggle to control a Zigbee HA on off light. It runs on an 802.15.4 SoC like ESP32-H2. For more details to see the example readme file.
* [HA_on_off_light](HA_on_off_light) is a standard Zigbee coordinator acting as Home Automation On/Off light bulb. It runs on an 802.15.4 SoC like ESP32-H2. For more details see [README](HA_on_off_light/README.md).
* [HA_on_off_switch](HA_on_off_switch) is a standard Zigbee End-device acting as Home Automation On/Off switch. It runs on an 802.15.4 SoC like ESP32-H2. For more details to see [README](HA_on_off_switch/README.md).
@@ -1,9 +1,8 @@
# SPDX-FileCopyrightText: 2023-2025 Espressif Systems (Shanghai) CO LTD
# SPDX-FileCopyrightText: 2023-2026 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0
# !/usr/bin/env python3
import pathlib
import time
from typing import Tuple
import pytest
from pytest_embedded import Dut
@@ -24,24 +23,25 @@ pytest_build_dir = CURRENT_DIR_LIGHT + '|' + CURRENT_DIR_SWITCH
)
# config Zigbee network
@idf_parametrize('target', ['esp32h2'], indirect=['target'])
def test_config_zigbee_network(dut: Tuple[Dut, Dut]) -> None:
def test_config_zigbee_network(dut: tuple[Dut, Dut]) -> None:
light = dut[0]
switch = dut[1]
time.sleep(3)
switch.expect('ESP_ZB_ON_OFF_SWITCH: Formed network successfully', timeout=30)
# get the switch extpanid
switch_node_expanid = switch.expect(r'Extended PAN ID: (([a-z0-9]{2}:?){8})', timeout=3)[1].decode()
switch_node_expanid = switch_node_expanid.replace(':', '')
# get the switch panid
switch_node_panid = switch.expect(r'PAN ID: 0x([a-z0-9]+:?)', timeout=2)[1].decode()
# new device commissioned successfully
switch.expect(r'New device commissioned or rejoined \(short: 0x([a-z0-9]+)[^a-z0-9]', timeout=30)[1].decode()
# get the light node extpanid
light.expect('ESP_ZB_ON_OFF_LIGHT: Joined network successfully', timeout=20)
light_node_expanid = light.expect(r'Extended PAN ID: (([a-z0-9]{2}:?){8})', timeout=3)[1].decode()
light_node_expanid = light_node_expanid.replace(':', '')
# get the light panid
light_node_panid = light.expect(r'PAN ID: 0x([a-z0-9]+:?)', timeout=2)[1].decode()
# make sure the light node join the network that switch node formed (same expanid)
if (light_node_expanid != switch_node_expanid) or (light_node_panid != switch_node_panid):
assert False
light_network = light.expect(
r'ON_OFF_LIGHT: Formed network successfully: PAN ID\(0x([a-fA-F0-9]+), EXT: 0x([a-fA-F0-9]+)\)',
timeout=30,
)
light_panid = light_network[1].decode()
light_extpanid = light_network[2].decode()
switch_network = switch.expect(
r'ON_OFF_SWITCH: Joined network successfully: PAN ID\(0x([a-fA-F0-9]+), EXT: 0x([a-fA-F0-9]+)\)',
timeout=30,
)
switch_panid = switch_network[1].decode()
switch_extpanid = switch_network[2].decode()
light.expect(r'New device commissioned or rejoined ?\(short: 0x([a-fA-F0-9]+)\)', timeout=30)
assert switch_panid == light_panid
assert switch_extpanid == light_extpanid