Skip to content

Commit dfa1db0

Browse files
P-R-O-C-H-Ypre-commit-ci-lite[bot]
authored andcommitted
feat(zigbee): Add OTA client cluster support (#10946)
* feat(zigbee): Add OTA client cluster support * feat(zigbee): Add conditions to reject OTA upgrade * feat(zigbee): Add newest version of OTA handler * fix(zigbee): Fix errors and warnings, swap parameters order * feat(zigbee): Add simple OTA Client example * ci(pre-commit): Apply automatic fixes --------- Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
1 parent 75f8550 commit dfa1db0

File tree

6 files changed

+465
-17
lines changed

6 files changed

+465
-17
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# Arduino-ESP32 Zigbee OTA Client + on/off light Example
2+
3+
This example shows how to configure the Zigbee end device with OTA Client and use it as a Home Automation (HA) on/off light.
4+
5+
# Supported Targets
6+
7+
Currently, this example supports the following targets.
8+
9+
| Supported Targets | ESP32-C6 | ESP32-H2 |
10+
| ----------------- | -------- | -------- |
11+
12+
## Hardware Required
13+
14+
* A USB cable for power supply and programming
15+
16+
### Configure the Project
17+
18+
Set the LED GPIO by changing the `LED_PIN` definition. By default, the LED_PIN is `RGB_BUILTIN`.
19+
By default, the `rgbLedWrite` function is used to control the LED. You can change it to digitalWrite to control a simple LED.
20+
21+
#### Using Arduino IDE
22+
23+
To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits).
24+
25+
* Before Compile/Verify, select the correct board: `Tools -> Board`.
26+
* Select the End device Zigbee mode: `Tools -> Zigbee mode: Zigbee ED (end device)`
27+
* Select Partition Scheme for Zigbee: `Tools -> Partition Scheme: Zigbee 4MB with spiffs`
28+
* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port.
29+
* Optional: Set debug level to verbose to see all logs from Zigbee stack: `Tools -> Core Debug Level: Verbose`.
30+
31+
## Troubleshooting
32+
33+
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.
34+
You can do the following:
35+
36+
* In the Arduino IDE go to the Tools menu and set `Erase All Flash Before Sketch Upload` to `Enabled`.
37+
* Add to the sketch `Zigbee.factoryReset();` to reset the device and Zigbee stack.
38+
39+
By default, the coordinator network is closed after rebooting or flashing new firmware.
40+
To open the network you have 2 options:
41+
42+
* Open network after reboot by setting `Zigbee.setRebootOpenNetwork(time);` before calling `Zigbee.begin();`.
43+
* In application you can anytime call `Zigbee.openNetwork(time);` to open the network for devices to join.
44+
45+
46+
***Important: Make sure you are using a good quality USB cable and that you have a reliable power source***
47+
48+
* **LED not blinking:** Check the wiring connection and the IO selection.
49+
* **Programming Fail:** If the programming/flash procedure fails, try reducing the serial connection speed.
50+
* **COM port not detected:** Check the USB cable and the USB to Serial driver installation.
51+
52+
If the error persists, you can ask for help at the official [ESP32 forum](https://esp32.com) or see [Contribute](#contribute).
53+
54+
## Contribute
55+
56+
To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst)
57+
58+
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!
59+
60+
Before creating a new issue, be sure to try Troubleshooting and check if the same issue was already created by someone else.
61+
62+
## Resources
63+
64+
* Official ESP32 Forum: [Link](https://esp32.com)
65+
* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
66+
* ESP32-C6 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c6_datasheet_en.pdf)
67+
* ESP32-H2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-h2_datasheet_en.pdf)
68+
* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
/**
16+
* @brief This example demonstrates OTA support on light bulb.
17+
*
18+
* The example demonstrates how to use Zigbee library to create a end device light bulb with OTA support.
19+
* The light bulb is a Zigbee end device, which is controlled by a Zigbee coordinator.
20+
*
21+
* Proper Zigbee mode must be selected in Tools->Zigbee mode
22+
* and also the correct partition scheme must be selected in Tools->Partition Scheme.
23+
*
24+
* Please check the README.md for instructions and more detailed description.
25+
*
26+
* Created by Jan Procházka (https://github.com/P-R-O-C-H-Y/)
27+
*/
28+
29+
#ifndef ZIGBEE_MODE_ED
30+
#error "Zigbee end device mode is not selected in Tools->Zigbee mode"
31+
#endif
32+
33+
#include "Zigbee.h"
34+
35+
/* Zigbee light bulb configuration */
36+
#define ZIGBEE_LIGHT_ENDPOINT 1
37+
uint8_t led = RGB_BUILTIN;
38+
uint8_t button = BOOT_PIN;
39+
40+
/* Zigbee OTA configuration */
41+
#define OTA_UPGRADE_RUNNING_FILE_VERSION 0x01010100 // Increment this value when the running image is updated
42+
#define OTA_UPGRADE_DOWNLOADED_FILE_VERSION 0x01010101 // Increment this value when the downloaded image is updated
43+
#define OTA_UPGRADE_HW_VERSION 0x0101 // The hardware version, this can be used to differentiate between different hardware versions
44+
45+
ZigbeeLight zbLight = ZigbeeLight(ZIGBEE_LIGHT_ENDPOINT);
46+
47+
/********************* RGB LED functions **************************/
48+
void setLED(bool value) {
49+
digitalWrite(led, value);
50+
}
51+
52+
/********************* Arduino functions **************************/
53+
void setup() {
54+
Serial.begin(115200);
55+
56+
// Init LED and turn it OFF (if LED_PIN == RGB_BUILTIN, the rgbLedWrite() will be used under the hood)
57+
pinMode(led, OUTPUT);
58+
digitalWrite(led, LOW);
59+
60+
// Init button for factory reset
61+
pinMode(button, INPUT_PULLUP);
62+
63+
// Optional: set Zigbee device name and model
64+
zbLight.setManufacturerAndModel("Espressif", "ZBLightBulb");
65+
66+
// Set callback function for light change
67+
zbLight.onLightChange(setLED);
68+
69+
// Add OTA client to the light bulb
70+
zbLight.addOTAClient(OTA_UPGRADE_RUNNING_FILE_VERSION, OTA_UPGRADE_DOWNLOADED_FILE_VERSION, OTA_UPGRADE_HW_VERSION);
71+
72+
// Add endpoint to Zigbee Core
73+
Serial.println("Adding ZigbeeLight endpoint to Zigbee Core");
74+
Zigbee.addEndpoint(&zbLight);
75+
76+
// When all EPs are registered, start Zigbee. By default acts as ZIGBEE_END_DEVICE
77+
if (!Zigbee.begin()) {
78+
Serial.println("Zigbee failed to start!");
79+
Serial.println("Rebooting...");
80+
ESP.restart();
81+
}
82+
Serial.println("Connecting to network");
83+
while (!Zigbee.connected()) {
84+
Serial.print(".");
85+
delay(100);
86+
}
87+
Serial.println();
88+
89+
// Start Zigbee OTA client query, first request is within a minute and the next requests are sent every hour automatically
90+
zbLight.requestOTAUpdate();
91+
}
92+
93+
void loop() {
94+
// Checking button for factory reset
95+
if (digitalRead(button) == LOW) { // Push button pressed
96+
// Key debounce handling
97+
delay(100);
98+
int startTime = millis();
99+
while (digitalRead(button) == LOW) {
100+
delay(50);
101+
if ((millis() - startTime) > 3000) {
102+
// If key pressed for more than 3secs, factory reset Zigbee and reboot
103+
Serial.println("Resetting Zigbee to factory and rebooting in 1s.");
104+
delay(1000);
105+
Zigbee.factoryReset();
106+
}
107+
}
108+
// Toggle light by pressing the button
109+
zbLight.setLight(!zbLight.getLightState());
110+
}
111+
delay(100);
112+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"fqbn_append": "PartitionScheme=zigbee,ZigbeeMode=ed",
3+
"requires": [
4+
"CONFIG_SOC_IEEE802154_SUPPORTED=y"
5+
]
6+
}

