Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Zigbee): Support for sleepy device + Power Source and battery level + Humidity sensor cluster #10551

Merged
merged 10 commits into from
Nov 6, 2024
75 changes: 75 additions & 0 deletions libraries/Zigbee/examples/Zigbee_Temp_Hum_Sensor_Sleepy/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Arduino-ESP32 Zigbee Temperature and Humidity Sensor Sleepy Device Example

This example demonstrates how to use the Zigbee library to create an end device temperature/humidity sensor and use it as a Home Automation (HA) extended temperature sensor.

# Supported Targets

Currently, this example supports the following targets.

| Supported Targets | ESP32-C6 | ESP32-H2 |
| ----------------- | -------- | -------- |

## Temperature Sensor Functions

1. Initialize a Zigbee temperature and humidity sensor.
2. Measure temperature and humidity values.
3. Report the measured values to the Zigbee network.
4. Put the device to sleep to save power.

## Hardware Required

* ESP32-H2 or ESP32-C6 development board
* A USB cable for power supply and programming

### Configure the Project

In this example, to demonstrate the funcionality the chip temperature is used and reported as temperature and humidity.
Set the Button GPIO by changing the `BUTTON_PIN` definition. By default, it's the pin `9` (BOOT button on ESP32-C6 and ESP32-H2).

#### Using Arduino IDE

To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits).

* Before Compile/Verify, select the correct board: `Tools -> Board`.
* Select the End device Zigbee mode: `Tools -> Zigbee mode: Zigbee ED (end device)`
* Select Partition Scheme for Zigbee: `Tools -> Partition Scheme: Zigbee 4MB with spiffs`
* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port.
* Optional: Set debug level to verbose to see all logs from Zigbee stack: `Tools -> Core Debug Level: Verbose`.

## Troubleshooting

If the End device flashed with this example is not connecting to the coordinator, erase the flash of the End device before flashing the example to the board. It is recommended to do this if you re-flash the coordinator.
You can do the following:

* In the Arduino IDE go to the Tools menu and set `Erase All Flash Before Sketch Upload` to `Enabled`.
* Add to the sketch `Zigbee.factoryReset();` to reset the device and Zigbee stack.

By default, the coordinator network is closed after rebooting or flashing new firmware.
To open the network you have 2 options:

* Open network after reboot by setting `Zigbee.setRebootOpenNetwork(time);` before calling `Zigbee.begin();`.
* In application you can anytime call `Zigbee.openNetwork(time);` to open the network for devices to join.

***Important: Make sure you are using a good quality USB cable and that you have a reliable power source***

* **LED not blinking:** Check the wiring connection and the IO selection.
* **Programming Fail:** If the programming/flash procedure fails, try reducing the serial connection speed.
* **COM port not detected:** Check the USB cable and the USB to Serial driver installation.

If the error persists, you can ask for help at the official [ESP32 forum](https://esp32.com) or see [Contribute](#contribute).

## Contribute

To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst)

If you have any **feedback** or **issue** to report on this example/library, please open an issue or fix it by creating a new PR. Contributions are more than welcome!

Before creating a new issue, be sure to try Troubleshooting and check if the same issue was already created by someone else.

## Resources

* Official ESP32 Forum: [Link](https://esp32.com)
* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
* ESP32-C6 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c6_datasheet_en.pdf)
* ESP32-H2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-h2_datasheet_en.pdf)
* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com)
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// Copyright 2024 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.

/**
* @brief This example demonstrates Zigbee temperature and humidity sensor Sleepy device.
*
* The example demonstrates how to use Zigbee library to create an end device temperature and humidity sensor.
* The sensor is a Zigbee end device, which is reporting data to the Zigbee network.
*
* Proper Zigbee mode must be selected in Tools->Zigbee mode
* and also the correct partition scheme must be selected in Tools->Partition Scheme.
*
* Please check the README.md for instructions and more detailed description.
*
* Created by Jan Procházka (https://github.com/P-R-O-C-H-Y/)
*/

#ifndef ZIGBEE_MODE_ED
#error "Zigbee coordinator mode is not selected in Tools->Zigbee mode"
#endif

#include "ZigbeeCore.h"
#include "ep/ZigbeeTempSensor.h"

#define BUTTON_PIN 9 //Boot button for C6/H2
#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 */

