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): Add Illuminance sensor endpoint #11171

Merged
merged 14 commits into from
Mar 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ set(ARDUINO_LIBRARY_Zigbee_SRCS
libraries/Zigbee/src/ep/ZigbeeRangeExtender.cpp
libraries/Zigbee/src/ep/ZigbeeGateway.cpp
libraries/Zigbee/src/ep/ZigbeeWindSpeedSensor.cpp
libraries/Zigbee/src/ep/ZigbeeIlluminanceSensor.cpp
)

set(ARDUINO_LIBRARY_BLE_SRCS
Expand Down
78 changes: 78 additions & 0 deletions libraries/Zigbee/examples/Zigbee_Illuminance_Sensor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Arduino-ESP32 Zigbee Illuminance Sensor Example

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.

# Supported Targets

Currently, this example supports the following targets.

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

## Illuminance Sensor Functions

1. Initialize a Zigbee illuminance sensor.
2. Measure illuminance value.
3. Report the measured value to the Zigbee network.

## Hardware Required

* ESP32-H2 or ESP32-C6 development board
* A USB cable for power supply and programming
* Some kind of light sensor, such as a photoresistor

### Configure the Project

In this example the raw analog value of a light sensor is used to calculate illuminance.
Alter the calculation according to your use case and calibrate it to receive correct lux values.
Set the illuminance sensor GPIO by changing the `illuminance_sensor_pin` variable to the pin to the pin to which your sensor is connected.
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).

