Skip to content

Commit 9090b46

Browse files
lboueP-R-O-C-H-Ypre-commit-ci-lite[bot]
authored
feat(esp32): Zigbee power outlet example (espressif#11296)
* feat(esp32): Zigbee power outlet example Zigbee power outlet example * feat(esp32): Zigbee power outlet example Change username * feat(esp32): Zigbee power outlet example Remove old comment * fix(zigbee): fix power outlet compile errors and update example * fix(example): Update readme * fix(example): Update ci json file * ci(pre-commit): Apply automatic fixes * fix(): precommit codespell --------- Co-authored-by: Jan Procházka <90197375+P-R-O-C-H-Y@users.noreply.github.com> Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
1 parent d85b75c commit 9090b46

File tree

8 files changed

+272
-0
lines changed

8 files changed

+272
-0
lines changed

CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,7 @@ set(ARDUINO_LIBRARY_Zigbee_SRCS
301301
libraries/Zigbee/src/ep/ZigbeeWindSpeedSensor.cpp
302302
libraries/Zigbee/src/ep/ZigbeeIlluminanceSensor.cpp
303303
libraries/Zigbee/src/ep/ZigbeePM25Sensor.cpp
304+
libraries/Zigbee/src/ep/ZigbeePowerOutlet.cpp
304305
)
305306

306307
set(ARDUINO_LIBRARY_BLE_SRCS
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
@ -0,0 +1,68 @@
2+
# Arduino-ESP32 Zigbee On/Off Power Outlet Example
3+
4+
This example shows how to configure Zigbee Router device and use it as a Home Automation (HA) on/off power outlet.
5+
6+
# Supported Targets
7+
8+
Currently, this example supports the following targets.
9+
10+
| Supported Targets | ESP32-C6 | ESP32-H2 |
11+
| ----------------- | -------- | -------- |
12+
13+
## Hardware Required
14+
15+
* A USB cable for power supply and programming.
16+
17+
### Configure the Project
18+
19+
Set the Button GPIO by changing the `button` definition. By default, it's the pin `9` (BOOT button on ESP32-C6 and ESP32-H2).
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 Coordinator Zigbee mode: `Tools -> Zigbee mode: Zigbee ZCZR (coordinator/router)`.
27+
* Select Partition Scheme for Zigbee: `Tools -> Partition Scheme: Zigbee ZCZR 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 device flashed with the example `Zigbee_Power_Outlet` is not connecting to the coordinator, erase the flash of the device before flashing the example to the board. It is recommended to do this if you re-flash the coordinator or do some big changes in the application code.
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+
* In the `Zigbee_Power_Outlet` example sketch call `Zigbee.factoryReset();`.
38+
39+
***Important: Make sure you are using a good quality USB cable and that you have a reliable power source***
40+
41+
* **LED not blinking:** Check the wiring connection and the IO selection.
42+
* **Programming Fail:** If the programming/flash procedure fails, try reducing the serial connection speed.
43+
* **COM port not detected:** Check the USB cable and the USB to Serial driver installation.
44+
45+
If the error persists, you can ask for help at the official [ESP32 forum](https://esp32.com) or see [Contribute](#contribute).
46+
47+
## Contribute
48+
49+
To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst)
50+
51+
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!
52+
53+
Before creating a new issue, be sure to try Troubleshooting and check if the same issue was already created by someone else.
54+
55+
## Resources
56+
57+
* Official ESP32 Forum: [Link](https://esp32.com)
58+
* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
59+
* ESP32-C6 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c6_datasheet_en.pdf)
60+
* ESP32-H2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-h2_datasheet_en.pdf)
61+
* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com)
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
// Copyright 2025 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 simple Zigbee power outlet.
17+
*
18+
* The example demonstrates how to use Zigbee library to create a end device power outlet.
19+
* The power outlet 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 Ludovic Boué (https://github.com/lboue)
27+
*/
28+
29+
#ifndef ZIGBEE_MODE_ZCZR
30+
#error "Zigbee router mode is not selected in Tools->Zigbee mode"
31+
#endif
32+
33+
#include "Zigbee.h"
34+
35+
/* Zigbee power outlet configuration */
36+
#define ZIGBEE_OUTLET_ENDPOINT 1
37+
uint8_t led = RGB_BUILTIN;
38+
uint8_t button = BOOT_PIN;
39+
40+
ZigbeePowerOutlet zbOutlet = ZigbeePowerOutlet(ZIGBEE_OUTLET_ENDPOINT);
41+
42+
/********************* RGB LED functions **************************/
43+
void setLED(bool value) {
44+
digitalWrite(led, value);
45+
}
46+
47+
/********************* Arduino functions **************************/
48+
void setup() {
49+
Serial.begin(115200);
50+
51+
// Init LED and turn it OFF (if LED_PIN == RGB_BUILTIN, the rgbLedWrite() will be used under the hood)
52+
pinMode(led, OUTPUT);
53+
digitalWrite(led, LOW);
54+
55+
// Init button for factory reset
56+
pinMode(button, INPUT_PULLUP);
57+
58+
//Optional: set Zigbee device name and model
59+
zbOutlet.setManufacturerAndModel("Espressif", "ZBPowerOutlet");
60+
61+
// Set callback function for power outlet change
62+
zbOutlet.onPowerOutletChange(setLED);
63+
64+
//Add endpoint to Zigbee Core
65+
Serial.println("Adding ZigbeePowerOutlet endpoint to Zigbee Core");
66+
Zigbee.addEndpoint(&zbOutlet);
67+
68+
// When all EPs are registered, start Zigbee. By default acts as ZIGBEE_END_DEVICE
69+
if (!Zigbee.begin(ZIGBEE_ROUTER)) {
70+
Serial.println("Zigbee failed to start!");
71+
Serial.println("Rebooting...");
72+
ESP.restart();
73+
}
74+
Serial.println("Connecting to network");
75+
while (!Zigbee.connected()) {
76+
Serial.print(".");
77+
delay(100);
78+
}
79+
Serial.println();
80+
}
81+
82+
void loop() {
83+
// Checking button for factory reset
84+
if (digitalRead(button) == LOW) { // Push button pressed
85+
// Key debounce handling
86+
delay(100);
87+
int startTime = millis();
88+
while (digitalRead(button) == LOW) {
89+
delay(50);
90+
if ((millis() - startTime) > 3000) {
91+
// If key pressed for more than 3secs, factory reset Zigbee and reboot
92+
Serial.println("Resetting Zigbee to factory and rebooting in 1s.");
93+
delay(1000);
94+
Zigbee.factoryReset();
95+
}
96+
}
97+
// Toggle state by pressing the button
98+
zbOutlet.setState(!zbOutlet.getPowerOutletState());
99+
}
100+
delay(100);
101+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"fqbn_append": "PartitionScheme=zigbee_zczr,ZigbeeMode=zczr",
3+
"requires": [
4+
"CONFIG_SOC_IEEE802154_SUPPORTED=y",
5+
"CONFIG_ZB_ENABLED=y"
6+
]
7+
}

libraries/Zigbee/keywords.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ ZigbeeRangeExtender KEYWORD1
3030
ZigbeeVibrationSensor KEYWORD1
3131
ZigbeeWindowCovering KEYWORD1
3232
ZigbeeIlluminanceSensor KEYWORD1
33+
ZigbeePowerOutlet KEYWORD1
3334

3435
# Other
3536
zigbee_role_t KEYWORD1

libraries/Zigbee/src/Zigbee.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
#include "ep/ZigbeeLight.h"
1717
//// Controllers
1818
#include "ep/ZigbeeThermostat.h"
19+
////Outlets
20+
#include "ep/ZigbeePowerOutlet.h"
1921
//// Sensors
2022
#include "ep/ZigbeeAnalog.h"
2123
#include "ep/ZigbeeCarbonDioxideSensor.h"
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include "ZigbeePowerOutlet.h"
2+
#if CONFIG_ZB_ENABLED
3+
4+
ZigbeePowerOutlet::ZigbeePowerOutlet(uint8_t endpoint) : ZigbeeEP(endpoint) {
5+
_device_id = ESP_ZB_HA_MAINS_POWER_OUTLET_DEVICE_ID;
6+
7+
esp_zb_mains_power_outlet_cfg_t outlet_cfg = ESP_ZB_DEFAULT_MAINS_POWER_OUTLET_CONFIG();
8+
_cluster_list = esp_zb_mains_power_outlet_clusters_create(&outlet_cfg);
9+
_ep_config = {
10+
.endpoint = endpoint, .app_profile_id = ESP_ZB_AF_HA_PROFILE_ID, .app_device_id = ESP_ZB_HA_MAINS_POWER_OUTLET_DEVICE_ID, .app_device_version = 0
11+
};
12+
log_v("Outlet endpoint created %d", _endpoint);
13+
}
14+
15+
//set attribute method -> method overridden in child class
16+
void ZigbeePowerOutlet::zbAttributeSet(const esp_zb_zcl_set_attr_value_message_t *message) {
17+
//check the data and call right method
18+
if (message->info.cluster == ESP_ZB_ZCL_CLUSTER_ID_ON_OFF) {
19+
if (message->attribute.id == ESP_ZB_ZCL_ATTR_ON_OFF_ON_OFF_ID && message->attribute.data.type == ESP_ZB_ZCL_ATTR_TYPE_BOOL) {
20+
_current_state = *(bool *)message->attribute.data.value;
21+
stateChanged();
22+
} else {
23+
log_w("Received message ignored. Attribute ID: %d not supported for On/Off Outlet", message->attribute.id);
24+
}
25+
} else {
26+
log_w("Received message ignored. Cluster ID: %d not supported for On/Off Outlet", message->info.cluster);
27+
}
28+
}
29+
30+
void ZigbeePowerOutlet::stateChanged() {
31+
if (_on_state_change) {
32+
_on_state_change(_current_state);
33+
} else {
34+
log_w("No callback function set for outlet change");
35+
}
36+
}
37+
38+
bool ZigbeePowerOutlet::setState(bool state) {
39+
esp_zb_zcl_status_t ret = ESP_ZB_ZCL_STATUS_SUCCESS;
40+
_current_state = state;
41+
stateChanged();
42+
43+
log_v("Updating on/off outlet state to %d", state);
44+
/* Update on/off outlet state */
45+
esp_zb_lock_acquire(portMAX_DELAY);
46+
ret = esp_zb_zcl_set_attribute_val(
47+
_endpoint, ESP_ZB_ZCL_CLUSTER_ID_ON_OFF, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE, ESP_ZB_ZCL_ATTR_ON_OFF_ON_OFF_ID, &_current_state, false
48+
);
49+
esp_zb_lock_release();
50+
51+
if (ret != ESP_ZB_ZCL_STATUS_SUCCESS) {
52+
log_e("Failed to set outlet state: 0x%x: %s", ret, esp_zb_zcl_status_to_name(ret));
53+
return false;
54+
}
55+
return true;
56+
}
57+
58+
#endif // CONFIG_ZB_ENABLED
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/* Class of Zigbee On/Off Power outlet endpoint inherited from common EP class */
2+
3+
#pragma once
4+
5+
#include "soc/soc_caps.h"
6+
#include "sdkconfig.h"
7+
#if CONFIG_ZB_ENABLED
8+
9+
#include "ZigbeeEP.h"
10+
#include "ha/esp_zigbee_ha_standard.h"
11+
12+
class ZigbeePowerOutlet : public ZigbeeEP {
13+
public:
14+
ZigbeePowerOutlet(uint8_t endpoint);
15+
~ZigbeePowerOutlet() {}
16+
17+
// Use to set a cb function to be called on outlet change
18+
void onPowerOutletChange(void (*callback)(bool)) {
19+
_on_state_change = callback;
20+
}
21+
// Use to restore outlet state
22+
void restoreState() {
23+
stateChanged();
24+
}
25+
// Use to control outlet state
26+
bool setState(bool state);
27+
// Use to get outlet state
28+
bool getPowerOutletState() {
29+
return _current_state;
30+
}
31+
32+
private:
33+
void zbAttributeSet(const esp_zb_zcl_set_attr_value_message_t *message) override;
34+
//callback function to be called on outlet change
35+
void (*_on_state_change)(bool);
36+
void stateChanged();
37+
38+
bool _current_state;
39+
};
40+
41+
#endif // CONFIG_ZB_ENABLED

0 commit comments

Comments
 (0)