Compare commits

..

1 Commits

Author SHA1 Message Date
53fca9f94f Merge pull request 'Finnished example program' (#1) from main into master
Reviewed-on: #1
2025-08-13 15:12:59 -04:00
8 changed files with 193 additions and 250 deletions

0
idf.py
View File

View File

@@ -1,3 +1,3 @@
idf_component_register(SRCS "simple_zb_light.c"
idf_component_register(SRCS "main.c"
INCLUDE_DIRS "."
REQUIRES nvs_flash driver espressif__esp-zigbee-lib espressif__esp-zboss-lib)

172
main/main.c Normal file
View File

@@ -0,0 +1,172 @@
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_zigbee_core.h"
#include "ha/esp_zigbee_ha_standard.h"
#include "ha/esp_zigbee_ha_standard.h"
#define LED_PIN GPIO_NUM_2
static const char *TAG = "SIMPLE_LIGHT_CONTROLLER";
static bool led_is_on = false;
static esp_err_t zb_action_handler(esp_zb_core_action_callback_id_t callback_id, const void *message);
static void led_task(void *pvParameters) {
gpio_reset_pin(LED_PIN); // Reset pin to default state (clean slate)
gpio_set_direction(LED_PIN, GPIO_MODE_OUTPUT); // Set pin as output (can send voltage)
while(1) {
gpio_set_level(LED_PIN, led_is_on ? 1 : 0); //set whether the light is on or off
vTaskDelay(100 / portTICK_PERIOD_MS); // delay by 100 ms
}
}
static void zigbee_task(void *pvParameter) {
ESP_LOGI(TAG, "Starting Zigbee... "); // print log
esp_zb_cfg_t zb_nwk_cfg = { // default end device config
.esp_zb_role = ESP_ZB_DEVICE_TYPE_ED,
.install_code_policy = true,
.nwk_cfg.zed_cfg = {
.ed_timeout = ESP_ZB_ED_AGING_TIMEOUT_64MIN,
.keep_alive = 60000, //respond to coordinator every 60 seconds to let it know its alive.
}
};
esp_zb_init(&zb_nwk_cfg); // Initialize Zigbee stack with config
// Create a light device with default settings
esp_zb_on_off_light_cfg_t light_cfg = ESP_ZB_DEFAULT_ON_OFF_LIGHT_CONFIG();
esp_zb_ep_list_t *ep_list = esp_zb_on_off_light_ep_create(1, &light_cfg); //TODO: endpoint_ID set to 1 for testing
esp_zb_device_register(ep_list); // Tell Zigbee stack about our device
esp_zb_core_action_handler_register(zb_action_handler); // Set function to handle commands
ESP_ERROR_CHECK(esp_zb_start(false)); // Start Zigbee (false = don't erase network info)
esp_zb_stack_main_loop(); // Run Zigbee forever (never returns)
}
// ========== HANDLE COMMANDS FROM HOME ASSISTANT ==========
// This function is called when Home Assistant sends commands to our device
static esp_err_t zb_action_handler(esp_zb_core_action_callback_id_t callback_id, const void *message)
{
// callback_id = what type of action/command this is
// message = pointer to the actual command data
// Check if this is a "set attribute value" command (like turn on/off)
if (callback_id == ESP_ZB_CORE_SET_ATTR_VALUE_CB_ID) {
// Cast the generic message pointer to the specific message type we expect
const esp_zb_zcl_set_attr_value_message_t *msg =
(esp_zb_zcl_set_attr_value_message_t *)message;
// Check if this command is for the on/off cluster AND the on/off attribute
if (msg->info.cluster == ESP_ZB_ZCL_CLUSTER_ID_ON_OFF && // Is this an on/off command?
msg->attribute.id == ESP_ZB_ZCL_ATTR_ON_OFF_ON_OFF_ID) { // Is this the on/off attribute?
// Extract the boolean value from the command
led_is_on = *(bool *)msg->attribute.data.value; // true = on, false = off
// Print what happened to serial monitor
ESP_LOGI(TAG, "Home Assistant says: LED %s", led_is_on ? "ON" : "OFF");
}
}
return ESP_OK; // Return success status
}
// Call this if device won't join network - forces it back to discoverable state
void force_factory_reset(void)
{
ESP_LOGI(TAG, "Forcing factory reset - device will be discoverable again");
esp_zb_factory_reset(); // Erases all network info
esp_restart(); // Restart device
}
// This function is called when Zigbee network events happen (joining, errors, etc.)
void esp_zb_app_signal_handler(esp_zb_app_signal_t *signal_struct)
{
// Extract the signal type from the structure
uint32_t *p_sg_p = signal_struct->p_app_signal; // Pointer to signal data
esp_zb_app_signal_type_t sig_type = *p_sg_p; // Dereference to get signal type
// Handle different types of network events
switch (sig_type) {
// === ZIGBEE STACK INITIALIZED ===
case ESP_ZB_ZDO_SIGNAL_SKIP_STARTUP:
ESP_LOGI(TAG, "Zigbee stack initialized");
// Start the commissioning process (joining a network)
// BDB = Base Device Behavior (standard way devices join networks)
esp_zb_bdb_start_top_level_commissioning(ESP_ZB_BDB_MODE_INITIALIZATION);
break;
// === DEVICE STARTED FOR FIRST TIME ===
case ESP_ZB_BDB_SIGNAL_DEVICE_FIRST_START:
ESP_LOGI(TAG, "Device started - looking for network to join");
// Start network steering = look for open Zigbee networks to join
esp_zb_bdb_start_top_level_commissioning(ESP_ZB_BDB_MODE_NETWORK_STEERING);
break;
// === NETWORK JOINING ATTEMPT RESULT ===
case ESP_ZB_BDB_SIGNAL_STEERING:
// Check if joining was successful
if (signal_struct->esp_err_status == ESP_OK) {
ESP_LOGI(TAG, "Successfully joined Zigbee network!");
ESP_LOGI(TAG, "Your device should now appear in Home Assistant");
} else {
ESP_LOGI(TAG, "Failed to join network, retrying in 5 seconds...");
// Retry joining after 5 second delay
esp_zb_scheduler_alarm((esp_zb_callback_t)esp_zb_bdb_start_top_level_commissioning,
ESP_ZB_BDB_MODE_NETWORK_STEERING, 5000);
}
break;
// === ANY OTHER ZIGBEE EVENT ===
default:
ESP_LOGI(TAG, "Other Zigbee event: %d", sig_type);
break;
}
}
void app_main(void)
{
// Print startup banner to serial monitor
ESP_LOGI(TAG, "=== Simple Light controller for Zigbee & HA ===");
// NVS = Non-Volatile Storage
// Saves Zigbee network info so device remembers which network it joined
ESP_ERROR_CHECK(nvs_flash_init()); // ESP_ERROR_CHECK = crash if this fails
esp_zb_platform_config_t config = {
.radio_config = ESP_ZB_DEFAULT_RADIO_CONFIG(), // Set up 2.4GHz radio settings
.host_config = ESP_ZB_DEFAULT_HOST_CONFIG(), // Set up processor settings
};
ESP_ERROR_CHECK(esp_zb_platform_config(&config)); // Apply the configuration to board
// === CREATE TASK 1: LED CONTROL ===
// xTaskCreate = create a new task (mini-program that runs independently)
xTaskCreate(led_task, // Function to run (defined above)
"LED_Task", // Name for debugging (shows in task monitor)
2048, // Stack size in bytes (how much memory task can use)
NULL, // Parameters to pass to task (we don't need any)
1, // Priority 1-25 (1=lowest, 25=highest priority)
NULL); // Task handle (we don't need to control task later)
// === CREATE TASK 2: ZIGBEE COMMUNICATION ===
xTaskCreate(zigbee_task, // Function to run (defined above)
"Zigbee_Task", // Name for debugging
4096, // Larger stack - Zigbee needs more memory
NULL, // No parameters
5, // Higher priority - network communication is important
NULL); // No handle needed
ESP_LOGI(TAG, "Both tasks started - LED and Zigbee running independently!");
}

View File

@@ -1,175 +0,0 @@
#include <stdio.h>
#include "freertos/FreeRTOS.h" // FreeRTOS kernel for task management
#include "freertos/task.h" // FreeRTOS task handling functions
#include "driver/gpio.h" // GPIO driver for controlling pins like LEDs
#include "esp_log.h" // ESP logging library for debug/info/error messages
#include "nvs_flash.h" // Non-volatile storage for persistent data
#include "simple_zb_light.h" // Custom header with Zigbee configs
#define LED_PIN GPIO_NUM_2
static const char *TAG = "SIMPLE_LIGHT_CONTROLLER";
static bool led_is_on = false;
static esp_err_t zb_action_handler(esp_zb_core_action_callback_id_t callback_id, const void *message);
// Helper function for scheduler callback
static void commissioning_restart_cb(uint8_t param) {
esp_zb_bdb_start_top_level_commissioning(ESP_ZB_BDB_MODE_NETWORK_STEERING);
}
static void led_task(void *pvParameters) {
gpio_reset_pin(LED_PIN); // Reset pin to default state (clean slate)
gpio_set_direction(LED_PIN, GPIO_MODE_OUTPUT); // Set pin as output (can send voltage)
// Track previous state to avoid redundant GPIO writes
bool prev_state = !led_is_on;
while (1) {
// Update GPIO only on state change for efficiency
if (led_is_on != prev_state) {
gpio_set_level(LED_PIN, led_is_on ? 1 : 0); //set whether the light is on or off
// Log state changes for debugging
ESP_LOGI(TAG, "LED state updated to %s", led_is_on ? "ON" : "OFF");
prev_state = led_is_on;
}
// Increased delay to 500ms for lower CPU usage
vTaskDelay(500 / portTICK_PERIOD_MS); // delay by 500 ms
}
}
static void zigbee_task(void *pvParameter) {
ESP_LOGI(TAG, "Starting Zigbee... "); // print log
// Simplified config using ESP_ZB_ZED_CONFIG() for standard end device settings
esp_zb_cfg_t zb_nwk_cfg = ESP_ZB_ZED_CONFIG();
esp_zb_init(&zb_nwk_cfg); // Initialize Zigbee stack with config
// Create a light device with default settings
esp_zb_on_off_light_cfg_t light_cfg = ESP_ZB_DEFAULT_ON_OFF_LIGHT_CONFIG();
// Use HA_ESP_LIGHT_ENDPOINT (10) for standard Home Automation compatibility
esp_zb_ep_list_t *ep_list = esp_zb_on_off_light_ep_create(1, &light_cfg);
esp_zb_device_register(ep_list); // Tell Zigbee stack about our device
esp_zb_core_action_handler_register(zb_action_handler); // Set function to handle commands
// Set channel mask to scan all Zigbee channels (11-26)
esp_zb_set_primary_network_channel_set(ESP_ZB_PRIMARY_CHANNEL_MASK);
ESP_ERROR_CHECK(esp_zb_start(false)); // Start Zigbee (false = don't erase network info)
esp_zb_stack_main_loop(); // Run Zigbee forever (never returns)
}
// ========== HANDLE COMMANDS FROM HOME ASSISTANT ==========
// This function is called when Home Assistant sends commands to our device
static esp_err_t zb_action_handler(esp_zb_core_action_callback_id_t callback_id, const void *message)
{
// callback_id = what type of action/command this is
// message = pointer to the actual command data
// Check if this is a "set attribute value" command (like turn on/off)
if (callback_id == ESP_ZB_CORE_SET_ATTR_VALUE_CB_ID) {
// Cast the generic message pointer to the specific message type we expect
const esp_zb_zcl_set_attr_value_message_t *msg =
(esp_zb_zcl_set_attr_value_message_t *)message;
// Check if this command is for the on/off cluster AND the on/off attribute
if (msg->info.cluster == ESP_ZB_ZCL_CLUSTER_ID_ON_OFF && // Is this an on/off command?
msg->attribute.id == ESP_ZB_ZCL_ATTR_ON_OFF_ON_OFF_ID) { // Is this the on/off attribute?
// Extract the boolean value from the command
led_is_on = *(bool *)msg->attribute.data.value; // true = on, false = off
// Log the command received
ESP_LOGI(TAG, "Zigbee command received: LED %s", led_is_on ? "ON" : "OFF");
}
}
return ESP_OK; // Return success status
}
// This function is called when Zigbee network events happen (joining, errors, etc.)
void esp_zb_app_signal_handler(esp_zb_app_signal_t *signal_struct)
{
// Extract the signal type from the structure
uint32_t *p_sg_p = signal_struct->p_app_signal; // Pointer to signal data
esp_zb_app_signal_type_t sig_type = *p_sg_p; // Dereference to get signal type
// Extract error status for better logging
esp_err_t err_status = signal_struct->esp_err_status;
// Handle different types of network events
switch (sig_type) {
// === ZIGBEE STACK INITIALIZED ===
case ESP_ZB_ZDO_SIGNAL_SKIP_STARTUP:
ESP_LOGI(TAG, "Zigbee stack initialized");
// Start the commissioning process (joining a network)
// BDB = Base Device Behavior (standard way devices join networks)
esp_zb_bdb_start_top_level_commissioning(ESP_ZB_BDB_MODE_INITIALIZATION);
break;
// === DEVICE STARTED FOR FIRST TIME ===
// Handle both first start and reboot consistently
case ESP_ZB_BDB_SIGNAL_DEVICE_FIRST_START:
case ESP_ZB_BDB_SIGNAL_DEVICE_REBOOT:
if (err_status == ESP_OK) {
// Log factory reset status
ESP_LOGI(TAG, "Device started in %s factory-reset mode", esp_zb_bdb_is_factory_new() ? "" : "non");
if (esp_zb_bdb_is_factory_new()) {
ESP_LOGI(TAG, "Start network steering");
esp_zb_bdb_start_top_level_commissioning(ESP_ZB_BDB_MODE_NETWORK_STEERING);
} else {
ESP_LOGI(TAG, "Device rebooted");
}
} else {
// Log initialization errors
ESP_LOGW(TAG, "Failed to initialize Zigbee stack (status: %s)", esp_err_to_name(err_status));
}
break;
// === NETWORK JOINING ATTEMPT RESULT ===
case ESP_ZB_BDB_SIGNAL_STEERING:
if (err_status == ESP_OK) {
// Log detailed network info on successful join
esp_zb_ieee_addr_t extended_pan_id;
esp_zb_get_extended_pan_id(extended_pan_id);
ESP_LOGI(TAG, "Joined network successfully (Extended PAN ID: %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x, PAN ID: 0x%04hx, Channel:%d)",
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());
} else {
// Reduced retry delay to 1s for faster recovery
ESP_LOGW(TAG, "Failed to join network (status: %s), retrying in 1s...", esp_err_to_name(err_status));
esp_zb_scheduler_alarm((esp_zb_callback_t)commissioning_restart_cb, 0, 1000);
}
break;
// === ANY OTHER ZIGBEE EVENT ===
default:
// Log other events with error status
ESP_LOGI(TAG, "Other Zigbee event: %d (status: %s)", sig_type, esp_err_to_name(err_status));
break;
}
}
void app_main(void) {
ESP_LOGI(TAG, "=== Simple Light Controller for Zigbee & Zigbee2MQTT ===");
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
// Initialize Zigbee platform configuration
esp_zb_platform_config_t config = {
.radio_config = ESP_ZB_DEFAULT_RADIO_CONFIG(), // Use macro from simple_zb_light.h
.host_config = ESP_ZB_DEFAULT_HOST_CONFIG(), // Use macro from simple_zb_light.h
};
ESP_ERROR_CHECK(esp_zb_platform_config(&config));
xTaskCreate(led_task, "LED_Task", 2048, NULL, 1, NULL);
xTaskCreate(zigbee_task, "Zigbee_Task", 4096, NULL, 5, NULL);
ESP_LOGI(TAG, "Both tasks started - LED and Zigbee running independently!");
}

View File

@@ -1,35 +0,0 @@
#ifndef SIMPLE_ZB_LIGHT_H
#define SIMPLE_ZB_LIGHT_H
#include "sdkconfig.h"
#include "esp_zigbee_core.h"
#include "esp_zigbee_type.h"
#include "ha/esp_zigbee_ha_standard.h"
// Zigbee configuration for End Device
#define ESP_ZB_ZED_CONFIG() \
{ \
.esp_zb_role = ESP_ZB_DEVICE_TYPE_ED, \
.install_code_policy = true, \
.nwk_cfg.zed_cfg = { \
.ed_timeout = ESP_ZB_ED_AGING_TIMEOUT_64MIN, \
.keep_alive = 60000, \
}, \
}
// Radio configuration for ESP32-C6 native Zigbee
#define ESP_ZB_DEFAULT_RADIO_CONFIG() \
{ \
.radio_mode = ZB_RADIO_MODE_NATIVE, \
}
// Host configuration (no host connection for single-chip mode)
#define ESP_ZB_DEFAULT_HOST_CONFIG() \
{ \
.host_connection_mode = ZB_HOST_CONNECTION_MODE_NONE, \
}
// Channel mask to scan all Zigbee channels (11-26)
#define ESP_ZB_PRIMARY_CHANNEL_MASK ESP_ZB_TRANSCEIVER_ALL_CHANNELS_MASK
#endif // SIMPLE_ZB_LIGHT_H

View File

@@ -1,7 +0,0 @@
# Name, Type, SubType, Offset, Size, Flags
# Note: if you have increased the bootloader size, make sure to update the offsets to avoid overlap
nvs, data, nvs, 0x9000, 24K,
phy_init, data, phy, 0xf000, 4K,
zb_storage, data, fat, 0x10000, 16K,
zb_fct, data, fat, 0x14000, 1K,
factory, app, factory, 0x20000, 1M,
1 # Name, Type, SubType, Offset, Size, Flags
2 # Note: if you have increased the bootloader size, make sure to update the offsets to avoid overlap
3 nvs, data, nvs, 0x9000, 24K,
4 phy_init, data, phy, 0xf000, 4K,
5 zb_storage, data, fat, 0x10000, 16K,
6 zb_fct, data, fat, 0x14000, 1K,
7 factory, app, factory, 0x20000, 1M,

View File

@@ -615,13 +615,13 @@ CONFIG_ESPTOOLPY_MONITOR_BAUD=115200
#
# Partition Table
#
# CONFIG_PARTITION_TABLE_SINGLE_APP is not set
CONFIG_PARTITION_TABLE_SINGLE_APP=y
# CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set
# CONFIG_PARTITION_TABLE_TWO_OTA is not set
# CONFIG_PARTITION_TABLE_TWO_OTA_LARGE is not set
CONFIG_PARTITION_TABLE_CUSTOM=y
# CONFIG_PARTITION_TABLE_CUSTOM is not set
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions_singleapp.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x8000
CONFIG_PARTITION_TABLE_MD5=y
# end of Partition Table
@@ -1818,6 +1818,7 @@ CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y
CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y
CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384
CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096
# CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set
# CONFIG_MBEDTLS_DEBUG is not set
#
@@ -1829,13 +1830,6 @@ CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096
# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set
CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y
CONFIG_MBEDTLS_PKCS7_C=y
#
# DTLS-based configurations
#
# CONFIG_MBEDTLS_SSL_DTLS_CONNECTION_ID is not set
# CONFIG_MBEDTLS_SSL_DTLS_SRTP is not set
# end of DTLS-based configurations
# end of mbedTLS v3.x related
#
@@ -1852,9 +1846,15 @@ CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200
# CONFIG_MBEDTLS_ECP_RESTARTABLE is not set
CONFIG_MBEDTLS_CMAC_C=y
# CONFIG_MBEDTLS_HARDWARE_AES is not set
# CONFIG_MBEDTLS_HARDWARE_MPI is not set
# CONFIG_MBEDTLS_HARDWARE_SHA is not set
CONFIG_MBEDTLS_HARDWARE_AES=y
CONFIG_MBEDTLS_AES_USE_INTERRUPT=y
CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0
CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y
CONFIG_MBEDTLS_HARDWARE_MPI=y
CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI=y
CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y
CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0
CONFIG_MBEDTLS_HARDWARE_SHA=y
CONFIG_MBEDTLS_HARDWARE_ECC=y
CONFIG_MBEDTLS_ECC_OTHER_CURVES_SOFT_FALLBACK=y
CONFIG_MBEDTLS_ROM_MD5=y
@@ -1890,7 +1890,7 @@ CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y
CONFIG_MBEDTLS_SSL_RENEGOTIATION=y
CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y
# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set
CONFIG_MBEDTLS_SSL_PROTO_DTLS=y
# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set
CONFIG_MBEDTLS_SSL_ALPN=y
CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y
CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y
@@ -2206,8 +2206,8 @@ CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y
# Zigbee
#
CONFIG_ZB_ENABLED=y
# CONFIG_ZB_ZCZR is not set
CONFIG_ZB_ZED=y
CONFIG_ZB_ZCZR=y
# CONFIG_ZB_ZED is not set
# CONFIG_ZB_ZGPD is not set
CONFIG_ZB_RADIO_NATIVE=y
# CONFIG_ZB_RADIO_SPINEL_UART is not set
@@ -2215,6 +2215,7 @@ CONFIG_ZB_RADIO_NATIVE=y
#
# Zigbee Example
#
CONFIG_ZB_GP_ENABLED=y
# end of Zigbee Example
# CONFIG_ZB_DEBUG_MODE is not set

View File

@@ -2205,20 +2205,7 @@ CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y
#
# Zigbee
#
CONFIG_ZB_ENABLED=y
CONFIG_ZB_ZCZR=y
# CONFIG_ZB_ZED is not set
# CONFIG_ZB_ZGPD is not set
CONFIG_ZB_RADIO_NATIVE=y
# CONFIG_ZB_RADIO_SPINEL_UART is not set
#
# Zigbee Example
#
CONFIG_ZB_GP_ENABLED=y
# end of Zigbee Example
# CONFIG_ZB_DEBUG_MODE is not set
# CONFIG_ZB_ENABLED is not set
# end of Zigbee
# end of Component config