#### 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`
* Enable USB CDC to be able to use the serial monitor: `Tools -> USB CDC On Boot: Enabled`
* 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 that you are using a good quality USB cable with data lines 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,141 @@
// Copyright 2025 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 illuminance sensor.
*
* The example demonstrates how to use Zigbee library to create a end device illuminance sensor.
* The illuminance sensor is a Zigbee end device, which is controlled by a Zigbee coordinator.
*
* 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 MikaFromTheRoof (https://github.com/MikaFromTheRoof)
*/

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

#include "Zigbee.h"

#define ZIGBEE_ILLUMINANCE_SENSOR_ENDPOINT 9
uint8_t button = BOOT_PIN;
uint8_t illuminance_sensor_pin = 6; // Insert the analog pin to which the sensor (e.g. photoresistor) is connected

ZigbeeIlluminanceSensor zbIlluminanceSensor = ZigbeeIlluminanceSensor(ZIGBEE_ILLUMINANCE_SENSOR_ENDPOINT);

/********************* Illuminance sensor **************************/
static void illuminance_sensor_value_update(void *arg) {
for (;;) {
// read the raw analog value from the sensor
int lsens_analog_raw = analogRead(illuminance_sensor_pin);
Serial.printf("[Illuminance Sensor] raw analog value: %d\r\n", lsens_analog_raw);

// conversion into zigbee raw illuminance value (typically between 0 in darkness and 50000 in direct sunlight)
// depends on the value range of the raw analog sensor values and will need calibration for correct lux values
// for demonstration purpose map the 12-bit ADC value (0-4095) to Zigbee illuminance range (0-50000)
int lsens_illuminance_raw = map(lsens_analog_raw, 0, 4095, 0, 50000);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would it be nicer to set the 50,000 limit as a #define ... - it is used latter in the code.

Serial.printf("[Illuminance Sensor] raw illuminance value: %d\r\n", lsens_illuminance_raw);

// according to zigbee documentation the formular 10^(lsens_illuminance_raw/10000)-1 can be used to calculate lux value from raw illuminance value
// Note: Zigbee2MQTT seems to be using the formular 10^(lsens_illuminance_raw/10000) instead (without -1)
int lsens_illuminance_lux = round(pow(10, (lsens_illuminance_raw / 10000.0)) - 1);
Serial.printf("[Illuminance Sensor] lux value: %d lux\r\n", lsens_illuminance_lux);

// Update illuminance in illuminance sensor EP
zbIlluminanceSensor.setIlluminance(lsens_illuminance_raw); // use raw illuminance here!

delay(1000); // reduce delay (in ms), if you want your device to react more quickly to changes in illuminance
}
}

/********************* Arduino functions **************************/
void setup() {
Serial.begin(115200);

// Optional: configure analog input
analogSetAttenuation(ADC_11db); // set analog to digital converter (ADC) attenuation to 11 dB (up to ~3.3V input)
analogReadResolution(12); // set analog read resolution to 12 bits (value range from 0 to 4095), 12 is default

// Init button for factory reset
pinMode(button, INPUT_PULLUP);

// Optional: Set Zigbee device name and model
zbIlluminanceSensor.setManufacturerAndModel("Espressif", "ZigbeeIlluminanceSensor");

// Optional: Set power source (choose between ZB_POWER_SOURCE_MAINS and ZB_POWER_SOURCE_BATTERY), defaults to unknown
zbIlluminanceSensor.setPowerSource(ZB_POWER_SOURCE_MAINS);

// Set minimum and maximum for raw illuminance value (0 min and 50000 max equals to 0 lux - 100,000 lux)
zbIlluminanceSensor.setMinMaxValue(0, 50000);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would it be nicer to set the 50,000 limit as a #define ... ?


// Optional: Set tolerance for raw illuminance value
zbIlluminanceSensor.setTolerance(1);

// Add endpoint to Zigbee Core
Serial.println("Adding Zigbee illuminance sensor endpoint to Zigbee Core");
Zigbee.addEndpoint(&zbIlluminanceSensor);

Serial.println("Starting Zigbee...");
// When all EPs are registered, start Zigbee in End Device mode
if (!Zigbee.begin()) {
Serial.println("Zigbee failed to start!");
Serial.println("Rebooting...");
ESP.restart();
} else {
Serial.println("Zigbee started successfully!");
}
Serial.println("Connecting to network");
while (!Zigbee.connected()) {
Serial.print(".");
delay(100);
}
Serial.println();

// Start illuminance sensor reading task
xTaskCreate(illuminance_sensor_value_update, "illuminance_sensor_update", 2048, NULL, 10, NULL);

// Set reporting schedule for illuminance value measurement in seconds, must be called after Zigbee.begin()
// min_interval and max_interval in seconds, delta
// if min = 1 and max = 0, delta = 1000, reporting is sent when raw illuminance value changes by 1000, but at most once per second
// if min = 0 and max = 10, delta = 1000, reporting is sent every 10 seconds or if raw illuminance value changes by 1000
// if min = 0, max = 10 and delta = 0, reporting is sent every 10 seconds regardless of illuminance change
// Note: On pairing with Zigbee Home Automation or Zigbee2MQTT the reporting schedule will most likely be overwritten with their default settings
zbIlluminanceSensor.setReporting(1, 0, 1000);
}

/********************* Main loop **************************/
void loop() {
// Checking button for factory reset
if (digitalRead(button) == LOW) { // Push button pressed
// Key debounce handling
delay(100);
int startTime = millis();
while (digitalRead(button) == LOW) {
delay(50);
if ((millis() - startTime) > 3000) {
// If key pressed for more than 3 secs, factory reset Zigbee and reboot
Serial.println("Resetting Zigbee to factory and rebooting in 1s");
delay(1000);
Zigbee.factoryReset();
}
}
// force report of illuminance when button is pressed
zbIlluminanceSensor.report();
}
delay(100);
}
7 changes: 7 additions & 0 deletions libraries/Zigbee/examples/Zigbee_Illuminance_Sensor/ci.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"fqbn_append": "PartitionScheme=zigbee,ZigbeeMode=ed",
"requires": [
"CONFIG_SOC_IEEE802154_SUPPORTED=y",
"CONFIG_ZB_ENABLED=y"
]
}
4 changes: 4 additions & 0 deletions libraries/Zigbee/keywords.txt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ ZigbeeGateway KEYWORD1
ZigbeeRangeExtender KEYWORD1
ZigbeeVibrationSensor KEYWORD1
ZigbeeWindowCovering KEYWORD1
ZigbeeIlluminanceSensor KEYWORD1