ZigbeeTempSensor zbTempSensor = ZigbeeTempSensor(TEMP_SENSOR_ENDPOINT_NUMBER);

/************************ Temp sensor *****************************/
void meausureAndSleep(){
// Measure temperature sensor value
float temperature = temperatureRead();

// Use temparture value as humidity value to demonstrate both temperature and humidity
float humidity = temperature;

// Update temperature and humidity values in Temperature sensor EP
zbTempSensor.setTemperature(temperature);
zbTempSensor.setHumidity(humidity);

// Report temperature and humidity values
zbTempSensor.reportTemperature();
zbTempSensor.reportHumidity();

log_d("Temperature: %.2f°C, Humidity: %.2f%", temperature, humidity);

// Put device to deep sleep
esp_deep_sleep_start();
}

/********************* Arduino functions **************************/
void setup() {
// Init button switch
pinMode(BUTTON_PIN, INPUT_PULLUP);

// Configure the wake up source and set to wake up every 5 seconds
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);

// Optional: set Zigbee device name and model
zbTempSensor.setManufacturerAndModel("Espressif", "SleepyZigbeeTempSensorTest");

// Set minimum and maximum temperature measurement value (10-50°C is default range for chip temperature measurement)
zbTempSensor.setMinMaxValue(10, 50);

// Set tolerance for temperature measurement in °C (lowest possible value is 0.01°C)
zbTempSensor.setTolerance(1);

// Set power source to battery and set battery percentage to measured value (now 100% for demonstration)
// The value can be also updated by calling zbTempSensor.setBatteryPercentage(percentage) anytime
zbTempSensor.setPowerSource(ZB_POWER_SOURCE_BATTERY, 100);

// Add humidity cluster to the temperature sensor device with min, max and tolerance values
zbTempSensor.addHumiditySensor(0,100,1);

// Add endpoint to Zigbee Core
Zigbee.addEndpoint(&zbTempSensor);

// Create a custom Zigbee configuration for End Device with keep alive 10s to avoid interference with reporting data
esp_zb_cfg_t zigbeeConfig = ZIGBEE_DEFAULT_ED_CONFIG();
zigbeeConfig.nwk_cfg.zed_cfg.keep_alive = 10000;

// When all EPs are registered, start Zigbee in End Device mode
Zigbee.begin(&zigbeeConfig, false);

// Wait for Zigbee to start
while(!Zigbee.isStarted()){
delay(100);
}

// Delay 5s to allow establishing connection with coordinator, needed for sleepy devices
delay(5000);
SuGlider marked this conversation as resolved.
Show resolved Hide resolved
}

void loop() {
// Checking button for factory reset
if (digitalRead(BUTTON_PIN) == LOW) { // Push button pressed
// Key debounce handling
delay(100);
int startTime = millis();
while (digitalRead(BUTTON_PIN) == LOW) {
delay(50);
if ((millis() - startTime) > 3000) {
SuGlider marked this conversation as resolved.
Show resolved Hide resolved
// If key pressed for more than 3secs, factory reset Zigbee and reboot
Zigbee.factoryReset();
}
}
}

// Call the function to measure temperature and put the device to sleep
meausureAndSleep();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"fqbn_append": "PartitionScheme=zigbee,ZigbeeMode=ed",
"requires": [
"CONFIG_SOC_IEEE802154_SUPPORTED=y"
]
}
20 changes: 17 additions & 3 deletions libraries/Zigbee/src/ZigbeeCore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
#include "ZigbeeHandlers.cpp"
#include "Arduino.h"

extern "C" void zb_set_ed_node_descriptor(bool power_src, bool rx_on_when_idle, bool alloc_addr);
static bool edBatteryPowered = false;