libraries/Zigbee/src/ZigbeeEP.cpp

+68
Original file line numberDiff line numberDiff line change
@@ -363,4 +363,72 @@ void ZigbeeEP::zbReadTimeCluster(const esp_zb_zcl_attribute_t *attribute) {
363363
}
364364
}
365365

366+
// typedef struct esp_zb_ota_cluster_cfg_s {
367+
// uint32_t ota_upgrade_file_version; /*!< The attribute indicates the file version of the running firmware image on the device */
368+
// uint16_t ota_upgrade_manufacturer; /*!< The attribute indicates the value for the manufacturer of the device */
369+
// uint16_t ota_upgrade_image_type; /*!< The attribute indicates the the image type of the file that the client is currently downloading */
370+
// uint32_t ota_upgrade_downloaded_file_ver; /*!< The attribute indicates the file version of the downloaded image on the device*/
371+
// esp_zb_ota_cluster_cfg_t;
372+
373+
// typedef struct esp_zb_zcl_ota_upgrade_client_variable_s {
374+
// uint16_t timer_query; /*!< The field indicates the time of querying OTA image for OTA upgrade client */
375+
// uint16_t hw_version; /*!< The hardware version */
376+
// uint8_t max_data_size; /*!< The maximum size of OTA data */
377+
// } esp_zb_zcl_ota_upgrade_client_variable_t;
378+
379+
void ZigbeeEP::addOTAClient(
380+
uint32_t file_version, uint32_t downloaded_file_ver, uint16_t hw_version, uint16_t manufacturer, uint16_t image_type, uint8_t max_data_size
381+
) {
382+
383+
esp_zb_ota_cluster_cfg_t ota_cluster_cfg = {};
384+
ota_cluster_cfg.ota_upgrade_file_version = file_version; //OTA_UPGRADE_RUNNING_FILE_VERSION;
385+
ota_cluster_cfg.ota_upgrade_downloaded_file_ver = downloaded_file_ver; //OTA_UPGRADE_DOWNLOADED_FILE_VERSION;
386+
ota_cluster_cfg.ota_upgrade_manufacturer = manufacturer; //OTA_UPGRADE_MANUFACTURER;
387+
ota_cluster_cfg.ota_upgrade_image_type = image_type; //OTA_UPGRADE_IMAGE_TYPE;
388+
389+
esp_zb_attribute_list_t *ota_cluster = esp_zb_ota_cluster_create(&ota_cluster_cfg);
390+
391+
esp_zb_zcl_ota_upgrade_client_variable_t variable_config = {};
392+
variable_config.timer_query = ESP_ZB_ZCL_OTA_UPGRADE_QUERY_TIMER_COUNT_DEF;
393+
variable_config.hw_version = hw_version; //OTA_UPGRADE_HW_VERSION;
394+
variable_config.max_data_size = max_data_size; //OTA_UPGRADE_MAX_DATA_SIZE;
395+
396+
uint16_t ota_upgrade_server_addr = 0xffff;
397+
uint8_t ota_upgrade_server_ep = 0xff;
398+
399+
ESP_ERROR_CHECK(esp_zb_ota_cluster_add_attr(ota_cluster, ESP_ZB_ZCL_ATTR_OTA_UPGRADE_CLIENT_DATA_ID, (void *)&variable_config));
400+
ESP_ERROR_CHECK(esp_zb_ota_cluster_add_attr(ota_cluster, ESP_ZB_ZCL_ATTR_OTA_UPGRADE_SERVER_ADDR_ID, (void *)&ota_upgrade_server_addr));
401+
ESP_ERROR_CHECK(esp_zb_ota_cluster_add_attr(ota_cluster, ESP_ZB_ZCL_ATTR_OTA_UPGRADE_SERVER_ENDPOINT_ID, (void *)&ota_upgrade_server_ep));
402+
403+
ESP_ERROR_CHECK(esp_zb_cluster_list_add_ota_cluster(_cluster_list, ota_cluster, ESP_ZB_ZCL_CLUSTER_CLIENT_ROLE));
404+
}
405+
406+
static void findOTAServer(esp_zb_zdp_status_t zdo_status, uint16_t addr, uint8_t endpoint, void *user_ctx) {
407+
if (zdo_status == ESP_ZB_ZDP_STATUS_SUCCESS) {
408+
esp_zb_ota_upgrade_client_query_interval_set(*((uint8_t *)user_ctx), OTA_UPGRADE_QUERY_INTERVAL);
409+
esp_zb_ota_upgrade_client_query_image_req(addr, endpoint);
410+
log_i("Query OTA upgrade from server endpoint: %d after %d seconds", endpoint, OTA_UPGRADE_QUERY_INTERVAL);
411+
} else {
412+
log_w("No OTA Server found");
413+
}
414+
}
415+
416+
void ZigbeeEP::requestOTAUpdate() {
417+
esp_zb_zdo_match_desc_req_param_t req;
418+
uint16_t cluster_list[] = {ESP_ZB_ZCL_CLUSTER_ID_OTA_UPGRADE};
419+
420+
/* Match the OTA server of coordinator */
421+
req.addr_of_interest = 0x0000;
422+
req.dst_nwk_addr = 0x0000;
423+
req.num_in_clusters = 1;
424+
req.num_out_clusters = 0;
425+
req.profile_id = ESP_ZB_AF_HA_PROFILE_ID;
426+
req.cluster_list = cluster_list;
427+
esp_zb_lock_acquire(portMAX_DELAY);
428+
if (esp_zb_bdb_dev_joined()) {
429+
esp_zb_zdo_match_cluster(&req, findOTAServer, &_endpoint);
430+
}
431+
esp_zb_lock_release();
432+
}
433+
366434
#endif //SOC_IEEE802154_SUPPORTED && CONFIG_ZB_ENABLED

