Skip to content

Commit e37435c

Browse files
MikaFromTheRoofP-R-O-C-H-Ypre-commit-ci-lite[bot]
authored
feat(zigbee): Add Illuminance sensor endpoint (#11171)
* Added Zigbee light sensor * Add comment for macro * Some last corrections * refactor(zigbee): changed class name to ZigbeeIlluminanceSensor * feat(zigbee): Illumanance sensor update * fix(zigbee): Change name of macro to avoid possible conflict with esp-zigbee-sdk * Update keywords.txt * fix(zigbee): Add Illuminance to Cmake file * fix(example): Update Illuminance example * ci(pre-commit): Apply automatic fixes * Update Zigbee_Illuminance_Sensor.ino * ci(pre-commit): Apply automatic fixes --------- Co-authored-by: Jan Procházka <[email protected]> Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
1 parent 8622147 commit e37435c

File tree

8 files changed

+357
-0
lines changed

8 files changed

+357
-0
lines changed

Diff for: CMakeLists.txt

+1
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,7 @@ set(ARDUINO_LIBRARY_Zigbee_SRCS
299299
libraries/Zigbee/src/ep/ZigbeeRangeExtender.cpp
300300
libraries/Zigbee/src/ep/ZigbeeGateway.cpp
301301
libraries/Zigbee/src/ep/ZigbeeWindSpeedSensor.cpp
302+
libraries/Zigbee/src/ep/ZigbeeIlluminanceSensor.cpp
302303
)
303304

304305
set(ARDUINO_LIBRARY_BLE_SRCS
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# Arduino-ESP32 Zigbee Illuminance Sensor Example
2+
3+
This example demonstrates how to use the Zigbee library to create an end device illuminance sensor and use it as a Home Automation (HA) extended illuminance sensor.
4+
5+
# Supported Targets
6+
7+
Currently, this example supports the following targets.
8+
9+
| Supported Targets | ESP32-C6 | ESP32-H2 |
10+
| ----------------- | -------- | -------- |
11+
12+
## Illuminance Sensor Functions
13+
14+
1. Initialize a Zigbee illuminance sensor.
15+
2. Measure illuminance value.
16+
3. Report the measured value to the Zigbee network.
17+
18+
## Hardware Required
19+
20+
* ESP32-H2 or ESP32-C6 development board
21+
* A USB cable for power supply and programming
22+
* Some kind of light sensor, such as a photoresistor
23+
24+
### Configure the Project
25+
26+
In this example the raw analog value of a light sensor is used to calculate illuminance.
27+
Alter the calculation according to your use case and calibrate it to receive correct lux values.
28+
Set the illuminance sensor GPIO by changing the `illuminance_sensor_pin` variable to the pin to the pin to which your sensor is connected.
29+
Set the button GPIO by changing the `button` variable. By default, it's the pin `BOOT_PIN` (BOOT button on ESP32-C6 and ESP32-H2).
30+
31+
#### Using Arduino IDE
32+
33+
To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits).
34+
35+
* Before Compile/Verify, select the correct board: `Tools -> Board`.
36+
* Select the End device Zigbee mode: `Tools -> Zigbee mode: Zigbee ED (end device)`
37+
* Select Partition Scheme for Zigbee: `Tools -> Partition Scheme: Zigbee 4MB with spiffs`
38+
* Enable USB CDC to be able to use the serial monitor: `Tools -> USB CDC On Boot: Enabled`
39+
* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port.
40+
* Optional: Set debug level to verbose to see all logs from Zigbee stack: `Tools -> Core Debug Level: Verbose`.
41+
42+
## Troubleshooting
43+
44+
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.
45+
You can do the following:
46+
47+
* In the Arduino IDE go to the Tools menu and set `Erase All Flash Before Sketch Upload` to `Enabled`.
48+
* Add to the sketch `Zigbee.factoryReset();` to reset the device and Zigbee stack.
49+
50+
By default, the coordinator network is closed after rebooting or flashing new firmware.
51+
To open the network you have 2 options:
52+
53+
* Open network after reboot by setting `Zigbee.setRebootOpenNetwork(time);` before calling `Zigbee.begin();`.
54+
* In application you can anytime call `Zigbee.openNetwork(time);` to open the network for devices to join.
55+
56+
***Important: Make sure that you are using a good quality USB cable with data lines and that you have a reliable power source***
57+
58+
* **LED not blinking:** Check the wiring connection and the IO selection.
59+
* **Programming Fail:** If the programming/flash procedure fails, try reducing the serial connection speed.
60+
* **COM port not detected:** Check the USB cable and the USB to Serial driver installation.
61+
62+
If the error persists, you can ask for help at the official [ESP32 forum](https://esp32.com) or see [Contribute](#contribute).
63+
64+
## Contribute
65+
66+
To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst)
67+
68+
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!
69+
70+
Before creating a new issue, be sure to try Troubleshooting and check if the same issue was already created by someone else.
71+
72+
## Resources
73+
74+
* Official ESP32 Forum: [Link](https://esp32.com)
75+
* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
76+
* ESP32-C6 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c6_datasheet_en.pdf)
77+
* ESP32-H2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-h2_datasheet_en.pdf)
78+
* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
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 Zigbee illuminance sensor.
17+
*
18+
* The example demonstrates how to use Zigbee library to create a end device illuminance sensor.
19+
* The illuminance sensor 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 MikaFromTheRoof (https://github.com/MikaFromTheRoof)
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+
#define ZIGBEE_ILLUMINANCE_SENSOR_ENDPOINT 9
36+
uint8_t button = BOOT_PIN;
37+
uint8_t illuminance_sensor_pin = 6; // Insert the analog pin to which the sensor (e.g. photoresistor) is connected
38+
39+
ZigbeeIlluminanceSensor zbIlluminanceSensor = ZigbeeIlluminanceSensor(ZIGBEE_ILLUMINANCE_SENSOR_ENDPOINT);
40+
41+
/********************* Illuminance sensor **************************/
42+
static void illuminance_sensor_value_update(void *arg) {
43+
for (;;) {
44+
// read the raw analog value from the sensor
45+
int lsens_analog_raw = analogRead(illuminance_sensor_pin);
46+
Serial.printf("[Illuminance Sensor] raw analog value: %d\r\n", lsens_analog_raw);
47+
48+
// conversion into zigbee raw illuminance value (typically between 0 in darkness and 50000 in direct sunlight)
49+
// depends on the value range of the raw analog sensor values and will need calibration for correct lux values
50+
// for demonstration purpose map the 12-bit ADC value (0-4095) to Zigbee illuminance range (0-50000)
51+
int lsens_illuminance_raw = map(lsens_analog_raw, 0, 4095, 0, 50000);
52+
Serial.printf("[Illuminance Sensor] raw illuminance value: %d\r\n", lsens_illuminance_raw);
53+
54+
// according to zigbee documentation the formular 10^(lsens_illuminance_raw/10000)-1 can be used to calculate lux value from raw illuminance value
55+
// Note: Zigbee2MQTT seems to be using the formular 10^(lsens_illuminance_raw/10000) instead (without -1)
56+
int lsens_illuminance_lux = round(pow(10, (lsens_illuminance_raw / 10000.0)) - 1);
57+
Serial.printf("[Illuminance Sensor] lux value: %d lux\r\n", lsens_illuminance_lux);
58+
59+
// Update illuminance in illuminance sensor EP
60+
zbIlluminanceSensor.setIlluminance(lsens_illuminance_raw); // use raw illuminance here!
61+
62+
delay(1000); // reduce delay (in ms), if you want your device to react more quickly to changes in illuminance
63+
}
64+
}
65+
66+
/********************* Arduino functions **************************/
67+
void setup() {
68+
Serial.begin(115200);
69+
70+
// Optional: configure analog input
71+
analogSetAttenuation(ADC_11db); // set analog to digital converter (ADC) attenuation to 11 dB (up to ~3.3V input)
72+
analogReadResolution(12); // set analog read resolution to 12 bits (value range from 0 to 4095), 12 is default
73+
74+
// Init button for factory reset
75+
pinMode(button, INPUT_PULLUP);
76+
77+
// Optional: Set Zigbee device name and model
78+
zbIlluminanceSensor.setManufacturerAndModel("Espressif", "ZigbeeIlluminanceSensor");
79+
80+
// Optional: Set power source (choose between ZB_POWER_SOURCE_MAINS and ZB_POWER_SOURCE_BATTERY), defaults to unknown
81+
zbIlluminanceSensor.setPowerSource(ZB_POWER_SOURCE_MAINS);
82+
83+
// Set minimum and maximum for raw illuminance value (0 min and 50000 max equals to 0 lux - 100,000 lux)
84+
zbIlluminanceSensor.setMinMaxValue(0, 50000);
85+
86+
// Optional: Set tolerance for raw illuminance value
87+
zbIlluminanceSensor.setTolerance(1);
88+
89+
// Add endpoint to Zigbee Core
90+
Serial.println("Adding Zigbee illuminance sensor endpoint to Zigbee Core");
91+
Zigbee.addEndpoint(&zbIlluminanceSensor);
92+
93+
Serial.println("Starting Zigbee...");
94+
// When all EPs are registered, start Zigbee in End Device mode
95+
if (!Zigbee.begin()) {
96+
Serial.println("Zigbee failed to start!");
97+
Serial.println("Rebooting...");
98+
ESP.restart();
99+
} else {
100+
Serial.println("Zigbee started successfully!");
101+
}
102+
Serial.println("Connecting to network");
103+
while (!Zigbee.connected()) {
104+
Serial.print(".");
105+
delay(100);
106+
}
107+
Serial.println();
108+
109+
// Start illuminance sensor reading task
110+
xTaskCreate(illuminance_sensor_value_update, "illuminance_sensor_update", 2048, NULL, 10, NULL);
111+
112+
// Set reporting schedule for illuminance value measurement in seconds, must be called after Zigbee.begin()
113+
// min_interval and max_interval in seconds, delta
114+
// if min = 1 and max = 0, delta = 1000, reporting is sent when raw illuminance value changes by 1000, but at most once per second
115+
// if min = 0 and max = 10, delta = 1000, reporting is sent every 10 seconds or if raw illuminance value changes by 1000
116+
// if min = 0, max = 10 and delta = 0, reporting is sent every 10 seconds regardless of illuminance change
117+
// Note: On pairing with Zigbee Home Automation or Zigbee2MQTT the reporting schedule will most likely be overwritten with their default settings
118+
zbIlluminanceSensor.setReporting(1, 0, 1000);
119+
}
120+
121+
/********************* Main loop **************************/
122+
void loop() {
123+
// Checking button for factory reset
124+
if (digitalRead(button) == LOW) { // Push button pressed
125+
// Key debounce handling
126+
delay(100);
127+
int startTime = millis();
128+
while (digitalRead(button) == LOW) {
129+
delay(50);
130+
if ((millis() - startTime) > 3000) {
131+
// If key pressed for more than 3 secs, factory reset Zigbee and reboot
132+
Serial.println("Resetting Zigbee to factory and rebooting in 1s");
133+
delay(1000);
134+
Zigbee.factoryReset();
135+
}
136+
}
137+
// force report of illuminance when button is pressed
138+
zbIlluminanceSensor.report();
139+
}
140+
delay(100);
141+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"fqbn_append": "PartitionScheme=zigbee,ZigbeeMode=ed",
3+
"requires": [
4+
"CONFIG_SOC_IEEE802154_SUPPORTED=y",
5+
"CONFIG_ZB_ENABLED=y"
6+
]
7+
}

Diff for: libraries/Zigbee/keywords.txt

+4
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ ZigbeeGateway KEYWORD1
2929
ZigbeeRangeExtender KEYWORD1
3030
ZigbeeVibrationSensor KEYWORD1
3131
ZigbeeWindowCovering KEYWORD1
32+
ZigbeeIlluminanceSensor KEYWORD1
3233

3334
# Other
3435
zigbee_role_t KEYWORD1
@@ -123,6 +124,9 @@ setHumidity KEYWORD2
123124
setHumidityReporting KEYWORD2
124125
reportHumidity KEYWORD2
125126

127+
# ZigbeeIlluminanceSensor
128+
setIlluminance KEYWORD2
129+
126130
# ZigbeeFlowSensor
127131
setFlow KEYWORD2
128132

Diff for: libraries/Zigbee/src/Zigbee.h

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#include "ep/ZigbeeAnalog.h"
1919
#include "ep/ZigbeeFlowSensor.h"
2020
#include "ep/ZigbeeOccupancySensor.h"
21+
#include "ep/ZigbeeIlluminanceSensor.h"
2122
#include "ep/ZigbeeCarbonDioxideSensor.h"
2223
#include "ep/ZigbeeContactSwitch.h"
2324
#include "ep/ZigbeeDoorWindowHandle.h"

Diff for: libraries/Zigbee/src/ep/ZigbeeIlluminanceSensor.cpp

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#include "ZigbeeIlluminanceSensor.h"
2+
#if CONFIG_ZB_ENABLED
3+
4+
ZigbeeIlluminanceSensor::ZigbeeIlluminanceSensor(uint8_t endpoint) : ZigbeeEP(endpoint) {
5+
_device_id = ESP_ZB_HA_LIGHT_SENSOR_DEVICE_ID;
6+
7+
esp_zb_light_sensor_cfg_t light_sensor_cfg = ZIGBEE_DEFAULT_ILLUMINANCE_SENSOR_CONFIG();
8+
_cluster_list = esp_zb_light_sensor_clusters_create(&light_sensor_cfg);
9+
10+
_ep_config = {.endpoint = _endpoint, .app_profile_id = ESP_ZB_AF_HA_PROFILE_ID, .app_device_id = ESP_ZB_HA_LIGHT_SENSOR_DEVICE_ID, .app_device_version = 0};
11+
}
12+
13+
void ZigbeeIlluminanceSensor::setMinMaxValue(uint16_t min, uint16_t max) {
14+
esp_zb_attribute_list_t *light_measure_cluster =
15+
esp_zb_cluster_list_get_cluster(_cluster_list, ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE);
16+
esp_zb_cluster_update_attr(light_measure_cluster, ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MIN_MEASURED_VALUE_ID, (void *)&min);
17+
esp_zb_cluster_update_attr(light_measure_cluster, ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MAX_MEASURED_VALUE_ID, (void *)&max);
18+
}
19+
20+
void ZigbeeIlluminanceSensor::setTolerance(uint16_t tolerance) {
21+
esp_zb_attribute_list_t *light_measure_cluster =
22+
esp_zb_cluster_list_get_cluster(_cluster_list, ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE);
23+
esp_zb_illuminance_meas_cluster_add_attr(light_measure_cluster, ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_TOLERANCE_ID, (void *)&tolerance);
24+
}
25+
26+
void ZigbeeIlluminanceSensor::setReporting(uint16_t min_interval, uint16_t max_interval, uint16_t delta) {
27+
esp_zb_zcl_reporting_info_t reporting_info;
28+
memset(&reporting_info, 0, sizeof(esp_zb_zcl_reporting_info_t));
29+
reporting_info.direction = ESP_ZB_ZCL_CMD_DIRECTION_TO_SRV;
30+
reporting_info.ep = _endpoint;
31+
reporting_info.cluster_id = ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT;
32+
reporting_info.cluster_role = ESP_ZB_ZCL_CLUSTER_SERVER_ROLE;
33+
reporting_info.attr_id = ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MEASURED_VALUE_ID;
34+
reporting_info.u.send_info.min_interval = min_interval;
35+
reporting_info.u.send_info.max_interval = max_interval;
36+
reporting_info.u.send_info.def_min_interval = min_interval;
37+
reporting_info.u.send_info.def_max_interval = max_interval;
38+
reporting_info.u.send_info.delta.u16 = delta;
39+
reporting_info.dst.profile_id = ESP_ZB_AF_HA_PROFILE_ID;
40+
reporting_info.manuf_code = ESP_ZB_ZCL_ATTR_NON_MANUFACTURER_SPECIFIC;
41+
esp_zb_lock_acquire(portMAX_DELAY);
42+
esp_zb_zcl_update_reporting_info(&reporting_info);
43+
esp_zb_lock_release();
44+
}
45+
46+
void ZigbeeIlluminanceSensor::setIlluminance(uint16_t illuminanceValue) {
47+
log_v("Updating Illuminance...");
48+
/* Update illuminance sensor measured illuminance */
49+
log_d("Setting Illuminance to %d", illuminanceValue);
50+
esp_zb_lock_acquire(portMAX_DELAY);
51+
esp_zb_zcl_set_attribute_val(
52+
_endpoint, ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE, ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MEASURED_VALUE_ID,
53+
&illuminanceValue, false
54+
);
55+
esp_zb_lock_release();
56+
}
57+
58+
void ZigbeeIlluminanceSensor::report() {
59+
/* Send report attributes command */
60+
esp_zb_zcl_report_attr_cmd_t report_attr_cmd;
61+
report_attr_cmd.address_mode = ESP_ZB_APS_ADDR_MODE_DST_ADDR_ENDP_NOT_PRESENT;
62+
report_attr_cmd.attributeID = ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MEASURED_VALUE_ID;
63+
report_attr_cmd.direction = ESP_ZB_ZCL_CMD_DIRECTION_TO_CLI;
64+
report_attr_cmd.clusterID = ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT;
65+
report_attr_cmd.zcl_basic_cmd.src_endpoint = _endpoint;
66+
report_attr_cmd.manuf_code = ESP_ZB_ZCL_ATTR_NON_MANUFACTURER_SPECIFIC;
67+
68+
esp_zb_lock_acquire(portMAX_DELAY);
69+
esp_zb_zcl_report_attr_cmd_req(&report_attr_cmd);
70+
esp_zb_lock_release();
71+
log_v("Illuminance report sent");
72+
}
73+
74+
#endif // CONFIG_ZB_ENABLED

Diff for: libraries/Zigbee/src/ep/ZigbeeIlluminanceSensor.h

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/* Class of Zigbee Illuminance sensor 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+
#define ZIGBEE_DEFAULT_ILLUMINANCE_SENSOR_CONFIG() \
13+
{ \
14+
.basic_cfg = \
15+
{ \
16+
.zcl_version = ESP_ZB_ZCL_BASIC_ZCL_VERSION_DEFAULT_VALUE, \
17+
.power_source = ESP_ZB_ZCL_BASIC_POWER_SOURCE_DEFAULT_VALUE, \
18+
}, \
19+
.identify_cfg = \
20+
{ \
21+
.identify_time = ESP_ZB_ZCL_IDENTIFY_IDENTIFY_TIME_DEFAULT_VALUE, \
22+
}, \
23+
.illuminance_cfg = { \
24+
.measured_value = ESP_ZB_ZCL_ILLUMINANCE_MEASUREMENT_LIGHT_SENSOR_TYPE_DEFAULT_VALUE, \
25+
.min_value = ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MIN_MEASURED_VALUE_MIN_VALUE, \
26+
.max_value = ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MAX_MEASURED_VALUE_MAX_VALUE, \
27+
}, \
28+
}
29+
30+
class ZigbeeIlluminanceSensor : public ZigbeeEP {
31+
public:
32+
ZigbeeIlluminanceSensor(uint8_t endpoint);
33+
~ZigbeeIlluminanceSensor() {}
34+
35+
// Set the illuminance value
36+
void setIlluminance(uint16_t value);
37+
38+
// Set the min and max value for the illuminance sensor
39+
void setMinMaxValue(uint16_t min, uint16_t max);
40+
41+
// Set the tolerance value for the illuminance sensor
42+
void setTolerance(uint16_t tolerance);
43+
44+
// Set the reporting interval for illuminance measurement in seconds and delta
45+
void setReporting(uint16_t min_interval, uint16_t max_interval, uint16_t delta);
46+
47+
// Report the illuminance value
48+
void report();
49+
};
50+
51+
#endif // CONFIG_ZB_ENABLED

0 commit comments

Comments
 (0)