ZigbeeCore::ZigbeeCore() {
_radio_config.radio_mode = ZB_RADIO_MODE_NATIVE; // Use the native 15.4 radio
_host_config.host_connection_mode = ZB_HOST_CONNECTION_MODE_NONE; // Disable host connection
Expand Down Expand Up @@ -73,6 +76,12 @@ void ZigbeeCore::addEndpoint(ZigbeeEP *ep) {
static void esp_zb_task(void *pvParameters) {
/* initialize Zigbee stack */
ESP_ERROR_CHECK(esp_zb_start(false));

//NOTE: This is a workaround to make battery powered devices to be discovered as battery powered
if(((zigbee_role_t)Zigbee.getRole() == ZIGBEE_END_DEVICE) && edBatteryPowered ) {
zb_set_ed_node_descriptor(0,0,0);
}

esp_zb_stack_main_loop();
}

Expand Down Expand Up @@ -109,6 +118,9 @@ bool ZigbeeCore::zigbeeInit(esp_zb_cfg_t *zb_cfg, bool erase_nvs) {
log_i("List of registered Zigbee EPs:");
for (std::list<ZigbeeEP *>::iterator it = ep_objects.begin(); it != ep_objects.end(); ++it) {
log_i("Device type: %s, Endpoint: %d, Device ID: 0x%04x", getDeviceTypeString((*it)->_device_id), (*it)->_endpoint, (*it)->_device_id);
if((*it)->_power_source == ZB_POWER_SOURCE_BATTERY) {
edBatteryPowered = true;
}
}
}
// Register Zigbee action handler
Expand Down Expand Up @@ -155,7 +167,7 @@ void ZigbeeCore::setRebootOpenNetwork(uint8_t time) {
}

void ZigbeeCore::openNetwork(uint8_t time) {
if (_started) {
if (isStarted()) {
log_v("Opening network for joining for %d seconds", time);
esp_zb_bdb_open_network(time);
}
Expand Down Expand Up @@ -205,6 +217,7 @@ void esp_zb_app_signal_handler(esp_zb_app_signal_t *signal_struct) {
} else {
/* commissioning failed */
log_e("Failed to initialize Zigbee stack (status: %s)", esp_err_to_name(err_status));
esp_restart();
}
break;
case ESP_ZB_BDB_SIGNAL_FORMATION: // Coordinator
Expand All @@ -225,11 +238,11 @@ void esp_zb_app_signal_handler(esp_zb_app_signal_t *signal_struct) {
}
break;
case ESP_ZB_BDB_SIGNAL_STEERING: // Router and End Device
Zigbee._started = true;
if ((zigbee_role_t)Zigbee.getRole() == ZIGBEE_COORDINATOR) {
if (err_status == ESP_OK) {
log_i("Network steering started");
}
Zigbee._started = true;
} else {
if (err_status == ESP_OK) {
esp_zb_ieee_addr_t extended_pan_id;
Expand All @@ -239,6 +252,7 @@ void esp_zb_app_signal_handler(esp_zb_app_signal_t *signal_struct) {
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()
);
Zigbee._started = true;
} else {
log_i("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);
Expand Down Expand Up @@ -321,7 +335,7 @@ void ZigbeeCore::scanCompleteCallback(esp_zb_zdp_status_t zdo_status, uint8_t co
}

void ZigbeeCore::scanNetworks(u_int32_t channel_mask, u_int8_t scan_duration) {
if (!_started) {
if (!isStarted()) {
log_e("Zigbee stack is not started, cannot scan networks");
return;
}
Expand Down
66 changes: 64 additions & 2 deletions libraries/Zigbee/src/ZigbeeEP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,32 @@
#if SOC_IEEE802154_SUPPORTED

#include "esp_zigbee_cluster.h"
#include "zcl/esp_zigbee_zcl_power_config.h"

uint8_t ZigbeeEP::_endpoint = 0;
#ifdef __cplusplus
P-R-O-C-H-Y marked this conversation as resolved.
Show resolved Hide resolved
extern "C"
{
#endif

extern void zb_set_ed_node_descriptor(bool power_src, bool rx_on_when_idle, bool alloc_addr);
P-R-O-C-H-Y marked this conversation as resolved.
Show resolved Hide resolved

#ifdef __cplusplus
}
#endif

// uint8_t ZigbeeEP::_endpoint = 0;
bool ZigbeeEP::_is_bound = false;
bool ZigbeeEP::_allow_multiple_binding = false;

//TODO: is_bound and allow_multiple_binding to make not static

/* Zigbee End Device Class */
ZigbeeEP::ZigbeeEP(uint8_t endpoint) {
_endpoint = endpoint;
log_v("Endpoint: %d", _endpoint);
_ep_config.endpoint = 0;
_cluster_list = nullptr;
_on_identify = nullptr;
#if !CONFIG_DISABLE_HAL_LOCKS
if (!lock) {
lock = xSemaphoreCreateBinary();
Expand Down Expand Up @@ -65,6 +81,50 @@ void ZigbeeEP::setManufacturerAndModel(const char *name, const char *model) {
esp_zb_basic_cluster_add_attr(basic_cluster, ESP_ZB_ZCL_ATTR_BASIC_MODEL_IDENTIFIER_ID, (void *)zb_model);
}

void ZigbeeEP::setPowerSource(zb_power_source_t power_source, uint8_t battery_percentage) {
esp_zb_attribute_list_t *basic_cluster = esp_zb_cluster_list_get_cluster(_cluster_list, ESP_ZB_ZCL_CLUSTER_ID_BASIC, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE);
esp_zb_cluster_update_attr(basic_cluster, ESP_ZB_ZCL_ATTR_BASIC_POWER_SOURCE_ID, (void *)&power_source);

if(power_source == ZB_POWER_SOURCE_BATTERY){
// Add power config cluster and battery percentage attribute
battery_percentage = battery_percentage * 2;
esp_zb_attribute_list_t *power_config_cluster = esp_zb_zcl_attr_list_create(ESP_ZB_ZCL_CLUSTER_ID_POWER_CONFIG);
esp_zb_power_config_cluster_add_attr(power_config_cluster, ESP_ZB_ZCL_ATTR_POWER_CONFIG_BATTERY_PERCENTAGE_REMAINING_ID, (void *)&battery_percentage);
esp_zb_cluster_list_add_power_config_cluster(_cluster_list, power_config_cluster, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE);
}
_power_source = power_source;
}

void ZigbeeEP::setBatteryPercentage(uint8_t percentage) {
// 100% = 200 in decimal, 0% = 0
// Convert percentage to 0-200 range
if (percentage > 100) {
percentage = 100;
}
percentage = percentage * 2;
esp_zb_lock_acquire(portMAX_DELAY);
esp_zb_zcl_set_attribute_val(
_endpoint, ESP_ZB_ZCL_CLUSTER_ID_POWER_CONFIG, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE, ESP_ZB_ZCL_ATTR_POWER_CONFIG_BATTERY_PERCENTAGE_REMAINING_ID, &percentage, false
);
esp_zb_lock_release();
log_v("Battery percentage updated");
}

void ZigbeeEP::reportBatteryPercentage() {
/* Send report attributes command */
esp_zb_zcl_report_attr_cmd_t report_attr_cmd;
report_attr_cmd.address_mode = ESP_ZB_APS_ADDR_MODE_DST_ADDR_ENDP_NOT_PRESENT;
report_attr_cmd.attributeID = ESP_ZB_ZCL_ATTR_POWER_CONFIG_BATTERY_PERCENTAGE_REMAINING_ID;
report_attr_cmd.cluster_role = ESP_ZB_ZCL_CLUSTER_SERVER_ROLE;
report_attr_cmd.clusterID = ESP_ZB_ZCL_CLUSTER_ID_POWER_CONFIG;
report_attr_cmd.zcl_basic_cmd.src_endpoint = _endpoint;

esp_zb_lock_acquire(portMAX_DELAY);
esp_zb_zcl_report_attr_cmd_req(&report_attr_cmd);
esp_zb_lock_release();
log_v("Battery percentage reported");
}

char *ZigbeeEP::readManufacturer(uint8_t endpoint, uint16_t short_addr) {
/* Read peer Manufacture Name & Model Identifier */
esp_zb_zcl_read_attr_cmd_t read_req;
Expand Down Expand Up @@ -153,7 +213,9 @@ void ZigbeeEP::zbReadBasicCluster(const esp_zb_zcl_attribute_t *attribute) {

void ZigbeeEP::zbIdentify(const esp_zb_zcl_set_attr_value_message_t *message) {
if (message->attribute.id == ESP_ZB_ZCL_CMD_IDENTIFY_IDENTIFY_ID && message->attribute.data.type == ESP_ZB_ZCL_ATTR_TYPE_U16) {
_on_identify(*(uint16_t *)message->attribute.data.value);
if(_on_identify != NULL) {
_on_identify(*(uint16_t *)message->attribute.data.value);
}
} else {
log_w("Other identify commands are not implemented yet.");
}
Expand Down
Loading
Loading