# Other
zigbee_role_t KEYWORD1
Expand Down Expand Up @@ -123,6 +124,9 @@ setHumidity KEYWORD2
setHumidityReporting KEYWORD2
reportHumidity KEYWORD2

# ZigbeeIlluminanceSensor
setIlluminance KEYWORD2

# ZigbeeFlowSensor
setFlow KEYWORD2

Expand Down
1 change: 1 addition & 0 deletions libraries/Zigbee/src/Zigbee.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include "ep/ZigbeeAnalog.h"
#include "ep/ZigbeeFlowSensor.h"
#include "ep/ZigbeeOccupancySensor.h"
#include "ep/ZigbeeIlluminanceSensor.h"
#include "ep/ZigbeeCarbonDioxideSensor.h"
#include "ep/ZigbeeContactSwitch.h"
#include "ep/ZigbeeDoorWindowHandle.h"
Expand Down
74 changes: 74 additions & 0 deletions libraries/Zigbee/src/ep/ZigbeeIlluminanceSensor.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#include "ZigbeeIlluminanceSensor.h"
#if CONFIG_ZB_ENABLED

ZigbeeIlluminanceSensor::ZigbeeIlluminanceSensor(uint8_t endpoint) : ZigbeeEP(endpoint) {
_device_id = ESP_ZB_HA_LIGHT_SENSOR_DEVICE_ID;

esp_zb_light_sensor_cfg_t light_sensor_cfg = ZIGBEE_DEFAULT_ILLUMINANCE_SENSOR_CONFIG();
_cluster_list = esp_zb_light_sensor_clusters_create(&light_sensor_cfg);

_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};
}

void ZigbeeIlluminanceSensor::setMinMaxValue(uint16_t min, uint16_t max) {
esp_zb_attribute_list_t *light_measure_cluster =
esp_zb_cluster_list_get_cluster(_cluster_list, ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE);
esp_zb_cluster_update_attr(light_measure_cluster, ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MIN_MEASURED_VALUE_ID, (void *)&min);
esp_zb_cluster_update_attr(light_measure_cluster, ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MAX_MEASURED_VALUE_ID, (void *)&max);
}

void ZigbeeIlluminanceSensor::setTolerance(uint16_t tolerance) {
esp_zb_attribute_list_t *light_measure_cluster =
esp_zb_cluster_list_get_cluster(_cluster_list, ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE);
esp_zb_illuminance_meas_cluster_add_attr(light_measure_cluster, ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_TOLERANCE_ID, (void *)&tolerance);
}

void ZigbeeIlluminanceSensor::setReporting(uint16_t min_interval, uint16_t max_interval, uint16_t delta) {
esp_zb_zcl_reporting_info_t reporting_info;
memset(&reporting_info, 0, sizeof(esp_zb_zcl_reporting_info_t));
reporting_info.direction = ESP_ZB_ZCL_CMD_DIRECTION_TO_SRV;
reporting_info.ep = _endpoint;
reporting_info.cluster_id = ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT;
reporting_info.cluster_role = ESP_ZB_ZCL_CLUSTER_SERVER_ROLE;
reporting_info.attr_id = ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MEASURED_VALUE_ID;
reporting_info.u.send_info.min_interval = min_interval;
reporting_info.u.send_info.max_interval = max_interval;
reporting_info.u.send_info.def_min_interval = min_interval;
reporting_info.u.send_info.def_max_interval = max_interval;
reporting_info.u.send_info.delta.u16 = delta;
reporting_info.dst.profile_id = ESP_ZB_AF_HA_PROFILE_ID;
reporting_info.manuf_code = ESP_ZB_ZCL_ATTR_NON_MANUFACTURER_SPECIFIC;
esp_zb_lock_acquire(portMAX_DELAY);
esp_zb_zcl_update_reporting_info(&reporting_info);
esp_zb_lock_release();
}