libraries/Zigbee/src/ZigbeeEP.h

+22-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
#include <Arduino.h>
99

1010
/* Useful defines */
11-
#define ZB_CMD_TIMEOUT 10000 // 10 seconds
11+
#define ZB_CMD_TIMEOUT 10000 // 10 seconds
12+
#define OTA_UPGRADE_QUERY_INTERVAL (1 * 60) // 1 hour = 60 minutes
1213

1314
#define ZB_ARRAY_LENTH(arr) (sizeof(arr) / sizeof(arr[0]))
1415
#define XYZ_TO_RGB(X, Y, Z, r, g, b) \
@@ -107,6 +108,26 @@ class ZigbeeEP {
107108
return _allow_multiple_binding;
108109
}
109110

111+
// OTA methods
112+
/**
113+
* @brief Add OTA client to the Zigbee endpoint.
114+
*
115+
* @param file_version The current file version of the OTA client.
116+
* @param downloaded_file_ver The version of the downloaded file.
117+
* @param hw_version The hardware version of the device.
118+
* @param manufacturer The manufacturer code (default: 0x1001).
119+
* @param image_type The image type code (default: 0x1011).
120+
* @param max_data_size The maximum data size for OTA transfer (default and recommended: 223).
121+
*/
122+
void addOTAClient(
123+
uint32_t file_version, uint32_t downloaded_file_ver, uint16_t hw_version, uint16_t manufacturer = 0x1001, uint16_t image_type = 0x1011,
124+
uint8_t max_data_size = 223
125+
);
126+
/**
127+
* @brief Request OTA update from the server, first request is within a minute and the next requests are sent every hour automatically.
128+
*/
129+
void requestOTAUpdate();
130+
110131
// findEndpoind may be implemented by EPs to find and bind devices
111132
virtual void findEndpoint(esp_zb_zdo_match_desc_req_param_t *cmd_req) {};
112133

0 commit comments

Comments
 (0)