void ZigbeeIlluminanceSensor::setIlluminance(uint16_t illuminanceValue) {
log_v("Updating Illuminance...");
/* Update illuminance sensor measured illuminance */
log_d("Setting Illuminance to %d", illuminanceValue);
esp_zb_lock_acquire(portMAX_DELAY);
esp_zb_zcl_set_attribute_val(
_endpoint, ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT, ESP_ZB_ZCL_CLUSTER_SERVER_ROLE, ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MEASURED_VALUE_ID,
&illuminanceValue, false
);
esp_zb_lock_release();
}

void ZigbeeIlluminanceSensor::report() {
/* 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_ILLUMINANCE_MEASUREMENT_MEASURED_VALUE_ID;
report_attr_cmd.direction = ESP_ZB_ZCL_CMD_DIRECTION_TO_CLI;
report_attr_cmd.clusterID = ESP_ZB_ZCL_CLUSTER_ID_ILLUMINANCE_MEASUREMENT;
report_attr_cmd.zcl_basic_cmd.src_endpoint = _endpoint;
report_attr_cmd.manuf_code = ESP_ZB_ZCL_ATTR_NON_MANUFACTURER_SPECIFIC;

esp_zb_lock_acquire(portMAX_DELAY);
esp_zb_zcl_report_attr_cmd_req(&report_attr_cmd);
esp_zb_lock_release();
log_v("Illuminance report sent");
}

#endif // CONFIG_ZB_ENABLED
51 changes: 51 additions & 0 deletions libraries/Zigbee/src/ep/ZigbeeIlluminanceSensor.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/* Class of Zigbee Illuminance sensor endpoint inherited from common EP class */

#pragma once

#include "soc/soc_caps.h"
#include "sdkconfig.h"
#if CONFIG_ZB_ENABLED

#include "ZigbeeEP.h"
#include "ha/esp_zigbee_ha_standard.h"

#define ZIGBEE_DEFAULT_ILLUMINANCE_SENSOR_CONFIG() \
{ \
.basic_cfg = \
{ \
.zcl_version = ESP_ZB_ZCL_BASIC_ZCL_VERSION_DEFAULT_VALUE, \
.power_source = ESP_ZB_ZCL_BASIC_POWER_SOURCE_DEFAULT_VALUE, \
}, \
.identify_cfg = \
{ \
.identify_time = ESP_ZB_ZCL_IDENTIFY_IDENTIFY_TIME_DEFAULT_VALUE, \
}, \
.illuminance_cfg = { \
.measured_value = ESP_ZB_ZCL_ILLUMINANCE_MEASUREMENT_LIGHT_SENSOR_TYPE_DEFAULT_VALUE, \
.min_value = ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MIN_MEASURED_VALUE_MIN_VALUE, \
.max_value = ESP_ZB_ZCL_ATTR_ILLUMINANCE_MEASUREMENT_MAX_MEASURED_VALUE_MAX_VALUE, \
}, \
}

class ZigbeeIlluminanceSensor : public ZigbeeEP {
public:
ZigbeeIlluminanceSensor(uint8_t endpoint);
~ZigbeeIlluminanceSensor() {}

// Set the illuminance value
void setIlluminance(uint16_t value);

// Set the min and max value for the illuminance sensor
void setMinMaxValue(uint16_t min, uint16_t max);

// Set the tolerance value for the illuminance sensor
void setTolerance(uint16_t tolerance);

// Set the reporting interval for illuminance measurement in seconds and delta
void setReporting(uint16_t min_interval, uint16_t max_interval, uint16_t delta);

// Report the illuminance value
void report();
};

#endif // CONFIG_ZB_ENABLED
Loading