From 13a15243cc92b1ce257559c043db49abfa9e0b76 Mon Sep 17 00:00:00 2001 From: WanqQixiang Date: Tue, 21 Jan 2025 19:08:13 +0800 Subject: [PATCH] esp_matter: create a data_model directory and move data_model related codes to it --- components/esp_matter/CMakeLists.txt | 66 +- components/esp_matter/Kconfig | 1 + .../{ => data_model}/esp_matter_attribute.cpp | 0 .../{ => data_model}/esp_matter_attribute.h | 2 +- .../esp_matter_attribute_bounds.cpp | 2 + .../esp_matter_attribute_bounds.h | 2 +- .../{ => data_model}/esp_matter_cluster.cpp | 3 - .../{ => data_model}/esp_matter_cluster.h | 3 +- .../{ => data_model}/esp_matter_command.cpp | 4 - .../{ => data_model}/esp_matter_command.h | 0 .../data_model/esp_matter_data_model.cpp | 1818 ++++++++++++++++ .../data_model/esp_matter_data_model.h | 958 +++++++++ .../esp_matter_data_model_utils.cpp | 118 ++ .../esp_matter_delegate_callbacks.cpp | 0 .../esp_matter_delegate_callbacks.h | 0 .../{ => data_model}/esp_matter_endpoint.cpp | 0 .../{ => data_model}/esp_matter_endpoint.h | 0 .../{ => data_model}/esp_matter_event.cpp | 0 .../{ => data_model}/esp_matter_event.h | 2 +- .../{ => data_model}/esp_matter_feature.cpp | 0 .../{ => data_model}/esp_matter_feature.h | 1 + .../private/esp_matter_data_model_priv.h | 43 + components/esp_matter/esp_matter.h | 88 +- .../esp_matter/esp_matter_attribute_utils.cpp | 84 +- .../esp_matter/esp_matter_attribute_utils.h | 16 + components/esp_matter/esp_matter_client.cpp | 12 +- components/esp_matter/esp_matter_client.h | 144 ++ components/esp_matter/esp_matter_core.cpp | 1868 +---------------- components/esp_matter/esp_matter_core.h | 1027 +-------- .../esp_matter_icd_configuration.cpp | 9 +- .../esp_matter/esp_matter_icd_configuration.h | 4 + components/esp_matter/esp_matter_identify.cpp | 49 +- components/esp_matter/esp_matter_identify.h | 1 + components/esp_matter/esp_matter_ota.cpp | 2 - components/esp_matter_bridge/CMakeLists.txt | 11 +- .../esp_matter_bridge/esp_matter_bridge.h | 2 +- .../esp_matter_controller/CMakeLists.txt | 3 +- .../esp_matter_controller_cluster_command.cpp | 1 - .../core/esp_matter_controller_client.cpp | 4 +- .../controller_data_model_provider.h | 130 ++ docs/Doxyfile | 15 +- .../api-reference/esp_matter_data_model.rst | 9 + docs/en/api-reference/index.rst | 1 + docs/en/developing.rst | 2 +- docs/en/faq.rst | 2 +- examples/common/app_bridge/CMakeLists.txt | 11 +- examples/controller/CMakeLists.txt | 18 +- examples/controller/main/app_main.cpp | 5 - examples/mfg_test_app/sdkconfig.defaults | 3 + examples/zap_light/main/app_main.cpp | 4 + 50 files changed, 3454 insertions(+), 3094 deletions(-) rename components/esp_matter/{ => data_model}/esp_matter_attribute.cpp (100%) rename components/esp_matter/{ => data_model}/esp_matter_attribute.h (99%) rename components/esp_matter/{ => data_model}/esp_matter_attribute_bounds.cpp (99%) rename components/esp_matter/{ => data_model}/esp_matter_attribute_bounds.h (97%) rename components/esp_matter/{ => data_model}/esp_matter_cluster.cpp (99%) rename components/esp_matter/{ => data_model}/esp_matter_cluster.h (99%) rename components/esp_matter/{ => data_model}/esp_matter_command.cpp (99%) rename components/esp_matter/{ => data_model}/esp_matter_command.h (100%) create mode 100644 components/esp_matter/data_model/esp_matter_data_model.cpp create mode 100644 components/esp_matter/data_model/esp_matter_data_model.h create mode 100644 components/esp_matter/data_model/esp_matter_data_model_utils.cpp rename components/esp_matter/{ => data_model}/esp_matter_delegate_callbacks.cpp (100%) rename components/esp_matter/{ => data_model}/esp_matter_delegate_callbacks.h (100%) rename components/esp_matter/{ => data_model}/esp_matter_endpoint.cpp (100%) rename components/esp_matter/{ => data_model}/esp_matter_endpoint.h (100%) rename components/esp_matter/{ => data_model}/esp_matter_event.cpp (100%) rename components/esp_matter/{ => data_model}/esp_matter_event.h (99%) rename components/esp_matter/{ => data_model}/esp_matter_feature.cpp (100%) rename components/esp_matter/{ => data_model}/esp_matter_feature.h (99%) create mode 100644 components/esp_matter/data_model/private/esp_matter_data_model_priv.h create mode 100644 components/esp_matter_controller/data_model_provider/controller_data_model_provider.h create mode 100644 docs/en/api-reference/esp_matter_data_model.rst diff --git a/components/esp_matter/CMakeLists.txt b/components/esp_matter/CMakeLists.txt index 047b81410..e3e01ff19 100644 --- a/components/esp_matter/CMakeLists.txt +++ b/components/esp_matter/CMakeLists.txt @@ -1,14 +1,6 @@ set(SRC_DIRS_LIST "." - "private" "utils" "${MATTER_SDK_PATH}/zzz_generated/app-common/app-common/zap-generated/attributes" - "${MATTER_SDK_PATH}/src/app/server" - "${MATTER_SDK_PATH}/src/app/util" - "${MATTER_SDK_PATH}/src/app/util/persistence" - "${MATTER_SDK_PATH}/src/app/reporting" - # TODO Use esp-matter data model and remove ember codes - "${MATTER_SDK_PATH}/src/data-model-providers/codegen" - "${MATTER_SDK_PATH}/src/app/server-cluster" ) set(INCLUDE_DIRS_LIST "." @@ -20,31 +12,43 @@ set(INCLUDE_DIRS_LIST "." # TODO: This file has compilation errors set(EXCLUDE_SRCS_LIST "${MATTER_SDK_PATH}/src/app/clusters/closure-control-server/closure-control-server.cpp") -if (CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) - include("utils/cluster_select/cluster_dir.cmake") - get_supported_cluster_dirs(SUPPORTED_CLUSTER_DIRS) - foreach(CLUSTER_DIR ${SUPPORTED_CLUSTER_DIRS}) - # If the cluster directory has .c/.cpp file, add it to SRC_DIRS_LIST - file(GLOB_RECURSE C_CPP_FILES "${CLUSTER_DIR}/*.c" "${CLUSTER_DIR}/*.cpp") - if (C_CPP_FILES) - list(APPEND SRC_DIRS_LIST "${CLUSTER_DIR}") - endif() - endforeach() +if (CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) + list(APPEND SRC_DIRS_LIST "${MATTER_SDK_PATH}/src/app/server" + "${MATTER_SDK_PATH}/src/app/reporting" + "${MATTER_SDK_PATH}/src/app/server-cluster" + # TODO Use esp-matter data model and remove ember codes + "${MATTER_SDK_PATH}/src/app/util" + "${MATTER_SDK_PATH}/src/app/util/persistence" + "${MATTER_SDK_PATH}/src/data-model-providers/codegen") + if (CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) + include("utils/cluster_select/cluster_dir.cmake") + get_supported_cluster_dirs(SUPPORTED_CLUSTER_DIRS) + foreach(CLUSTER_DIR ${SUPPORTED_CLUSTER_DIRS}) + # If the cluster directory has .c/.cpp file, add it to SRC_DIRS_LIST + file(GLOB_RECURSE C_CPP_FILES "${CLUSTER_DIR}/*.c" "${CLUSTER_DIR}/*.cpp") + if (C_CPP_FILES) + list(APPEND SRC_DIRS_LIST "${CLUSTER_DIR}") + endif() + endforeach() - list(APPEND SRC_DIRS_LIST "zap_common/app") - list(APPEND INCLUDE_DIRS_LIST "zap_common") + list(APPEND SRC_DIRS_LIST "zap_common/app" + "data_model" + "private") + list(APPEND INCLUDE_DIRS_LIST "zap_common" + "data_model") + endif(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) else() - # Do not add all the clusters srcs to esp_matter for examples that don't use ESP-Matter Data Model(such as zap light example) - # For those examples, they should include the clusters srcs in their main component - list(APPEND EXCLUDE_SRCS_LIST "esp_matter_delegate_callbacks.cpp") -endif() + list(APPEND EXCLUDE_SRCS_LIST "esp_matter_identify.cpp" + "esp_matter_ota.cpp" + "esp_matter_attribute_utils.cpp") +endif(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) set(REQUIRES_LIST chip bt esp_matter_console nvs_flash app_update esp_secure_cert_mgr mbedtls esp_system openthread json) idf_component_register( SRC_DIRS ${SRC_DIRS_LIST} INCLUDE_DIRS ${INCLUDE_DIRS_LIST} EXCLUDE_SRCS ${EXCLUDE_SRCS_LIST} - PRIV_INCLUDE_DIRS "private" + PRIV_INCLUDE_DIRS "private" "data_model/private" REQUIRES ${REQUIRES_LIST}) # This has been added to fix the error and should be removed once fixed: @@ -53,10 +57,14 @@ idf_component_register( SRC_DIRS ${SRC_DIRS_LIST} idf_build_set_property(COMPILE_OPTIONS "-Wno-error=uninitialized;-Wno-error=maybe-uninitialized;-Wno-missing-field-initializers;" APPEND) idf_build_set_property(COMPILE_OPTIONS "-Wno-error=array-bounds" APPEND) -if (NOT CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) - target_include_directories(${COMPONENT_LIB} PUBLIC "${CMAKE_BINARY_DIR}/gen/__idf_main-codegen/cpp-app" - "${CMAKE_BINARY_DIR}/gen/__idf_main-zapgen/zapgen/app-templates") -endif() +if (CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) + if (CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) + target_link_libraries(${COMPONENT_LIB} INTERFACE "-u data_model_utils_impl") + else() + target_include_directories(${COMPONENT_LIB} PUBLIC "${CMAKE_BINARY_DIR}/gen/__idf_main-codegen/cpp-app" + "${CMAKE_BINARY_DIR}/gen/__idf_main-zapgen/zapgen/app-templates") + endif(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) +endif(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) target_sources(${COMPONENT_LIB} PRIVATE ${MATTER_SDK_PATH}/src/app/StorageDelegateWrapper.cpp ${MATTER_SDK_PATH}/src/app/SafeAttributePersistenceProvider.cpp) diff --git a/components/esp_matter/Kconfig b/components/esp_matter/Kconfig index dff39518a..885599dc2 100644 --- a/components/esp_matter/Kconfig +++ b/components/esp_matter/Kconfig @@ -212,6 +212,7 @@ menu "ESP Matter" config ESP_MATTER_ENABLE_DATA_MODEL bool "Use ESP-Matter data model" + depends on ESP_MATTER_ENABLE_MATTER_SERVER default y help This option should be disable for zap examples diff --git a/components/esp_matter/esp_matter_attribute.cpp b/components/esp_matter/data_model/esp_matter_attribute.cpp similarity index 100% rename from components/esp_matter/esp_matter_attribute.cpp rename to components/esp_matter/data_model/esp_matter_attribute.cpp diff --git a/components/esp_matter/esp_matter_attribute.h b/components/esp_matter/data_model/esp_matter_attribute.h similarity index 99% rename from components/esp_matter/esp_matter_attribute.h rename to components/esp_matter/data_model/esp_matter_attribute.h index d48f13cd7..6515ae4bf 100644 --- a/components/esp_matter/esp_matter_attribute.h +++ b/components/esp_matter/data_model/esp_matter_attribute.h @@ -14,7 +14,7 @@ #pragma once -#include +#include namespace esp_matter { namespace cluster { diff --git a/components/esp_matter/esp_matter_attribute_bounds.cpp b/components/esp_matter/data_model/esp_matter_attribute_bounds.cpp similarity index 99% rename from components/esp_matter/esp_matter_attribute_bounds.cpp rename to components/esp_matter/data_model/esp_matter_attribute_bounds.cpp index 6af146ffb..3ecb25ed6 100644 --- a/components/esp_matter/esp_matter_attribute_bounds.cpp +++ b/components/esp_matter/data_model/esp_matter_attribute_bounds.cpp @@ -15,6 +15,8 @@ #include #include +#include + static const char *TAG = "esp_matter_cluster"; using namespace chip::app::Clusters; diff --git a/components/esp_matter/esp_matter_attribute_bounds.h b/components/esp_matter/data_model/esp_matter_attribute_bounds.h similarity index 97% rename from components/esp_matter/esp_matter_attribute_bounds.h rename to components/esp_matter/data_model/esp_matter_attribute_bounds.h index 8a9de85f5..e0bf0a947 100644 --- a/components/esp_matter/esp_matter_attribute_bounds.h +++ b/components/esp_matter/data_model/esp_matter_attribute_bounds.h @@ -13,7 +13,7 @@ // limitations under the License. #pragma once -#include +#include namespace esp_matter { namespace cluster { diff --git a/components/esp_matter/esp_matter_cluster.cpp b/components/esp_matter/data_model/esp_matter_cluster.cpp similarity index 99% rename from components/esp_matter/esp_matter_cluster.cpp rename to components/esp_matter/data_model/esp_matter_cluster.cpp index 2fa418eb2..baa494f3a 100644 --- a/components/esp_matter/esp_matter_cluster.cpp +++ b/components/esp_matter/data_model/esp_matter_cluster.cpp @@ -114,7 +114,6 @@ cluster_t *create_default_binding_cluster(endpoint_t *endpoint) return binding::create(endpoint, &config, CLUSTER_FLAG_SERVER); } -#if CONFIG_ESP_MATTER_ENABLE_DATA_MODEL namespace descriptor { const function_generic_t *function_list = NULL; const int function_flags = CLUSTER_FLAG_NONE; @@ -3727,7 +3726,5 @@ cluster_t *create(endpoint_t *endpoint, config_t *config, uint8_t flags) // // ToDo // } /* audio_output */ -#endif /* CONFIG_ESP_MATTER_ENABLE_DATA_MODEL */ - } /* cluster */ } /* esp_matter */ diff --git a/components/esp_matter/esp_matter_cluster.h b/components/esp_matter/data_model/esp_matter_cluster.h similarity index 99% rename from components/esp_matter/esp_matter_cluster.h rename to components/esp_matter/data_model/esp_matter_cluster.h index 0bcde7cdd..31da7c715 100644 --- a/components/esp_matter/esp_matter_cluster.h +++ b/components/esp_matter/data_model/esp_matter_cluster.h @@ -14,13 +14,14 @@ #pragma once -#include #include #include +#include #include #include #include +#include namespace esp_matter { namespace cluster { diff --git a/components/esp_matter/esp_matter_command.cpp b/components/esp_matter/data_model/esp_matter_command.cpp similarity index 99% rename from components/esp_matter/esp_matter_command.cpp rename to components/esp_matter/data_model/esp_matter_command.cpp index d545b3f5e..dae4a6341 100644 --- a/components/esp_matter/esp_matter_command.cpp +++ b/components/esp_matter/data_model/esp_matter_command.cpp @@ -3225,7 +3225,6 @@ constexpr const cluster_command_t cluster_command_table[] = { {GroupKeyManagement::Id, GET_COMMAND_COUNT_LIST(cluster::group_key_management)}, }; -#if defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) const command_entry_t *get_cluster_accepted_command_list(uint32_t cluster_id) { for (auto const &cluster_command : cluster_command_table) { @@ -3265,11 +3264,9 @@ size_t get_cluster_generated_command_count(uint32_t cluster_id) } return 0; } -#endif // defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) static callback_t get_cluster_accepted_command(uint32_t cluster_id, uint32_t command_id) { -#if defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) for (auto const &cluster_command : cluster_command_table) { if (cluster_command.cluster_id == cluster_id) { for (size_t index = 0; index < cluster_command.accepted_command_count; ++index){ @@ -3279,7 +3276,6 @@ static callback_t get_cluster_accepted_command(uint32_t cluster_id, uint32_t com } } } -#endif return nullptr; } diff --git a/components/esp_matter/esp_matter_command.h b/components/esp_matter/data_model/esp_matter_command.h similarity index 100% rename from components/esp_matter/esp_matter_command.h rename to components/esp_matter/data_model/esp_matter_command.h diff --git a/components/esp_matter/data_model/esp_matter_data_model.cpp b/components/esp_matter/data_model/esp_matter_data_model.cpp new file mode 100644 index 000000000..20823983f --- /dev/null +++ b/components/esp_matter/data_model/esp_matter_data_model.cpp @@ -0,0 +1,1818 @@ +// 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. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include "app/server/Server.h" +#include "credentials/GroupDataProviderImpl.h" + +#define ESP_MATTER_MAX_DEVICE_TYPE_COUNT CONFIG_ESP_MATTER_MAX_DEVICE_TYPE_COUNT +#define MAX_GROUPS_PER_FABRIC_PER_ENDPOINT CONFIG_MAX_GROUPS_PER_FABRIC_PER_ENDPOINT + +static const char *TAG = "data_model"; + +using chip::CommandId; +using chip::DataVersion; +using chip::EventId; +using chip::kInvalidAttributeId; +using chip::kInvalidCommandId; +using chip::kInvalidClusterId; +using chip::kInvalidEndpointId; + +namespace esp_matter { +struct _attribute_base_t { + uint16_t flags; // This struct is for attributes managed internally. + uint16_t index; + uint32_t attribute_id; + struct _attribute_base_t *next; +}; + +struct _attribute_t : public _attribute_base_t { + uint32_t cluster_id; // This struct is for attributes not managed internally. + esp_matter_attr_val_t val; + attribute::callback_t override_callback; + uint16_t endpoint_id; +}; + +typedef struct _command { + uint32_t command_id; + uint16_t flags; + command::callback_t callback; + command::callback_t user_callback; + struct _command *next; +} _command_t; + +typedef struct _event { + uint32_t event_id; + struct _event *next; +} _event_t; + +typedef struct _cluster { + uint8_t index; + uint16_t endpoint_id; + cluster::plugin_server_init_callback_t plugin_server_init_callback; + cluster::delegate_init_callback_t delegate_init_callback; + void * delegate_pointer; + cluster::add_bounds_callback_t add_bounds_callback; + _attribute_base_t *attribute_list; /* If attribute is managed internally, the actual pointer type is _internal_attribute_t. + When operating attribute_list, do check the flags first! */ + EmberAfAttributeMetadata *matter_attributes; + _command_t *command_list; + _event_t *event_list; + struct _cluster *next; +} _cluster_t; + +typedef struct _endpoint { + uint16_t endpoint_id; + uint8_t device_type_count; + uint8_t cluster_count; + uint8_t device_type_versions[ESP_MATTER_MAX_DEVICE_TYPE_COUNT]; + uint32_t device_type_ids[ESP_MATTER_MAX_DEVICE_TYPE_COUNT]; + uint16_t flags; + uint16_t parent_endpoint_id; + _cluster_t *cluster_list; + EmberAfEndpointType *endpoint_type; + chip::DataVersion *data_versions_ptr; + EmberAfDeviceType *device_types_ptr; + void *priv_data; + Identify *identify; + struct _endpoint *next; +} _endpoint_t; + +typedef struct _node { + _endpoint_t *endpoint_list; + uint16_t min_unused_endpoint_id; +} _node_t; + +namespace node { + +static _node_t *node = NULL; + +// If Matter server or ESP-Matter data model is not enabled. we will never use minimum unused endpoint id. +esp_err_t store_min_unused_endpoint_id() +{ + VerifyOrReturnError((node && esp_matter::is_started()), ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "Node does not exist or esp_matter does not start")); + nvs_handle_t handle; + esp_err_t err = nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, ESP_MATTER_KVS_NAMESPACE, + NVS_READWRITE, &handle); + + VerifyOrReturnError(err == ESP_OK, err, ESP_LOGE(TAG, "Failed to open the node nvs_namespace")); + err = nvs_set_u16(handle, "min_uu_ep_id", node->min_unused_endpoint_id); + nvs_commit(handle); + nvs_close(handle); + return err; +} + +esp_err_t read_min_unused_endpoint_id() +{ + VerifyOrReturnError((node && esp_matter::is_started()), ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "Node does not exist or esp_matter does not start")); + + nvs_handle_t handle; + esp_err_t err = nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, ESP_MATTER_KVS_NAMESPACE, + NVS_READONLY, &handle); + if (err == ESP_OK) { + err = nvs_get_u16(handle, "min_uu_ep_id", &node->min_unused_endpoint_id); + nvs_close(handle); + } + + if (err == ESP_ERR_NVS_NOT_FOUND) { + ESP_LOGI(TAG, "Cannot find minimum unused endpoint_id, try to find in the previous namespace"); + // Try to read the minimum unused endpoint_id from the previous node namespace. + err = nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, "node", NVS_READONLY, &handle); + VerifyOrReturnError(err == ESP_OK, err, ESP_LOGI(TAG, "Failed to open node namespace")); + err = nvs_get_u16(handle, "min_uu_ep_id", &node->min_unused_endpoint_id); + nvs_close(handle); + if (err == ESP_OK) { + // If the minimum unused endpoint_id is got, we will erase it from the previous namespace + // and store it to the new namespace. + if (nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, "node", NVS_READWRITE, &handle) == ESP_OK) { + if (nvs_erase_key(handle, "min_uu_ep_id") != ESP_OK) { + ESP_LOGE(TAG, "Failed to erase minimum unused endpoint_id"); + } else { + nvs_commit(handle); + } + nvs_close(handle); + } + return store_min_unused_endpoint_id(); + } + } else if (err != ESP_OK) { + ESP_LOGE(TAG, "Failed to get minimum unused endpoint_id in the %s nvs_namespace", ESP_MATTER_KVS_NAMESPACE); + } + return err; +} + +} /* node */ + +namespace command { +command_entry_t *get_cluster_accepted_command_list(uint32_t cluster_id); +size_t get_cluster_accepted_command_count(uint32_t cluster_id); +command_entry_t *get_cluster_generated_command_list(uint32_t cluster_id); +size_t get_cluster_generated_command_count(uint32_t cluster_id); +} /* command */ + +namespace attribute { + +static EmberAfAttributeMetadata *get_external_attribute_metadata(_attribute_t * attribute) +{ + if (NULL == attribute || (attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY)) { + return NULL; + } + _cluster_t *cluster = (_cluster_t *)cluster::get(attribute->endpoint_id, attribute->cluster_id); + if (NULL == cluster) { + return NULL; + } + return &cluster->matter_attributes[attribute->index]; +} + +static esp_err_t free_default_value(attribute_t *attribute) +{ + VerifyOrReturnError(attribute, ESP_FAIL, ESP_LOGE(TAG, "Attribute cannot be NULL")); + _attribute_t *current_attribute = (_attribute_t *)attribute; + EmberAfAttributeMetadata *matter_attribute = get_external_attribute_metadata(current_attribute); + if (!matter_attribute) { + ESP_LOGE(TAG, "Attribute Metadata is not found"); + return ESP_ERR_NOT_FOUND; + } + + /* Free value if data is more than 2 bytes or if it is min max attribute */ + if (current_attribute->flags & ATTRIBUTE_FLAG_MIN_MAX) { + if (matter_attribute->size > 2) { + esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToMinMaxValue->defaultValue.ptrToDefaultValue); + esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToMinMaxValue->minValue.ptrToDefaultValue); + esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToMinMaxValue->maxValue.ptrToDefaultValue); + } + esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToMinMaxValue); + } else if (matter_attribute->size > 2) { + esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToDefaultValue); + } + return ESP_OK; +} + +static EmberAfDefaultAttributeValue get_default_value_from_data(esp_matter_attr_val_t *val, + EmberAfAttributeType attribute_type, + uint16_t attribute_size) +{ + EmberAfDefaultAttributeValue default_value = (uint16_t)0; + uint8_t *value = (uint8_t *)esp_matter_mem_calloc(1, attribute_size); + VerifyOrReturnValue(value, default_value, ESP_LOGE(TAG, "Could not allocate value buffer for default value")); + get_data_from_attr_val(val, &attribute_type, &attribute_size, value); + + if (attribute_size > 2) { + /* Directly set the pointer */ + default_value = value; + } else { + /* This data is 2 bytes or less. This should be represented as uint16. Copy the bytes appropriately + for 0 or 1 or 2 bytes to be converted to uint16. Then free the allocated buffer. */ + uint16_t int_value = 0; + if (attribute_size == 2) { + memcpy(&int_value, value, attribute_size); + } else if (attribute_size == 1) { + int_value = (uint16_t)*value; + } + default_value = int_value; + esp_matter_mem_free(value); + } + return default_value; +} + +static esp_err_t set_default_value_from_current_val(attribute_t *attribute, esp_matter_attr_val_t *min, esp_matter_attr_val_t *max) +{ + VerifyOrReturnError(attribute, ESP_FAIL, ESP_LOGE(TAG, "Attribute cannot be NULL")); + _attribute_t *current_attribute = (_attribute_t *)attribute; + + EmberAfAttributeMetadata *matter_attribute = get_external_attribute_metadata(current_attribute); + if (!matter_attribute) { + ESP_LOGE(TAG, "Attribute Metadata is not found"); + return ESP_ERR_NOT_FOUND; + } + + esp_matter_attr_val_t *val = ¤t_attribute->val; + + /* Get size */ + EmberAfAttributeType attribute_type = 0; + uint16_t attribute_size = 0; + get_data_from_attr_val(val, &attribute_type, &attribute_size, NULL); + + /* Get and set value */ + if (current_attribute->flags & ATTRIBUTE_FLAG_MIN_MAX) { + EmberAfAttributeMinMaxValue *temp_value = (EmberAfAttributeMinMaxValue *)esp_matter_mem_calloc(1, + sizeof(EmberAfAttributeMinMaxValue)); + VerifyOrReturnError(temp_value, ESP_FAIL, ESP_LOGE(TAG, "Could not allocate ptrToMinMaxValue for default value")); + temp_value->defaultValue = get_default_value_from_data(val, attribute_type, attribute_size); + temp_value->minValue = get_default_value_from_data(min, attribute_type, attribute_size); + temp_value->maxValue = get_default_value_from_data(max, attribute_type, attribute_size); + matter_attribute->defaultValue.ptrToMinMaxValue = temp_value; + } else if (attribute_size > 2) { + EmberAfDefaultAttributeValue temp_value = get_default_value_from_data(val, attribute_type, attribute_size); + matter_attribute->defaultValue.ptrToDefaultValue = temp_value.ptrToDefaultValue; + } else { + EmberAfDefaultAttributeValue temp_value = get_default_value_from_data(val, attribute_type, attribute_size); + matter_attribute->defaultValue.defaultValue = temp_value.defaultValue; + } + return ESP_OK; +} +} /* attribute */ + +namespace endpoint { + +static int get_next_index() +{ + uint16_t endpoint_id = 0; + for (int index = 0; index < MAX_ENDPOINT_COUNT; index++) { + endpoint_id = emberAfEndpointFromIndex(index); + if (endpoint_id == kInvalidEndpointId) { + return index; + } + } + return 0xFFFF; +} + +// global instance so that we can reset it when needed. +// We may need to reset it when new endpoint is added or existing endpoint is removed. +// This is specifically for bridged device. +static chip::Credentials::GroupDataProviderImpl *s_group_data_provider = nullptr; +static uint16_t s_groups_server_cluster_count = 0; + +static void resize_group_data_provider() +{ + // don't do anything if the count is the same + uint16_t groups_server_cluster_count = node::get_server_cluster_endpoint_count(chip::app::Clusters::Groups::Id); + if (s_groups_server_cluster_count == groups_server_cluster_count) { + return; + } + + s_groups_server_cluster_count = groups_server_cluster_count; + uint16_t max_groups_per_fabric = s_groups_server_cluster_count * MAX_GROUPS_PER_FABRIC_PER_ENDPOINT; + auto group_data_provider = new (std::nothrow) chip::Credentials::GroupDataProviderImpl(max_groups_per_fabric, CHIP_CONFIG_MAX_GROUP_KEYS_PER_FABRIC); + if (!group_data_provider) { + ESP_LOGE(TAG, "Failed to allocate memory for group data provider"); + return; + } + + group_data_provider->SetStorageDelegate(&chip::Server::GetInstance().GetPersistentStorage()); + group_data_provider->SetSessionKeystore(chip::Server::GetInstance().GetSessionKeystore()); + + // As we are re-using the persistent storage instance from the Server class instance, + // which has all the data from the previous endpoints, so no harm in re-sizing. + group_data_provider->Init(); + + // delete the old one if it exists + if (s_group_data_provider) { + delete s_group_data_provider; + } + + s_group_data_provider = group_data_provider; + chip::Credentials::SetGroupDataProvider(s_group_data_provider); +} + +static esp_err_t disable(endpoint_t *endpoint) +{ + /* Take lock if not already taken */ + lock::status_t lock_status = lock::chip_stack_lock(portMAX_DELAY); + + VerifyOrReturnError(lock_status != lock::FAILED, ESP_FAIL, ESP_LOGE(TAG, "Could not get task context")); + + /* Remove endpoint */ + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + int endpoint_index = emberAfGetDynamicIndexFromEndpoint(current_endpoint->endpoint_id); + if (endpoint_index == 0xFFFF) { + ESP_LOGE(TAG, "Could not find endpoint index"); + if (lock_status == lock::SUCCESS) { + lock::chip_stack_unlock(); + } + return ESP_FAIL; + } + emberAfClearDynamicEndpoint(endpoint_index); + + if (lock_status == lock::SUCCESS) { + lock::chip_stack_unlock(); + } + + /* Delete identify */ + if (current_endpoint->identify) { + chip::Platform::Delete(current_endpoint->identify); + current_endpoint->identify = NULL; + } + + // resize the group data provider to match the new endpoint count + resize_group_data_provider(); + + return ESP_OK; +} + +esp_err_t enable(endpoint_t *endpoint) +{ + VerifyOrReturnError(endpoint, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Endpoint cannot be NULL")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + + /* Device types */ + EmberAfDeviceType *device_types_ptr = (EmberAfDeviceType *)esp_matter_mem_calloc(current_endpoint->device_type_count, sizeof(EmberAfDeviceType)); + if (!device_types_ptr) { + ESP_LOGE(TAG, "Couldn't allocate device_types"); + /* goto cleanup is not used here to avoid 'crosses initialization' of device_types below */ + return ESP_ERR_NO_MEM; + } + for (size_t i = 0; i < current_endpoint->device_type_count; ++i) { + device_types_ptr[i].deviceTypeId = current_endpoint->device_type_ids[i]; + device_types_ptr[i].deviceTypeRevision = current_endpoint->device_type_versions[i]; + } + chip::Span device_types(device_types_ptr, current_endpoint->device_type_count); + current_endpoint->device_types_ptr = device_types_ptr; + + /* Clusters */ + _cluster_t *cluster = current_endpoint->cluster_list; + int cluster_count = SinglyLinkedList<_cluster_t>::count(cluster); + int cluster_index = 0; + + DataVersion *data_versions_ptr = (DataVersion *)esp_matter_mem_calloc(1, cluster_count * sizeof(DataVersion)); + if (!data_versions_ptr) { + ESP_LOGE(TAG, "Couldn't allocate data_versions"); + esp_matter_mem_free(device_types_ptr); + current_endpoint->device_types_ptr = NULL; + /* goto cleanup is not used here to avoid 'crosses initialization' of data_versions below */ + return ESP_ERR_NO_MEM; + } + chip::Span data_versions(data_versions_ptr, cluster_count); + current_endpoint->data_versions_ptr = data_versions_ptr; + + /* Variables */ + /* This is needed to avoid 'crosses initialization' errors because of goto */ + esp_err_t err = ESP_OK; + lock::status_t lock_status = lock::FAILED; + CHIP_ERROR status = CHIP_NO_ERROR; + CommandId *accepted_command_ids = NULL; + CommandId *generated_command_ids = NULL; + _command_t *command = NULL; + command_entry_t *command_list = NULL; + uint32_t cluster_id = kInvalidClusterId; + int command_count = 0; + int command_index = 0; + int command_flag = COMMAND_FLAG_NONE; + EventId *event_ids = NULL; + _event_t *event = NULL; + int event_count = 0; + int event_index = 0; + int endpoint_index = 0; + + while (cluster) { + /* Attributes */ + /* Handled in attribute::create() */ + + /* Commands */ + command = NULL; + command_count = 0; + command_index = 0; + command_flag = COMMAND_FLAG_NONE; + accepted_command_ids = NULL; + generated_command_ids = NULL; + cluster_id = cluster::get_id((cluster_t*)cluster); + + /* Init identify if exists and not initialized */ + if (cluster_id == chip::app::Clusters::Identify::Id && current_endpoint->identify == NULL) { + _attribute_t *identify_type_attr = (_attribute_t *)attribute::get( + current_endpoint->endpoint_id, cluster_id, chip::app::Clusters::Identify::Attributes::IdentifyType::Id); + if (identify_type_attr) { + if (identification::init(current_endpoint->endpoint_id, identify_type_attr->val.val.u8) != ESP_OK) { + ESP_LOGE(TAG, "Failed to init identification"); + err = ESP_FAIL; + break; + } + } else { + ESP_LOGE(TAG, "Can't get IdentifyType attribute in Identify cluster"); + err = ESP_ERR_INVALID_STATE; + break; + } + } + + /* Client Generated Commands */ + command_flag = COMMAND_FLAG_ACCEPTED; + command = cluster->command_list; + command_count = SinglyLinkedList<_command_t>::count_with_flag(command, command_flag); + command_count += command::get_cluster_accepted_command_count(cluster_id); + if (command_count > 0) { + command_index = 0; + accepted_command_ids = (CommandId *)esp_matter_mem_calloc(1, (command_count + 1) * sizeof(CommandId)); + if (!accepted_command_ids) { + ESP_LOGE(TAG, "Couldn't allocate accepted_command_ids"); + err = ESP_ERR_NO_MEM; + break; + } + while (command) { + if (command->flags & command_flag) { + accepted_command_ids[command_index] = command->command_id; + command_index++; + } + command = command->next; + } + command_list = command::get_cluster_accepted_command_list(cluster_id); + for(size_t index = 0; command_index < command_count && command_list; index++) { + accepted_command_ids[command_index] = command_list[index].command_id; + command_index++; + } + accepted_command_ids[command_index] = kInvalidCommandId; + } + + /* Server Generated Commands */ + command_flag = COMMAND_FLAG_GENERATED; + command = cluster->command_list; + command_count = SinglyLinkedList<_command_t>::count_with_flag(command, command_flag); + command_count += command::get_cluster_generated_command_count(cluster_id); + if (command_count > 0) { + command_index = 0; + generated_command_ids = (CommandId *)esp_matter_mem_calloc(1, (command_count + 1) * sizeof(CommandId)); + if (!generated_command_ids) { + ESP_LOGE(TAG, "Couldn't allocate generated_command_ids"); + err = ESP_ERR_NO_MEM; + break; + } + while (command) { + if (command->flags & command_flag) { + generated_command_ids[command_index] = command->command_id; + command_index++; + } + command = command->next; + } + command_list = command::get_cluster_generated_command_list(cluster_id); + for(size_t index = 0; command_index < command_count && command_list; index++) { + generated_command_ids[command_index] = command_list[index].command_id; + command_index++; + } + generated_command_ids[command_index] = kInvalidCommandId; + } + + /* Event */ + event = cluster->event_list; + event_count = SinglyLinkedList<_event_t>::count(event); + if (event_count > 0) { + event_index = 0; + event_ids = (EventId *)esp_matter_mem_calloc(1, (event_count + 1) * sizeof(EventId)); + if (!event_ids) { + ESP_LOGE(TAG, "Couldn't allocate event_ids"); + err = ESP_ERR_NO_MEM; + break; + } + while (event) { + event_ids[event_index] = event->event_id; + event_index++; + event = event->next; + } + event_ids[event_index] = chip::kInvalidEventId; + } + + /* Fill up the cluster */ + EmberAfCluster *matter_clusters = (EmberAfCluster *)(¤t_endpoint->endpoint_type->cluster[cluster_index]); + matter_clusters->attributes = cluster->matter_attributes; + matter_clusters->acceptedCommandList = accepted_command_ids; + matter_clusters->generatedCommandList = generated_command_ids; + matter_clusters->eventList = event_ids; + matter_clusters->eventCount = event_count; + + /* Get next cluster */ + current_endpoint->endpoint_type->endpointSize += matter_clusters->clusterSize; + cluster = cluster->next; + cluster_index++; + + /* This is to avoid double free in case of errors */ + accepted_command_ids = NULL; + generated_command_ids = NULL; + event_ids = NULL; + } + if (err != ESP_OK) { + goto cleanup; + } + + current_endpoint->endpoint_type->clusterCount = cluster_count; + + /* Take lock if not already taken */ + lock_status = lock::chip_stack_lock(portMAX_DELAY); + if (lock_status == lock::FAILED) { + ESP_LOGE(TAG, "Could not get task context"); + goto cleanup; + } + + /* Add Endpoint */ + endpoint_index = endpoint::get_next_index(); + status = emberAfSetDynamicEndpoint(endpoint_index, current_endpoint->endpoint_id, current_endpoint->endpoint_type, data_versions, + device_types, current_endpoint->parent_endpoint_id); + if (status != CHIP_NO_ERROR) { + ESP_LOGE(TAG, "Error adding dynamic endpoint %" PRIu16 ": %" CHIP_ERROR_FORMAT, current_endpoint->endpoint_id, status.Format()); + err = ESP_FAIL; + if (lock_status == lock::SUCCESS) { + lock::chip_stack_unlock(); + } + goto cleanup; + } + if (lock_status == lock::SUCCESS) { + lock::chip_stack_unlock(); + } + ESP_LOGI(TAG, "Dynamic endpoint %" PRIu16 " added", current_endpoint->endpoint_id); + return err; + +cleanup: + esp_matter_mem_free(generated_command_ids); + esp_matter_mem_free(accepted_command_ids); + esp_matter_mem_free(event_ids); + if (current_endpoint->endpoint_type->cluster) { + for (int cluster_index = 0; cluster_index < cluster_count; cluster_index++) { + /* Free attributes */ + esp_matter_mem_free((void *)current_endpoint->endpoint_type->cluster[cluster_index].attributes); + /* Free commands */ + esp_matter_mem_free((void *)current_endpoint->endpoint_type->cluster[cluster_index].acceptedCommandList); + esp_matter_mem_free((void *)current_endpoint->endpoint_type->cluster[cluster_index].generatedCommandList); + /* Free events */ +esp_matter_mem_free((void *)current_endpoint->endpoint_type->cluster[cluster_index].eventList); + } + + } + esp_matter_mem_free(data_versions_ptr); + current_endpoint->data_versions_ptr = NULL; + esp_matter_mem_free(device_types_ptr); + current_endpoint->device_types_ptr = NULL; + return err; +} + +esp_err_t enable_all() +{ + node_t *node = node::get(); + /* Not returning error, since the node will not be initialized for application using the data model from zap */ + VerifyOrReturnError(node, ESP_OK); + + endpoint_t *endpoint = get_first(node); + while (endpoint) { + enable(endpoint); + endpoint = get_next(endpoint); + } + return ESP_OK; +} +} /* endpoint */ + +namespace attribute { +attribute_t *create(cluster_t *cluster, uint32_t attribute_id, uint16_t flags, esp_matter_attr_val_t val, + uint16_t max_val_size) +{ + /* Find */ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + attribute_t *existing_attribute = get(cluster, attribute_id); + if (existing_attribute) { + ESP_LOGW(TAG, "Attribute 0x%08" PRIX32 " on cluster 0x%08" PRIX32 " already exists. Not creating again.", attribute_id, + cluster::get_id(cluster)); + return existing_attribute; + } + + endpoint_t *endpoint = endpoint::get(current_cluster->endpoint_id); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + + /* Matter attributes */ + EmberAfCluster *matter_clusters = (EmberAfCluster *)(¤t_endpoint->endpoint_type->cluster[current_cluster->index]); + matter_clusters->attributeCount++; + int attribute_count = matter_clusters->attributeCount; + + if (current_cluster->matter_attributes) { + current_cluster->matter_attributes = (EmberAfAttributeMetadata *)esp_matter_mem_realloc(current_cluster->matter_attributes, attribute_count * sizeof(EmberAfAttributeMetadata)); + } else { + current_cluster->matter_attributes = (EmberAfAttributeMetadata *)esp_matter_mem_calloc(1, attribute_count * sizeof(EmberAfAttributeMetadata)); + } + if (!current_cluster->matter_attributes) { + ESP_LOGE(TAG, "Couldn't allocate matter_attributes"); + return NULL; + } + + /* Set */ + EmberAfAttributeMetadata *matter_attribute = ¤t_cluster->matter_attributes[attribute_count - 1]; + matter_attribute->attributeId = attribute_id; + + /* esp-matter uses uint16_t as the flags for the extras, EmberAfAttributeMetadata uses uint8_t as the mask. + The conversion from uint16 to uint8 is as expected for that the extra flags are only used in esp-matter. */ + matter_attribute->mask = static_cast(flags); + if (!(flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY)) { + matter_attribute->mask |= ATTRIBUTE_FLAG_EXTERNAL_STORAGE; + } + matter_attribute->attributeType = 0; + matter_attribute->size = 0; + _attribute_t *attribute = NULL; + if (!(flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY)) { + /* Allocate */ + attribute = (_attribute_t *)esp_matter_mem_calloc(1, sizeof(_attribute_t)); + if (!attribute) { + ESP_LOGE(TAG, "Couldn't allocate _attribute_t"); + return NULL; + } + attribute->index = attribute_count - 1; + attribute->attribute_id = attribute_id; + attribute->cluster_id = matter_clusters->clusterId; + attribute->endpoint_id = current_cluster->endpoint_id; + attribute->flags = flags; + attribute->flags |= ATTRIBUTE_FLAG_EXTERNAL_STORAGE; + + // After reboot, string and array are treated as Invalid. So need to store val.type and size of attribute value. + attribute->val.type = val.type; + if (val.type == ESP_MATTER_VAL_TYPE_CHAR_STRING || + val.type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING || + val.type == ESP_MATTER_VAL_TYPE_OCTET_STRING || + val.type == ESP_MATTER_VAL_TYPE_LONG_OCTET_STRING || + val.type == ESP_MATTER_VAL_TYPE_ARRAY) { + attribute->val.val.a.s = val.val.a.s; + attribute->val.val.a.n = val.val.a.n; + attribute->val.val.a.t = val.val.a.t; + } + + bool attribute_updated = false; + if (flags & ATTRIBUTE_FLAG_NONVOLATILE) { + // Lets directly read into attribute->val so that we don't have to set the attribute value again. + esp_err_t err = get_val_from_nvs(attribute->endpoint_id, attribute->cluster_id, attribute_id, + attribute->val); + if (err == ESP_OK) { + attribute_updated = true; + } + } + if (!attribute_updated) { + set_val((attribute_t *)attribute, &val); + } + + set_default_value_from_current_val((attribute_t *)attribute, NULL, NULL); + + attribute::get_data_from_attr_val(&attribute->val, &matter_attribute->attributeType, + &matter_attribute->size, NULL); + if (attribute->val.type == ESP_MATTER_VAL_TYPE_CHAR_STRING || + attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING) { + uint16_t size_for_storing_str_len = attribute->val.val.a.t - attribute->val.val.a.s; + matter_attribute->size = max_val_size + size_for_storing_str_len; + } + matter_clusters->clusterSize += matter_attribute->size; + } else { + attribute = (_attribute_t *)esp_matter_mem_calloc(1, sizeof(_attribute_base_t)); + attribute->attribute_id = attribute_id; + attribute->index = attribute_count - 1; + attribute->flags = flags; + } + + /* Add */ + SinglyLinkedList<_attribute_base_t>::append(¤t_cluster->attribute_list, attribute); + return (attribute_t *)attribute; +} + +static esp_err_t destroy(attribute_t *attribute) +{ + VerifyOrReturnError(attribute, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Attribute cannot be NULL")); + _attribute_t *current_attribute = (_attribute_t *)attribute; + + if (current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY) { + // For attribute managed internally, free as the _attribute_base_t pointer. + esp_matter_mem_free((_attribute_base_t *)attribute); + return ESP_OK; + } + + /* Default value needs to be deleted first since it uses the current val. */ + free_default_value(attribute); + + /* Delete val here, if required */ + if (current_attribute->val.type == ESP_MATTER_VAL_TYPE_CHAR_STRING || + current_attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING || + current_attribute->val.type == ESP_MATTER_VAL_TYPE_OCTET_STRING || + current_attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_OCTET_STRING || + current_attribute->val.type == ESP_MATTER_VAL_TYPE_ARRAY) { + /* Free buf */ + esp_matter_mem_free(current_attribute->val.val.a.b); + } + + /* Erase the persistent data */ + if (attribute::get_flags(attribute) & ATTRIBUTE_FLAG_NONVOLATILE) { + erase_val_in_nvs(current_attribute->endpoint_id, current_attribute->cluster_id, current_attribute->attribute_id); + } + + /* Free */ + esp_matter_mem_free(current_attribute); + return ESP_OK; +} + +attribute_t *get(cluster_t *cluster, uint32_t attribute_id) +{ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + _attribute_base_t *current_attribute = current_cluster->attribute_list; + while (current_attribute) { + if (current_attribute->attribute_id == attribute_id) { + break; + } + current_attribute = current_attribute->next; + } + + return (attribute_t *)current_attribute; +} + +attribute_t *get(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id) +{ + cluster_t *cluster = cluster::get(endpoint_id, cluster_id); + return get(cluster, attribute_id); +} + +attribute_t *get_first(cluster_t *cluster) +{ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + return (attribute_t *)current_cluster->attribute_list; +} + +attribute_t *get_next(attribute_t *attribute) +{ + VerifyOrReturnValue(attribute, NULL, ESP_LOGE(TAG, "Attribute cannot be NULL")); + _attribute_t *current_attribute = (_attribute_t *)attribute; + return (attribute_t *)current_attribute->next; +} + +uint32_t get_id(attribute_t *attribute) +{ + VerifyOrReturnValue(attribute, kInvalidAttributeId, ESP_LOGE(TAG, "Attribute cannot be NULL")); + _attribute_t *current_attribute = (_attribute_t *)attribute; + return current_attribute->attribute_id; +} + +constexpr uint16_t k_deferred_attribute_persistence_time_ms = CONFIG_ESP_MATTER_DEFERRED_ATTR_PERSISTENCE_TIME_MS; + +static void deferred_attribute_write(chip::System::Layer *layer, void *attribute_ptr) +{ + _attribute_t *current_attribute = (_attribute_t *)attribute_ptr; + ESP_LOGI(TAG, "Store the deferred attribute 0x%" PRIx32 " of cluster 0x%" PRIX32 " on endpoint 0x%" PRIx16, + current_attribute->attribute_id, current_attribute->cluster_id, current_attribute->endpoint_id); + store_val_in_nvs(current_attribute->endpoint_id, current_attribute->cluster_id, current_attribute->attribute_id, + current_attribute->val); +} + +esp_err_t set_val(attribute_t *attribute, esp_matter_attr_val_t *val) +{ + VerifyOrReturnError(attribute, ESP_FAIL, ESP_LOGE(TAG, "Attribute cannot be NULL")); + _attribute_t *current_attribute = (_attribute_t *)attribute; + + ESP_RETURN_ON_FALSE(!(current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY), ESP_ERR_NOT_SUPPORTED, TAG, + "Attribute is not managed by esp matter data model"); + + if (val->type == ESP_MATTER_VAL_TYPE_CHAR_STRING || val->type == ESP_MATTER_VAL_TYPE_OCTET_STRING || + val->type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING || val->type == ESP_MATTER_VAL_TYPE_LONG_OCTET_STRING || + val->type == ESP_MATTER_VAL_TYPE_ARRAY) { + /* Free old buf */ + esp_matter_mem_free(current_attribute->val.val.a.b); + current_attribute->val.val.a.b = NULL; + if (val->val.a.s > 0) { + /* Alloc new buf */ + uint8_t *new_buf = (uint8_t *)esp_matter_mem_calloc(1, val->val.a.s); + VerifyOrReturnError(new_buf, ESP_ERR_NO_MEM, ESP_LOGE(TAG, "Could not allocate new buffer")); + /* Copy to new buf and assign */ + memcpy(new_buf, val->val.a.b, val->val.a.s); + current_attribute->val.val.a.b = new_buf; + current_attribute->val.val.a.s = val->val.a.s; + current_attribute->val.val.a.n = val->val.a.n; + current_attribute->val.val.a.t = val->val.a.t; + } else { + ESP_LOGD(TAG, "Set val called with string with size 0"); + } + } else { + memcpy((void *)¤t_attribute->val, (void *)val, sizeof(esp_matter_attr_val_t)); + } + + if (current_attribute->flags & ATTRIBUTE_FLAG_NONVOLATILE) { + if (current_attribute->flags & ATTRIBUTE_FLAG_DEFERRED) { + if (!chip::DeviceLayer::SystemLayer().IsTimerActive(deferred_attribute_write, current_attribute)) { + auto & system_layer = chip::DeviceLayer::SystemLayer(); + system_layer.StartTimer(chip::System::Clock::Milliseconds16(k_deferred_attribute_persistence_time_ms), + deferred_attribute_write, current_attribute); + } + } else { + store_val_in_nvs(current_attribute->endpoint_id, current_attribute->cluster_id, + current_attribute->attribute_id, current_attribute->val); + } + } + return ESP_OK; +} + +esp_err_t get_val(attribute_t *attribute, esp_matter_attr_val_t *val) +{ + VerifyOrReturnError(attribute, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Attribute cannot be NULL")); + _attribute_t *current_attribute = (_attribute_t *)attribute; + + ESP_RETURN_ON_FALSE(!(current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY), ESP_ERR_NOT_SUPPORTED, TAG, + "Attribute is not managed by esp matter data model"); + memcpy((void *)val, (void *)¤t_attribute->val, sizeof(esp_matter_attr_val_t)); + return ESP_OK; +} + +esp_err_t add_bounds(attribute_t *attribute, esp_matter_attr_val_t min, esp_matter_attr_val_t max) +{ + VerifyOrReturnError(attribute, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Attribute cannot be NULL")); + _attribute_t *current_attribute = (_attribute_t *)attribute; + + ESP_RETURN_ON_FALSE(!(current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY), ESP_ERR_NOT_SUPPORTED, TAG, + "Attribute is not managed by esp matter data model"); + + /* Check if bounds can be set */ + if (current_attribute->val.type == ESP_MATTER_VAL_TYPE_CHAR_STRING || + current_attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING || + current_attribute->val.type == ESP_MATTER_VAL_TYPE_OCTET_STRING || + current_attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_OCTET_STRING || + current_attribute->val.type == ESP_MATTER_VAL_TYPE_ARRAY) { + ESP_LOGE(TAG, "Bounds cannot be set for string/array type attributes"); + return ESP_ERR_INVALID_ARG; + } + VerifyOrReturnError(((current_attribute->val.type == min.type) && (current_attribute->val.type == max.type)), ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Cannot set bounds because of val type mismatch: expected: %d, min: %d, max: %d", + current_attribute->val.type, min.type, max.type)); + + EmberAfAttributeMetadata *matter_attribute= get_external_attribute_metadata(current_attribute); + if (!matter_attribute) { + ESP_LOGE(TAG, "Attribute Metadata is not found"); + return ESP_ERR_NOT_FOUND; + } + matter_attribute->mask |= ATTRIBUTE_FLAG_MIN_MAX; + current_attribute->flags |= ATTRIBUTE_FLAG_MIN_MAX; + + /* Set the default value again after setting the bounds and the flag */ + set_default_value_from_current_val(attribute, &min, &max); + return ESP_OK; +} + +esp_err_t get_bounds(attribute_t *attribute, esp_matter_attr_bounds_t *bounds) +{ + if (!attribute || !bounds) { + ESP_LOGE(TAG, "Attribute or bounds cannot be NULL"); + return ESP_ERR_INVALID_ARG; + } + _attribute_t *current_attribute = (_attribute_t *)attribute; + + EmberAfAttributeMetadata *matter_attribute= get_external_attribute_metadata(current_attribute); + if (!matter_attribute) { + ESP_LOGE(TAG, "Attribute Metadata is not found"); + return ESP_ERR_NOT_FOUND; + } + + if (!(matter_attribute->mask & ATTRIBUTE_FLAG_MIN_MAX)) { + ESP_LOGW(TAG, "Endpoint 0x%04" PRIX16 "'s Cluster 0x%08" PRIX32 "'s Attribute 0x%08" PRIX32 " has not set bounds", + current_attribute->endpoint_id, current_attribute->cluster_id, matter_attribute->attributeId); + return ESP_ERR_INVALID_ARG; + } + + if (matter_attribute->size > 2) { + get_attr_val_from_data(&bounds->min, matter_attribute->attributeType, matter_attribute->size, (uint8_t *)matter_attribute->defaultValue.ptrToMinMaxValue->minValue.ptrToDefaultValue, matter_attribute); + get_attr_val_from_data(&bounds->max, matter_attribute->attributeType, matter_attribute->size, (uint8_t *)matter_attribute->defaultValue.ptrToMinMaxValue->maxValue.ptrToDefaultValue, matter_attribute); + } else { + uint8_t value[2]; + uint16_t min_value = matter_attribute->defaultValue.ptrToMinMaxValue->minValue.defaultValue; + memcpy(value, &min_value, matter_attribute->size); + get_attr_val_from_data(&bounds->min, matter_attribute->attributeType, matter_attribute->size, value, matter_attribute); + uint16_t max_value = matter_attribute->defaultValue.ptrToMinMaxValue->maxValue.defaultValue; + memcpy(value, &max_value, matter_attribute->size); + get_attr_val_from_data(&bounds->max, matter_attribute->attributeType, matter_attribute->size, value, matter_attribute); + } + return ESP_OK; +} + +uint16_t get_flags(attribute_t *attribute) +{ + VerifyOrReturnValue(attribute, 0, ESP_LOGE(TAG, "Attribute cannot be NULL")); + _attribute_t *current_attribute = (_attribute_t *)attribute; + return current_attribute->flags; +} + +esp_err_t set_override_callback(attribute_t *attribute, callback_t callback) +{ + VerifyOrReturnError(attribute, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Attribute cannot be NULL")); + _attribute_t *current_attribute = (_attribute_t *)attribute; + + ESP_RETURN_ON_FALSE(!(current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY), ESP_ERR_NOT_SUPPORTED, TAG, + "Attribute is not managed by esp matter data model"); + + cluster_t *cluster = cluster::get(current_attribute->endpoint_id, current_attribute->cluster_id); + + if (current_attribute->val.type == ESP_MATTER_VAL_TYPE_ARRAY || + current_attribute->val.type == ESP_MATTER_VAL_TYPE_OCTET_STRING || + current_attribute->val.type == ESP_MATTER_VAL_TYPE_CHAR_STRING || + current_attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING || + current_attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_OCTET_STRING) { + // The override callback might allocate memory and we have no way to free the memory + // TODO: Add memory-safe override callback for these attribute types + ESP_LOGE(TAG, "Cannot set override callback for attribute 0x%" PRIX32 " on cluster 0x%" PRIX32, + current_attribute->attribute_id, cluster::get_id(cluster)); + return ESP_ERR_NOT_SUPPORTED; + } + current_attribute->override_callback = callback; + current_attribute->flags |= ATTRIBUTE_FLAG_OVERRIDE; + return ESP_OK; +} + +callback_t get_override_callback(attribute_t *attribute) +{ + VerifyOrReturnValue(attribute, NULL, ESP_LOGE(TAG, "Attribute cannot be NULL")); + _attribute_t *current_attribute = (_attribute_t *)attribute; + + VerifyOrReturnValue(!(current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY), NULL, ESP_LOGE(TAG, "Attribute is not managed by esp matter data model")); + + return current_attribute->override_callback; +} + +esp_err_t set_deferred_persistence(attribute_t *attribute) +{ + VerifyOrReturnError(attribute, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Attribute cannot be NULL")); + _attribute_t *current_attribute = (_attribute_t *)attribute; + + ESP_RETURN_ON_FALSE(!(current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY), ESP_ERR_NOT_SUPPORTED, TAG, + "Attribute is not managed by esp matter data model"); + + if (!(current_attribute->flags & ATTRIBUTE_FLAG_NONVOLATILE)) { + ESP_LOGE(TAG, "Attribute should be non-volatile to set a deferred persistence time"); + return ESP_ERR_INVALID_ARG; + } + current_attribute->flags |= ATTRIBUTE_FLAG_DEFERRED; + return ESP_OK; +} + +} /* attribute */ + +namespace command { +command_t *create(cluster_t *cluster, uint32_t command_id, uint8_t flags, callback_t callback) +{ + /* Find */ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + command_t *existing_command = get(cluster, command_id, flags); + if (existing_command) { + ESP_LOGW(TAG, "Command 0x%08" PRIX32 " on cluster 0x%08" PRIX32 " already exists. Not creating again.", command_id, + cluster::get_id(cluster)); + return existing_command; + } + + /* Allocate */ + _command_t *command = (_command_t *)esp_matter_mem_calloc(1, sizeof(_command_t)); + VerifyOrReturnValue(command, NULL, ESP_LOGE(TAG, "Couldn't allocate _command_t")); + + /* Set */ + command->command_id = command_id; + command->flags = flags; + command->callback = callback; + command->user_callback = NULL; + + /* Add */ + SinglyLinkedList<_command_t>::append(¤t_cluster->command_list, command); + return (command_t *)command; +} + +command_t *get(cluster_t *cluster, uint32_t command_id, uint16_t flags) +{ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + _command_t *current_command = (_command_t *)current_cluster->command_list; + while (current_command) { + if ((current_command->command_id == command_id) && (current_command->flags & flags)) { + break; + } + current_command = current_command->next; + } + return (command_t *)current_command; +} + +command_t *get_first(cluster_t *cluster) +{ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + return (command_t *)current_cluster->command_list; +} + +command_t *get_next(command_t *command) +{ + VerifyOrReturnValue(command, NULL, ESP_LOGE(TAG, "Command cannot be NULL")); + _command_t *current_command = (_command_t *)command; + return (command_t *)current_command->next; +} + +uint32_t get_id(command_t *command) +{ + VerifyOrReturnValue(command, kInvalidCommandId, ESP_LOGE(TAG, "Command cannot be NULL")); + _command_t *current_command = (_command_t *)command; + return current_command->command_id; +} + +callback_t get_callback(command_t *command) +{ + VerifyOrReturnValue(command, NULL, ESP_LOGE(TAG, "Command cannot be NULL")); + _command_t *current_command = (_command_t *)command; + return current_command->callback; +} + +callback_t get_user_callback(command_t *command) +{ + VerifyOrReturnValue(command, NULL, ESP_LOGE(TAG, "Command cannot be NULL")); + _command_t *current_command = (_command_t *)command; + return current_command->user_callback; +} + +void set_user_callback(command_t *command, callback_t user_callback) +{ + if (!command) { + ESP_LOGE(TAG, "Command cannot be NULL"); + } + _command_t *current_command = (_command_t *)command; + current_command->user_callback = user_callback; +} + +uint16_t get_flags(command_t *command) +{ + VerifyOrReturnValue(command, 0, ESP_LOGE(TAG, "Command cannot be NULL")); + _command_t *current_command = (_command_t *)command; + return current_command->flags; +} + +} /* command */ + +namespace event { + +event_t *create(cluster_t *cluster, uint32_t event_id) +{ + /* Find */ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + event_t *existing_event = get(cluster, event_id); + if (existing_event) { + ESP_LOGW(TAG, "Event 0x%08" PRIX32 " on cluster 0x%08" PRIX32 " already exists. Not creating again.", event_id, + cluster::get_id(cluster)); + return existing_event; + } + + /* Allocate */ + _event_t *event = (_event_t *)esp_matter_mem_calloc(1, sizeof(_event_t)); + VerifyOrReturnValue(event, NULL, ESP_LOGE(TAG, "Couldn't allocate _event_t")); + + /* Set */ + event->event_id = event_id; + + /* Add */ + SinglyLinkedList<_event_t>::append(¤t_cluster->event_list, event); + return (event_t *)event; +} + +event_t *get(cluster_t *cluster, uint32_t event_id) +{ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + _event_t *current_event = (_event_t *)current_cluster->event_list; + while (current_event) { + if (current_event->event_id == event_id) { + break; + } + current_event = current_event->next; + } + return (event_t *)current_event; +} + +event_t *get_first(cluster_t *cluster) +{ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + return (event_t *)current_cluster->event_list; +} + +event_t *get_next(event_t *event) +{ + VerifyOrReturnValue(event, NULL, ESP_LOGE(TAG, "Event cannot be NULL")); + _event_t *current_event = (_event_t *)event; + return (event_t *)current_event->next; +} + +uint32_t get_id(event_t *event) +{ + VerifyOrReturnValue(event, chip::kInvalidEventId, ESP_LOGE(TAG, "Event cannot be NULL")); + _event_t *current_event = (_event_t *)event; + return current_event->event_id; +} + +} /* event */ + + +namespace cluster { + +cluster_t *create(endpoint_t *endpoint, uint32_t cluster_id, uint8_t flags) +{ + /* Find */ + VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Endpoint cannot be NULL")); + VerifyOrReturnValue(((flags & CLUSTER_FLAG_SERVER) || (flags & CLUSTER_FLAG_CLIENT)), NULL, ESP_LOGE(TAG, "Server or client cluster flag not set")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + cluster_t *existing_cluster = get(endpoint, cluster_id); + if (existing_cluster) { + /* If a server already exists, do not create it again */ + _cluster_t *_existing_cluster = (_cluster_t *)existing_cluster; + // The member EmberAfCluster * in EmberAfEndpointType is const, do a non-const cast to change the mask. + EmberAfClusterMask *cluster_flags = (EmberAfClusterMask *)¤t_endpoint->endpoint_type->cluster[_existing_cluster->index].mask; + if ((*cluster_flags & CLUSTER_FLAG_SERVER) && (flags & CLUSTER_FLAG_SERVER)) { + ESP_LOGW(TAG, "Server Cluster 0x%08" PRIX32 " on endpoint 0x%04" PRIx16 " already exists. Not creating again.", cluster_id, + current_endpoint->endpoint_id); + return existing_cluster; + } + + /* If a client already exists, do not create it again */ + if ((*cluster_flags & CLUSTER_FLAG_CLIENT) && (flags & CLUSTER_FLAG_CLIENT)) { + ESP_LOGW(TAG, "Client Cluster 0x%08" PRIX32 " on endpoint 0x%04" PRIx16 " already exists. Not creating again.", cluster_id, + current_endpoint->endpoint_id); + return existing_cluster; + } + + /* The cluster already exists, but is of a different type. Just update the 'Set' part from below. */ + ESP_LOGI(TAG, "Cluster 0x%08" PRIX32 " on endpoint 0x%04" PRIx16 " already exists. Updating values.", cluster_id, + current_endpoint->endpoint_id); + *cluster_flags |= flags; + return existing_cluster; + } + + /* Allocate */ + _cluster_t *cluster = (_cluster_t *)esp_matter_mem_calloc(1, sizeof(_cluster_t)); + if (!cluster) { + ESP_LOGE(TAG, "Couldn't allocate _cluster_t"); + return NULL; + } + + /* Matter clusters */ + EmberAfCluster *matter_clusters = (EmberAfCluster *)current_endpoint->endpoint_type->cluster; + current_endpoint->cluster_count++; + cluster->index = current_endpoint->cluster_count - 1; + if (matter_clusters) { + matter_clusters = (EmberAfCluster *)esp_matter_mem_realloc(matter_clusters, current_endpoint->cluster_count * sizeof(EmberAfCluster)); + } else { + matter_clusters = (EmberAfCluster *)esp_matter_mem_calloc(1, current_endpoint->cluster_count * sizeof(EmberAfCluster)); + } + if (!matter_clusters) { + ESP_LOGE(TAG, "Couldn't allocate EmberAfCluster"); + return NULL; + } + current_endpoint->endpoint_type->cluster = matter_clusters; + + /* Set */ + EmberAfCluster *matter_cluster = (EmberAfCluster *)¤t_endpoint->endpoint_type->cluster[cluster->index]; + cluster->endpoint_id = current_endpoint->endpoint_id; + + matter_cluster->clusterId = cluster_id; + matter_cluster->mask = flags; + matter_cluster->clusterSize = 0; + matter_cluster->attributeCount = 0; + matter_cluster->functions = NULL; + + /* Add */ + SinglyLinkedList<_cluster_t>::append(¤t_endpoint->cluster_list, cluster); + return (cluster_t *)cluster; +} + +esp_err_t destroy(cluster_t *cluster) +{ + VerifyOrReturnError(cluster, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Cluster cannot be NULL")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + + /* Parse and delete all commands */ + SinglyLinkedList<_command_t>::delete_list(¤t_cluster->command_list); + + /* Parse and delete all attributes */ + _attribute_base_t *attribute = current_cluster->attribute_list; + while (attribute) { + _attribute_base_t *next_attribute = attribute->next; + attribute::destroy((attribute_t *)attribute); + attribute = next_attribute; + } + + /* Parse and delete all events */ + SinglyLinkedList<_event_t>::delete_list(¤t_cluster->event_list); + + /* Free matter_attributes if allocated */ + if (current_cluster->matter_attributes) { + esp_matter_mem_free(current_cluster->matter_attributes); + current_cluster->matter_attributes = NULL; + } + + /* Free */ + esp_matter_mem_free(current_cluster); + return ESP_OK; +} + +cluster_t *get(endpoint_t *endpoint, uint32_t cluster_id) +{ + VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Endpoint cannot be NULL")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + _cluster_t *current_cluster = (_cluster_t *)current_endpoint->cluster_list; + + uint8_t cluster_index = 0; + for (cluster_index = 0; cluster_index < current_endpoint->cluster_count; cluster_index++) { + if (current_endpoint->endpoint_type->cluster[cluster_index].clusterId == cluster_id) { + break; + } + } + if (cluster_index == current_endpoint->cluster_count) { + ESP_LOGD(TAG, "Cluster not found"); + return NULL; + } + + while (current_cluster) { + if (current_cluster->index == cluster_index) { + break; + } + current_cluster = current_cluster->next; + } + return (cluster_t *)current_cluster; +} + +cluster_t *get(uint16_t endpoint_id, uint32_t cluster_id) +{ + endpoint_t *endpoint = endpoint::get(endpoint_id); + return get(endpoint, cluster_id); +} + +cluster_t *get_first(endpoint_t *endpoint) +{ + VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Endpoint cannot be NULL")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + return (cluster_t *)current_endpoint->cluster_list; +} + +cluster_t *get_next(cluster_t *cluster) +{ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + return (cluster_t *)current_cluster->next; +} + +uint32_t get_id(cluster_t *cluster) +{ + VerifyOrReturnValue(cluster, kInvalidClusterId, ESP_LOGE(TAG, "Cluster cannot be NULL")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + endpoint_t *endpoint = endpoint::get(current_cluster->endpoint_id); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + return current_endpoint->endpoint_type->cluster[current_cluster->index].clusterId; +} + +void *get_delegate_impl(cluster_t *cluster) +{ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + return current_cluster->delegate_pointer; +} + +esp_err_t set_plugin_server_init_callback(cluster_t *cluster, plugin_server_init_callback_t callback) +{ + VerifyOrReturnError(cluster, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Cluster cannot be NULL")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + current_cluster->plugin_server_init_callback = callback; + return ESP_OK; +} + +plugin_server_init_callback_t get_plugin_server_init_callback(cluster_t *cluster) +{ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + return current_cluster->plugin_server_init_callback; +} + +esp_err_t set_delegate_and_init_callback(cluster_t *cluster, delegate_init_callback_t callback, void *delegate) +{ + VerifyOrReturnError(cluster, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Cluster cannot be NULL")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + current_cluster->delegate_init_callback = callback; + current_cluster->delegate_pointer = delegate; + return ESP_OK; +} + +delegate_init_callback_t get_delegate_init_callback(cluster_t *cluster) +{ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + return current_cluster->delegate_init_callback; +} + +esp_err_t set_add_bounds_callback(cluster_t *cluster, add_bounds_callback_t callback) +{ + VerifyOrReturnError(cluster, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Cluster cannot be NULL")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + current_cluster->add_bounds_callback = callback; + return ESP_OK; +} + +add_bounds_callback_t get_add_bounds_callback(cluster_t *cluster) +{ + VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + return current_cluster->add_bounds_callback; +} + +esp_err_t add_function_list(cluster_t *cluster, const function_generic_t *function_list, int function_flags) +{ + VerifyOrReturnError(cluster, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Cluster cannot be NULL")); + _cluster_t *current_cluster = (_cluster_t *)cluster; + + endpoint_t *endpoint = endpoint::get(current_cluster->endpoint_id); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + EmberAfCluster *matter_clusters = (EmberAfCluster *)current_endpoint->endpoint_type->cluster; + matter_clusters[current_cluster->index].mask |= function_flags; + matter_clusters[current_cluster->index].functions = (const EmberAfGenericClusterFunction *)function_list; + return ESP_OK; +} + +} /* cluster */ + +namespace endpoint { + +endpoint_t *create(node_t *node, uint8_t flags, void *priv_data) +{ + /* Find */ + VerifyOrReturnValue(node, NULL, ESP_LOGE(TAG, "Node cannot be NULL")); + _node_t *current_node = (_node_t *)node; + + VerifyOrReturnValue(get_count(node) < CONFIG_ESP_MATTER_MAX_DYNAMIC_ENDPOINT_COUNT, NULL, ESP_LOGE(TAG, "Dynamic endpoint count cannot be greater than CONFIG_ESP_MATTER_MAX_DYNAMIC_ENDPOINT_COUNT:%u", + CONFIG_ESP_MATTER_MAX_DYNAMIC_ENDPOINT_COUNT)); + + /* Allocate */ + _endpoint_t *endpoint = (_endpoint_t *)esp_matter_mem_calloc(1, sizeof(_endpoint_t)); + VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Couldn't allocate _endpoint_t")); + + endpoint->endpoint_type = (EmberAfEndpointType *)esp_matter_mem_calloc(1, sizeof(EmberAfEndpointType)); + if (!endpoint->endpoint_type) { + ESP_LOGE(TAG, "Couldn't allocate EmberAfEndpointType"); + esp_matter_mem_free(endpoint); + return NULL; + } + + /* Set */ + endpoint->endpoint_id = current_node->min_unused_endpoint_id++; + endpoint->device_type_count = 0; + endpoint->parent_endpoint_id = chip::kInvalidEndpointId; + endpoint->flags = flags; + endpoint->priv_data = priv_data; + /* Store */ + if (esp_matter::is_started()) { + node::store_min_unused_endpoint_id(); + } + + /* Add */ + SinglyLinkedList<_endpoint_t>::append(¤t_node->endpoint_list, endpoint); + return (endpoint_t *)endpoint; +} + +endpoint_t *resume(node_t *node, uint8_t flags, uint16_t endpoint_id, void *priv_data) +{ + /* Find */ + VerifyOrReturnValue(node, NULL, ESP_LOGE(TAG, "Node cannot be NULL")); + _node_t *current_node = (_node_t *)node; + _endpoint_t *previous_endpoint = NULL; + _endpoint_t *current_endpoint = current_node->endpoint_list; + while (current_endpoint) { + VerifyOrReturnValue(current_endpoint->endpoint_id != endpoint_id, NULL, ESP_LOGE(TAG, "Could not resume an endpoint that has been added to the node")); + previous_endpoint = current_endpoint; + current_endpoint = current_endpoint->next; + } + + /* Check */ + VerifyOrReturnError(endpoint_id < current_node->min_unused_endpoint_id, NULL, ESP_LOGE(TAG, "The endpoint_id of the resumed endpoint should have been used")); + + /* Allocate */ + _endpoint_t *endpoint = (_endpoint_t *)esp_matter_mem_calloc(1, sizeof(_endpoint_t)); + VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Couldn't allocate _endpoint_t")); + + endpoint->endpoint_type = (EmberAfEndpointType *)esp_matter_mem_calloc(1, sizeof(EmberAfEndpointType)); + if (!endpoint->endpoint_type) { + ESP_LOGE(TAG, "Couldn't allocate EmberAfEndpointType"); + esp_matter_mem_free(endpoint); + return NULL; + } + + /* Set */ + endpoint->endpoint_id = endpoint_id; + endpoint->device_type_count = 0; + endpoint->flags = flags; + endpoint->priv_data = priv_data; + + /* Add */ + if (previous_endpoint == NULL) { + current_node->endpoint_list = endpoint; + } else { + previous_endpoint->next = endpoint; + } + + return (endpoint_t *)endpoint; +} + +esp_err_t destroy(node_t *node, endpoint_t *endpoint) +{ + VerifyOrReturnError((node && endpoint), ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Node or endpoint cannot be NULL")); + _node_t *current_node = (_node_t *)node; + _endpoint_t *_endpoint = (_endpoint_t *)endpoint; + + VerifyOrReturnError((_endpoint->flags & ENDPOINT_FLAG_DESTROYABLE), ESP_FAIL, ESP_LOGE(TAG, "This endpoint cannot be deleted since the ENDPOINT_FLAG_DESTROYABLE is not set")); + + /* Disable */ + disable(endpoint); + + /* Find current endpoint */ + _endpoint_t *current_endpoint = current_node->endpoint_list; + _endpoint_t *previous_endpoint = NULL; + while (current_endpoint) { + if (current_endpoint == _endpoint) { + break; + } + previous_endpoint = current_endpoint; + current_endpoint = current_endpoint->next; + } + VerifyOrReturnError(current_endpoint != NULL, ESP_FAIL, ESP_LOGE(TAG, "Could not find the endpoint to delete")); + + /* Parse and delete all clusters */ + _cluster_t *cluster = current_endpoint->cluster_list; + while (cluster) { + _cluster_t *next_cluster = cluster->next; + cluster::destroy((cluster_t *)cluster); + cluster = next_cluster; + /* Move cluster_list to find the remain cluster */ + current_endpoint->cluster_list = cluster; + } + + /* Free endpoint_type after freeing cluster_list */ + { + /* Free all clusters in endpoint_type */ + EmberAfEndpointType *endpoint_type = current_endpoint->endpoint_type; + VerifyOrReturnError(endpoint_type, ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "endpoint %" PRIu16 "'s endpoint_type is NULL", current_endpoint->endpoint_id)); + int cluster_count = endpoint_type->clusterCount; + for (int cluster_index = 0; cluster_index < cluster_count; cluster_index++) { + /* Free commands */ + if (endpoint_type->cluster[cluster_index].acceptedCommandList) { + esp_matter_mem_free((void *)endpoint_type->cluster[cluster_index].acceptedCommandList); + } + if (endpoint_type->cluster[cluster_index].generatedCommandList) { + esp_matter_mem_free((void *)endpoint_type->cluster[cluster_index].generatedCommandList); + } + /* Free events */ + if (endpoint_type->cluster[cluster_index].eventList) { + esp_matter_mem_free((void *)endpoint_type->cluster[cluster_index].eventList); + } + } + esp_matter_mem_free((void *)endpoint_type->cluster); + + /* Free data versions */ + if (current_endpoint->data_versions_ptr) { + esp_matter_mem_free(current_endpoint->data_versions_ptr); + current_endpoint->data_versions_ptr = NULL; + } + + /* Free device types */ + if (current_endpoint->device_types_ptr) { + esp_matter_mem_free(current_endpoint->device_types_ptr); + current_endpoint->device_types_ptr = NULL; + } + + /* Free endpoint type */ + esp_matter_mem_free(endpoint_type); + current_endpoint->endpoint_type = NULL; + } + + /* Remove from list */ + if (previous_endpoint == NULL) { + current_node->endpoint_list = current_endpoint->next; + } else { + previous_endpoint->next = current_endpoint->next; + } + + /* Free */ + if (current_endpoint->identify != NULL) { + chip::Platform::Delete(current_endpoint->identify); + current_endpoint->identify = NULL; + } + esp_matter_mem_free(current_endpoint); + + // resize the group data provider to match the new endpoint count + resize_group_data_provider(); + + return ESP_OK; +} + +endpoint_t *get(node_t *node, uint16_t endpoint_id) +{ + VerifyOrReturnValue(node, NULL, ESP_LOGE(TAG, "Node cannot be NULL")); + _node_t *current_node = (_node_t *)node; + _endpoint_t *current_endpoint = (_endpoint_t *)current_node->endpoint_list; + while (current_endpoint) { + if (current_endpoint->endpoint_id == endpoint_id) { + break; + } + current_endpoint = current_endpoint->next; + } + return (endpoint_t *)current_endpoint; +} + +endpoint_t *get(uint16_t endpoint_id) +{ + node_t *node = node::get(); + return get(node, endpoint_id); +} + + +endpoint_t *get_first(node_t *node) +{ + VerifyOrReturnValue(node, NULL, ESP_LOGE(TAG, "Node cannot be NULL")); + _node_t *current_node = (_node_t *)node; + return (endpoint_t *)current_node->endpoint_list; +} + +endpoint_t *get_next(endpoint_t *endpoint) +{ + VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Endpoint cannot be NULL")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + return (endpoint_t *)current_endpoint->next; +} + +uint16_t get_count(node_t *node) +{ + VerifyOrReturnValue(node, 0, ESP_LOGE(TAG, "Node cannot be NULL")); + uint16_t count = 0; + endpoint_t *endpoint = get_first(node); + while (endpoint) { + count++; + endpoint = get_next(endpoint); + } + return count; + +} + +uint16_t get_id(endpoint_t *endpoint) +{ + VerifyOrReturnValue(endpoint, kInvalidEndpointId, ESP_LOGE(TAG, "Endpoint cannot be NULL")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + return current_endpoint->endpoint_id; +} + +esp_err_t add_device_type(endpoint_t *endpoint, uint32_t device_type_id, uint8_t device_type_version) +{ + VerifyOrReturnError(endpoint, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Endpoint cannot be NULL")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + VerifyOrReturnError(current_endpoint->device_type_count < ESP_MATTER_MAX_DEVICE_TYPE_COUNT, ESP_FAIL, + ESP_LOGE(TAG, "Could not add a new device-type:%" PRIu32 " to the endpoint", device_type_id)); + current_endpoint->device_type_ids[current_endpoint->device_type_count] = device_type_id; + current_endpoint->device_type_versions[current_endpoint->device_type_count] = device_type_version; + current_endpoint->device_type_count++; + return ESP_OK; +} + +uint32_t *get_device_type_ids(endpoint_t *endpoint, uint8_t *device_type_count_ptr) +{ + VerifyOrReturnValue((endpoint && device_type_count_ptr), NULL, ESP_LOGE(TAG, "Endpoint and device type count pointer cannot be NULL")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + *device_type_count_ptr = current_endpoint->device_type_count; + return current_endpoint->device_type_ids; +} + +uint8_t *get_device_type_versions(endpoint_t *endpoint, uint8_t *device_type_count_ptr) +{ + VerifyOrReturnValue((endpoint && device_type_count_ptr), NULL, ESP_LOGE(TAG, "Endpoint and device type count pointer cannot be NULL")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + *device_type_count_ptr = current_endpoint->device_type_count; + return current_endpoint->device_type_versions; +} + +esp_err_t set_parent_endpoint(endpoint_t *endpoint, endpoint_t *parent_endpoint) +{ + VerifyOrReturnError((endpoint && parent_endpoint), ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Endpoint or parent_endpoint cannot be NULL")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + _endpoint_t *current_parent_endpoint = (_endpoint_t *)parent_endpoint; + current_endpoint->parent_endpoint_id = current_parent_endpoint->endpoint_id; + return ESP_OK; +} + +void *get_priv_data(uint16_t endpoint_id) +{ + endpoint_t *endpoint = get(endpoint_id); + VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Endpoint not found")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + return current_endpoint->priv_data; +} + +esp_err_t set_priv_data(uint16_t endpoint_id, void *priv_data) +{ + endpoint_t *endpoint = get(endpoint_id); + VerifyOrReturnError(endpoint, ESP_ERR_NOT_FOUND, ESP_LOGE(TAG, "Endpoint not found")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + current_endpoint->priv_data = priv_data; + return ESP_OK; +} + +esp_err_t set_identify(uint16_t endpoint_id, void *identify) +{ + endpoint_t *endpoint = get(endpoint_id); + VerifyOrReturnError(endpoint, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Endpoint not found")); + _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; + current_endpoint->identify = (Identify *)identify; + return ESP_OK; +} + +} /* endpoint */ + +namespace node { + +node_t *create_raw() +{ + VerifyOrReturnValue(!node, (node_t*) node, ESP_LOGE(TAG, "Node already exists")); + node = (_node_t *)esp_matter_mem_calloc(1, sizeof(_node_t)); + VerifyOrReturnValue(node, NULL, ESP_LOGE(TAG, "Couldn't allocate _node_t")); + return (node_t *)node; +} + +esp_err_t destroy_raw() +{ + VerifyOrReturnError(node, ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "NULL node cannot be destroyed")); + _node_t *current_node = (_node_t *)node; + esp_matter_mem_free(current_node); + node = NULL; + return ESP_OK; +} + +node_t *get() +{ + return (node_t *)node; +} + +esp_err_t destroy() +{ + esp_err_t err = ESP_OK; + node_t *current_node = get(); + VerifyOrReturnError(current_node, ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "Node cannot be NULL")); + + attribute::set_callback(nullptr); + identification::set_callback(nullptr); + + endpoint_t *current_endpoint = endpoint::get_first(current_node); + endpoint_t *next_endpoint = nullptr; + while (current_endpoint != nullptr) { + next_endpoint = endpoint::get_next(current_endpoint); + // Endpoints should have destroyable flag set to true before destroying + ((_endpoint_t *)current_endpoint)->flags |= ENDPOINT_FLAG_DESTROYABLE; + err = endpoint::destroy((node_t *)current_node, current_endpoint); + VerifyOrDo(err == ESP_OK, ESP_LOGE(TAG, "Failed to destroy endpoint")); + + current_endpoint = next_endpoint; + } + + return destroy_raw(); +} + +// Treat 0xFFFF'FFFF as wildcard cluster +static inline bool is_wildcard_cluster_id(uint32_t cluster_id) +{ + return cluster_id == chip::kInvalidClusterId; +} + +// Treat 0xFFFF as wildcard endpoint +static inline bool is_wildcard_endpoint_id(uint16_t endpoint_id) +{ + return endpoint_id == chip::kInvalidEndpointId; +} + +/** + * @brief Get the number of clusters that match the given flags + * + * @param endpoint_id: The endpoint ID to check, 0xFFFF is treated as wildcard endpoint id + * @param cluster_id: The cluster ID to check, 0xFFFF is treated as wildcard cluster id + * @param cluster_flags: The flags to check + * @return The number of clusters that match the given flags + */ +static uint32_t get_cluster_count(uint32_t endpoint_id, uint32_t cluster_id, uint8_t cluster_flags) +{ + uint32_t count = 0; + node_t *node = get(); + VerifyOrReturnValue(node, count, ESP_LOGE(TAG, "Node cannot be NULL")); + + // lambda to check if cluster matches flags and return 1 if it does, 0 otherwise + auto check_cluster_flags = [cluster_flags](const endpoint_t *endpoint, const cluster_t *cluster) -> uint32_t { + if (cluster && endpoint) { + const _endpoint_t *_endpoint = (_endpoint_t *)endpoint; + const _cluster_t *_cluster = (_cluster_t *)cluster; + EmberAfClusterMask flags = _endpoint->endpoint_type->cluster[_cluster->index].mask; + return (flags & cluster_flags) ? 1 : 0; + } + return 0; + }; + + // lambda to count all matching clusters for an endpoint + auto get_count_on_all_clusters = [&check_cluster_flags](endpoint_t *endpoint) -> uint32_t { + uint32_t result = 0; + if (!endpoint) return result; + + cluster_t *cluster = cluster::get_first(endpoint); + while (cluster) { + result += check_cluster_flags(endpoint, cluster); + cluster = cluster::get_next(cluster); + } + return result; + }; + + // lambda to find and count a specific cluster + auto get_count_on_specific_cluster = [&check_cluster_flags](const endpoint_t *endpoint, uint32_t cluster_id) -> uint32_t { + if (!endpoint) return 0; + cluster_t *cluster = cluster::get((endpoint_t *)endpoint, cluster_id); + return check_cluster_flags(endpoint, cluster); + }; + + // Case 1: Wildcard endpoint + if (is_wildcard_endpoint_id(endpoint_id)) { + endpoint_t *endpoint = endpoint::get_first(node); + while (endpoint) { + // Case 1.1: Wildcard cluster - count all clusters with matching flags + if (is_wildcard_cluster_id(cluster_id)) { + count += get_count_on_all_clusters(endpoint); + } + // Case 1.2: Specific cluster - count if it exists and has matching flags + else { + count += get_count_on_specific_cluster(endpoint, cluster_id); + } + endpoint = endpoint::get_next(endpoint); + } + } + // Case 2: Specific endpoint + else { + endpoint_t *endpoint = endpoint::get(endpoint_id); + if (!endpoint) { + return count; + } + + // Case 2.1: Wildcard cluster - count all clusters with matching flags + if (is_wildcard_cluster_id(cluster_id)) { + count += get_count_on_all_clusters(endpoint); + } + // Case 2.2: Specific cluster - count if it exists and has matching flags + else { + count += get_count_on_specific_cluster(endpoint, cluster_id); + } + } + + return count; +} + +uint32_t get_server_cluster_endpoint_count(uint32_t cluster_id) +{ + return get_cluster_count(chip::kInvalidEndpointId, cluster_id, CLUSTER_FLAG_SERVER); +} + +uint32_t get_client_cluster_endpoint_count(uint32_t cluster_id) +{ + return get_cluster_count(chip::kInvalidEndpointId, cluster_id, CLUSTER_FLAG_CLIENT); +} + +} /* node */ +} /* esp_matter */ diff --git a/components/esp_matter/data_model/esp_matter_data_model.h b/components/esp_matter/data_model/esp_matter_data_model.h new file mode 100644 index 000000000..f19a79d67 --- /dev/null +++ b/components/esp_matter/data_model/esp_matter_data_model.h @@ -0,0 +1,958 @@ +// 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. + +#pragma once +#include +#include +#include "app/ConcreteCommandPath.h" +#include "app/util/af-types.h" +#include "lib/core/TLVReader.h" + +#define ESP_MATTER_NVS_PART_NAME CONFIG_ESP_MATTER_NVS_PART_NAME + +using chip::app::ConcreteCommandPath; +using chip::TLV::TLVReader; +using chip::DeviceLayer::ChipDeviceEvent; + +namespace esp_matter { + +/** Generic handle */ +typedef size_t handle_t; +/** Node handle */ +typedef handle_t node_t; +/** Endpoint handle */ +typedef handle_t endpoint_t; +/** Cluster handle */ +typedef handle_t cluster_t; +/** Attribute handle */ +typedef handle_t attribute_t; +/** Command handle */ +typedef handle_t command_t; +/** Event handle */ +typedef handle_t event_t; + +/** Endpoint flags */ +typedef enum endpoint_flags { + /** No specific flags */ + ENDPOINT_FLAG_NONE = 0x00, + /** The endpoint can be destroyed using `endpoint::destroy()` */ + ENDPOINT_FLAG_DESTROYABLE = 0x01, + /** The endpoint is a bridged node */ + ENDPOINT_FLAG_BRIDGE = 0x02, +} endpoint_flags_t; + +/** Cluster flags */ +typedef enum cluster_flags { + /** No specific flags */ + CLUSTER_FLAG_NONE = 0x00, + /** The cluster has an init function (function_flag) */ + CLUSTER_FLAG_INIT_FUNCTION = MATTER_CLUSTER_FLAG_INIT_FUNCTION, /* 0x01 */ + /** The cluster has an attribute changed function (function_flag) */ + CLUSTER_FLAG_ATTRIBUTE_CHANGED_FUNCTION = MATTER_CLUSTER_FLAG_ATTRIBUTE_CHANGED_FUNCTION, /* 0x02 */ + /** The cluster has a shutdown function (function_flag) */ + CLUSTER_FLAG_SHUTDOWN_FUNCTION = MATTER_CLUSTER_FLAG_SHUTDOWN_FUNCTION, /* 0x10 */ + /** The cluster has a pre attribute changed function (function_flag) */ + CLUSTER_FLAG_PRE_ATTRIBUTE_CHANGED_FUNCTION = MATTER_CLUSTER_FLAG_PRE_ATTRIBUTE_CHANGED_FUNCTION, /* 0x20 */ + /** The cluster is a server cluster */ + CLUSTER_FLAG_SERVER = MATTER_CLUSTER_FLAG_SERVER, /* 0x40 */ + /** The cluster is a client cluster */ + CLUSTER_FLAG_CLIENT = MATTER_CLUSTER_FLAG_CLIENT, /* 0x80 */ +} cluster_flags_t; + +/** Attribute flags */ +typedef enum attribute_flags { + /** No specific flags */ + ATTRIBUTE_FLAG_NONE = 0x00, + /** The attribute is writable and can be directly changed by clients */ + ATTRIBUTE_FLAG_WRITABLE = MATTER_ATTRIBUTE_FLAG_WRITABLE, /* 0x01 */ + /** The attribute is non volatile and its value will be stored in NVS */ + ATTRIBUTE_FLAG_NONVOLATILE = MATTER_ATTRIBUTE_FLAG_NONVOLATILE, /* 0x02 */ + /** The attribute has bounds */ + ATTRIBUTE_FLAG_MIN_MAX = MATTER_ATTRIBUTE_FLAG_MIN_MAX, /* 0x04 */ + ATTRIBUTE_FLAG_MUST_USE_TIMED_WRITE = MATTER_ATTRIBUTE_FLAG_MUST_USE_TIMED_WRITE, /* 0x08 */ + /** The attribute uses external storage for its value. If attributes + have this flag enabled, as all of them are stored in the ESP Matter database. */ + ATTRIBUTE_FLAG_EXTERNAL_STORAGE = MATTER_ATTRIBUTE_FLAG_EXTERNAL_STORAGE, /* 0x10 */ + ATTRIBUTE_FLAG_SINGLETON = MATTER_ATTRIBUTE_FLAG_SINGLETON, /* 0x20 */ + ATTRIBUTE_FLAG_NULLABLE = MATTER_ATTRIBUTE_FLAG_NULLABLE, /* 0x40 */ + /** The attribute read and write are overridden. The attribute value will be fetched from and will be updated using + the override callback. The value of this attribute is not maintained internally. */ + ATTRIBUTE_FLAG_OVERRIDE = ATTRIBUTE_FLAG_NULLABLE << 1, /* 0x80 */ + /** The attribute is non-volatile but its value will be changed frequently. If an attribute has this flag, its value + will not be written to flash immediately. A timer will be started and the attribute value will be written after + timeout. */ + ATTRIBUTE_FLAG_DEFERRED = ATTRIBUTE_FLAG_NULLABLE << 2, /* 0x100 */ + /** The attribute is managed internally and is not stored in the ESP Matter database. + If not set, ATTRIBUTE_FLAG_EXTERNAL_STORAGE flag will be enabled. */ + ATTRIBUTE_FLAG_MANAGED_INTERNALLY = ATTRIBUTE_FLAG_NULLABLE << 3, /* 0x200 */ +} attribute_flags_t; + +/** Command flags */ +typedef enum command_flags { + /** No specific flags */ + COMMAND_FLAG_NONE = 0x00, + /** The command is not a standard command */ + COMMAND_FLAG_CUSTOM = 0x01, + /** The command is client generated */ + COMMAND_FLAG_ACCEPTED = 0x02, + /** The command is server generated */ + COMMAND_FLAG_GENERATED = 0x04, +} command_flags_t; + +namespace node { + +/** Create raw node + * + * @return Node handle on success. + * @return NULL in case of failure. + */ +node_t *create_raw(); + +/** Destroy raw node + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t destroy_raw(); + +/** Get node + * + * @return Node handle on success. + * @return NULL in case of failure. + */ +node_t *get(); + +/** Destroy node + * + * This will destroy the node and all the endpoints, clusters, attributes, commands and events associated with it. + * + * @note: Call this function only if matter is not running. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t destroy(); + +/** Get the endpoint count for a server cluster + * + * Get the number of endpoints that have the given cluster ID as a server cluster. + * + * @param[in] cluster_id Cluster ID. + * + * @return Endpoint count on success. + * @return 0 in case of failure or if not found on any endpoint. + */ + +uint32_t get_server_cluster_endpoint_count(uint32_t cluster_id); + +/** Get the endpoint count for a client cluster + * + * Get the number of endpoints that have the given cluster ID as a client cluster. + * + * @param[in] cluster_id Cluster ID. + * + * @return Endpoint count on success. + * @return 0 in case of failure or if not found on any endpoint. + */ +uint32_t get_client_cluster_endpoint_count(uint32_t cluster_id); + +} /* node */ + +namespace endpoint { + +/** Create endpoint + * + * This will create a new endpoint with a unique endpoint_id and add the endpoint to the node. + * + * @param[in] node Node handle. + * @param[in] flags Bitmap of `endpoint_flags_t`. + * @param[in] priv_data (Optional) Private data associated with the endpoint. This will be passed to the + * attribute_update and identify callbacks. It should stay allocated throughout the lifetime of the device. + * + * @return Endpoint handle on success. + * @return NULL in case of failure. + */ +endpoint_t *create(node_t *node, uint8_t flags, void *priv_data); + +/** Resume endpoint + * + * This will resume an endpoint after reboot and add it to the node. + * + * @param[in] node Node handle. + * @param[in] flags Bitmap of `endpoint_flags_t`. + * @param[in] endpoint_id Endpoint ID of the endpoint resumed. + * @param[in] priv_data (Optional) Private data associated with the endpoint. This will be passed to the + * attribute_update and identify callbacks. It should stay allocated throughout the lifetime of the device. + * + * @return Endpoint handle on success. + * @return NULL in case of failure. + */ +endpoint_t *resume(node_t *node, uint8_t flags, uint16_t endpoint_id, void *priv_data); + +/** Destroy endpoint + * + * This will destroy the endpoint which has been created and added to the node. It also destroys the associated + * clusters, attributes and commands. + * + * @param[in] node Node handle. + * @param[in] endpoint Endpoint handle. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t destroy(node_t *node, endpoint_t *endpoint); + +/** Get endpoint + * + * Get the endpoint present on the node. + * + * @param[in] node Node handle. + * @param[in] endpoint_id Endpoint ID of the endpoint. + * + * @return Endpoint handle on success. + * @return NULL in case of failure. + */ +endpoint_t *get(node_t *node, uint16_t endpoint_id); + +/** Get endpoint + * + * Get the endpoint present on the node. + * + * @param[in] endpoint_id Endpoint ID of the endpoint. + * + * @return Endpoint handle on success. + * @return NULL in case of failure. + */ +endpoint_t *get(uint16_t endpoint_id); + +/** Get first endpoint + * + * Get the first endpoint present on the node. + * + * @param[in] node Node handle. + * + * @return Endpoint handle on success. + * @return NULL in case of failure. + */ +endpoint_t *get_first(node_t *node); + +/** Get next endpoint + * + * Get the next endpoint present on the node. + * + * @param[in] endpoint Endpoint handle. + * + * @return Endpoint handle on success. + * @return NULL in case of failure. + */ +endpoint_t *get_next(endpoint_t *endpoint); + +/** Get endpoint count + * + * Get the endpoint count present on the node. + * + * @param[in] node Node handle. + * + * @return Endpoint count on success. + * @return 0 in case of failure. + */ +uint16_t get_count(node_t *node); + +/** Get endpoint ID + * + * Get the endpoint ID for the endpoint. + * + * @param[in] endpoint Endpoint handle. + * + * @return Endpoint ID on success. + * @return Invalid Endpoint ID (0xFFFF) in case of failure. + */ +uint16_t get_id(endpoint_t *endpoint); + +/** Add device type ID and verision + * + * Add the device type ID and version for the endpoint. + * + * @param[in] endpoint Endpoint handle. + * @param[in] device_type_id Device type ID. + * @param[in] device_type_version Device type version. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t add_device_type(endpoint_t *endpoint, uint32_t device_type_id, uint8_t device_type_version); + +/** Get device type ID array + * + * Get the device type ID array for the endpoint. This array is aligned with the device type version array. + * + * @param[in] endpoint Endpoint handle. + * @param[out] device_type_count_ptr the pointer of device type ID array length. + * + * @return device type ID array on success. + * @return NULL when the endpoint or the device_type_count_ptr is NULL. + */ +uint32_t *get_device_type_ids(endpoint_t *endpoint, uint8_t *device_type_count_ptr); + +/** Get device type version array + * + * Get the device type version array for the endpoint. This array is aligned with the device type ID array. + * + * @param[in] endpoint Endpoint handle. + * @param[out] device_type_count_ptr the pointer of device type version array length. + * + * @return device type version array on success. + * @return NULL when the endpoint or the device_type_count_ptr is NULL. + */ +uint8_t *get_device_type_versions(endpoint_t *endpoint, uint8_t *device_type_count_ptr); + +/** Set parent endpoint + * + * Set the parent endpoint. This is useful in correctly setting the parts_list attribute for the parent, when the + * parent is a composite endpoint. + * + * @param[in] endpoint Endpoint handle. + * @param[out] parent_endpoint Parent endpoint handle. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t set_parent_endpoint(endpoint_t *endpoint, endpoint_t *parent_endpoint); + +/** Get private data + * + * Get the private data passed while creating the endpoint. + * + * @param[in] endpoint_id Endpoint ID of the endpoint. + * + * @return Private data on success. + * @return NULL in case of failure. + */ +void *get_priv_data(uint16_t endpoint_id); + +/** Set private data + * + * Set the private data after creating the endpoint. + * + * @param[in] endpoint_id Endpoint ID of the endpoint. + * @param[in] priv_data Private data of the endpoint. + * + * @return ESP_OK on success. + * @return ESP_ERR_INVALID_STATE or ESP_ERR_NOT_FOUND in case of failure. + */ +esp_err_t set_priv_data(uint16_t endpoint_id, void *priv_data); + +/** Set identify + * + * Set identify to the endpoint. The identify pointer should be dynamically allocated using 'chip::Platform::New()', + * and once Matter stack is done using it, it will be freed by 'chip::Platform::Delete()'. + * + * @param[in] endpoint_id Endpoint id. + * @param[in] identify Identify pointer. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t set_identify(uint16_t endpoint_id, void *identify); + +/** Enable endpoint + * + * Enable the endpoint which has been previously created. + * + * @note: This API only needs to be called for endpoints created after calling esp_matter::start(). It should be + * called after all the clusters, attributes and commands have been added to the created endpoint. + * + * @param[in] endpoint Endpoint handle. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t enable(endpoint_t *endpoint); + +} /* endpoint */ + +namespace cluster { + +/** Cluster plugin server init callback + * + * This callback will be called when the endpoints are initialised. This should be set to upstream's + * `MatterPluginServerInitCallback` API, if it exists. + */ +typedef void (*plugin_server_init_callback_t)(); + +/** Cluster delegate server init callback + * + * This callback will be called when the endpoints are initialised. + */ +typedef void (*delegate_init_callback_t)(void *ptr, uint16_t endpoint_id); + +/** Cluster add bounds callback + * + * This callback will be called when the endpoints are initialised. + */ +typedef void (*add_bounds_callback_t)(cluster_t *cluster); + +/** Generic function + * + * This can be used to add additional functions based on `cluster_flags_t`. + */ +typedef void (*function_generic_t)(); + +/** Create cluster + * + * This will create a new cluster and add it to the endpoint. + * + * @param[in] endpoint Endpoint handle. + * @param[in] cluster_id Cluster ID for the cluster. + * @param[in] flags Bitmap of `cluster_flags_t`. + * + * @return Cluster handle on success. + * @return NULL in case of failure. + */ +cluster_t *create(endpoint_t *endpoint, uint32_t cluster_id, uint8_t flags); + +/** Destroy cluster + * + * This will destroy the cluster which has been created and added to the endpoint. It also destroys the associated + * attributes, commands and events. + * + * @param[in] cluster Cluster handle. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t destroy(cluster_t *cluster); + +/** Get cluster + * + * Get the cluster present on the endpoint. + * + * @param[in] endpoint Endpoint handle. + * @param[in] cluster_id Cluster ID for the cluster. + * + * @return Cluster handle on success. + * @return NULL in case of failure. + */ +cluster_t *get(endpoint_t *endpoint, uint32_t cluster_id); + +/** Get cluster + * + * Get the cluster present on the endpoint. + * + * @param[in] endpoint_id Endpoint id. + * @param[in] cluster_id Cluster ID for the cluster. + * + * @return Cluster handle on success. + * @return NULL in case of failure. + */ +cluster_t *get(uint16_t endpoint_id, uint32_t cluster_id); + +/** Get first cluster + * + * Get the first cluster present on the endpoint. + * + * @param[in] endpoint Endpoint handle. + * + * @return Cluster handle on success. + * @return NULL in case of failure. + */ +cluster_t *get_first(endpoint_t *endpoint); + +/** Get next cluster + * + * Get the next cluster present on the endpoint. + * + * @param[in] cluster Cluster handle. + * + * @return Cluster handle on success. + * @return NULL in case of failure. + */ +cluster_t *get_next(cluster_t *cluster); + +/** Get cluster ID + * + * Get the cluster ID for the cluster. + * + * @param[in] cluster Cluster handle. + * + * @return Cluster ID on success. + * @return Invalid CLuster ID (0xFFFF'FFFF) in case of failure. + */ +uint32_t get_id(cluster_t *cluster); + +/** Get delegate pointer + * + * Get the delegate pointer for the cluster. + * + * @param[in] cluster Cluster handle. + * + * @return pointer of delegate class on success. + * @return nullptr in case of failure. + */ +void *get_delegate_impl(cluster_t *cluster); + +/** Set cluster plugin server init callback + * + * Set the cluster plugin server init callback. This callback will be called when the endpoints are initialised. The + * callback should be set to upstream's `MatterPluginServerInitCallback` API for the cluster, if it + * exists. + * + * @param[in] cluster Cluster handle. + * @param[in] callback Plugin server init callback. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t set_plugin_server_init_callback(cluster_t *cluster, plugin_server_init_callback_t callback); + +/** Set server cluster delegate init callback + * + * @param[in] cluster Cluster handle. + * @param[in] callback Delegate server init callback. + * @param[in] delegate Pointer to delegate impl.. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t set_delegate_and_init_callback(cluster_t *cluster, delegate_init_callback_t callback, void *delegate); + +/** Set server cluster add bounds callback + * + * @param[in] cluster Cluster handle. + * @param[in] callback Add bounds callback. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t set_add_bounds_callback(cluster_t *cluster, add_bounds_callback_t callback); + +/** Get cluster plugin server init callback + * + * Get the cluster plugin server init callback which has previously been set. + * + * @param[in] cluster Cluster handle. + * + * @return Plugin server init callback. + * @return NULL in case of failure or if it has not been set. + */ +plugin_server_init_callback_t get_plugin_server_init_callback(cluster_t *cluster); + +/** Get server cluster delegate init callback + * + * @param[in] cluster Cluster handle. + * + * @return Delegate init callback. + * @return NULL in case of failure or if it has not been set. + */ +delegate_init_callback_t get_delegate_init_callback(cluster_t *cluster); + +/** Get server cluster add bounds callback + * + * @param[in] cluster Cluster handle. + * + * @return add bounds callback. + * @return NULL in case of failure or if it has not been set. + */ +add_bounds_callback_t get_add_bounds_callback(cluster_t *cluster); + +/** Add cluster function list + * + * This API can be used to add additional cluster functions based on `cluster_flags_t`. This should be set + * to upstream's `MatterServerCallback` or + * `emberAfServerCallback` API, if it exists. The corresponding function_flags must be be + * set. + * + * @param[in] cluster Cluster handle. + * @param[in] function_list Array of function_generic_t. + * @param[in] function_flags Bitmap of cluster flags corresponding to the function_list. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t add_function_list(cluster_t *cluster, const function_generic_t *function_list, int function_flags); + +} /* cluster */ + +namespace attribute { + +/** Create attribute + * + * This will create a new attribute and add it to the cluster. + * + * @param[in] cluster Cluster handle. + * @param[in] attribute_id Attribute ID for the attribute. + * @param[in] flags Bitmap of `attribute_flags_t`. + * @param[in] val Default type and value of the attribute. Use appropriate elements as per the value type. + * @param[in] max_val_size For attributes of type char string and long char string, the size should correspond to the + * maximum size defined in the specification. However, for other types of attributes, this + * parameter remains unused, and therefore the default value is set to 0 + * + * @return Attribute handle on success. + * @return NULL in case of failure. + */ +attribute_t *create(cluster_t *cluster, uint32_t attribute_id, uint16_t flags, esp_matter_attr_val_t val, + uint16_t max_val_size = 0); + +/** Get attribute + * + * Get the attribute present on the cluster. + * + * @param[in] cluster Cluster handle. + * @param[in] attribute_id Attribute ID for the attribute. + * + * @return Attribute handle on success. + * @return NULL in case of failure. + */ +attribute_t *get(cluster_t *cluster, uint32_t attribute_id); + +/** Get attribute + * + * Get the attribute present on the cluster. + * + * @param[in] endpoint_id Endpoint id.. + * @param[in] cluster_id Cluster ID for the Cluster. + * @param[in] attribute_id Attribute ID for the attribute. + * + * @return Attribute handle on success. + * @return NULL in case of failure. + */ +attribute_t *get(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id); + + +/** Get first attribute + * + * Get the first attribute present on the cluster. + * + * @param[in] cluster Cluster handle. + * + * @return Attribute handle on success. + * @return NULL in case of failure. + */ +attribute_t *get_first(cluster_t *cluster); + +/** Get next attribute + * + * Get the next attribute present on the cluster. + * + * @param[in] attribute Attribute handle. + * + * @return Attribute handle on success. + * @return NULL in case of failure. + */ +attribute_t *get_next(attribute_t *attribute); + +/** Get attribute ID + * + * Get the attribute ID for the attribute. + * + * @param[in] attribute Attribute handle. + * + * @return Attribute ID on success. + * @return Invalid Attribute ID (0xFFFF'FFFF) in case of failure. + */ +uint32_t get_id(attribute_t *attribute); + +/** Set attribute val + * + * Set/Update the value of the attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag) in the database. + * + * @note: Once `esp_matter::start()` is done, `attribute::update()` should be used to update the attribute value. + * + * @param[in] attribute Attribute handle. + * @param[in] val Pointer to `esp_matter_attr_val_t`. Use appropriate elements as per the value type. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t set_val(attribute_t *attribute, esp_matter_attr_val_t *val); + +/** Get attribute val + * + * Get the value of the attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag) from the database. + * + * @param[in] attribute Attribute handle. + * @param[out] val Pointer to `esp_matter_attr_val_t`. Use appropriate elements as per the value type. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t get_val(attribute_t *attribute, esp_matter_attr_val_t *val); + +/** Add attribute bounds + * + * Add bounds to the attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag). Bounds cannot be added to string/array type attributes. + * + * @param[in] attribute Attribute handle. + * @param[in] min Minimum allowed value. + * @param[in] max Maximum allowed value. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t add_bounds(attribute_t *attribute, esp_matter_attr_val_t min, esp_matter_attr_val_t max); + +/** Get attribute bounds + * + * Get the bounds which have been added to the attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag). + * + * @param[in] attribute Attribute handle. + * @param[in] bounds Pointer to `esp_matter_attr_bounds_t`. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t get_bounds(attribute_t *attribute, esp_matter_attr_bounds_t *bounds); + +/** Get attribute flags + * + * Get the attribute flags for the attribute. + * + * @param[in] attribute Attribute handle. + * + * @return Attribute flags. + */ +uint16_t get_flags(attribute_t *attribute); + +/** Set attribute override + * + * Set the override callback for the attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag). For attribute read and write calls, instead of doing that from the + * common database, this callback will be called. + * + * This can be used if the application or some component wants to maintain the attribute's value in the application or + * in that component respectively. It can also be used if the attribute value needs to be dynamically fetched and is + * difficult to maintain in the database. + * + * @param[in] attribute Attribute handle. + * @param[in] callback Override callback. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t set_override_callback(attribute_t *attribute, callback_t callback); + +/** Get attribute override + * + * Get the override callback for the attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag). + * + * @param[in] attribute Attribute handle. + * + * @return Attribute override callback. + */ +callback_t get_override_callback(attribute_t *attribute); + +/** Set attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag) deferred persistence + * + * Only non-volatile attributes can be set with deferred presistence. If an attribute is configured with deferred + * presistence, any modifications to it will be enacted in its persistent storage with a specific delay + * (CONFIG_ESP_MATTER_DEFERRED_ATTR_PERSISTENCE_TIME_MS) + * + * It could be used for the non-volatile attribues which might be changed rapidly, such as CurrentLevel in LevelControl + * cluster. + * + * @param[in] attribute Attribute handle. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t set_deferred_persistence(attribute_t *attribute); + +} /* attribute */ + +namespace command { + +/** Command callback + * + * Command callback which is called when the command is invoked. + * + * @note: If the `COMMAND_FLAG_CUSTOM` is set, the default command response is sent internally based on the + * return value from the callback. + * + * @param[in] command_path Common structure for endpoint, cluster and commands IDs. + * @param[in] tlv_data Command data in TLV format. + * @param[in] opaque_ptr This is a pointer which is used internally. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +typedef esp_err_t (*callback_t)(const ConcreteCommandPath &command_path, TLVReader &tlv_data, void *opaque_ptr); + +/** Create command + * + * This will create a new command and add it to the cluster. + * + * @note: For commands which are not defined in the spec the `COMMAND_FLAG_CUSTOM` flag must be set. This + * will send the command response internally, after the command callback is called. + * + * @param[in] cluster Cluster handle. + * @param[in] command_id Command ID for the command. + * @param[in] flags Bitmap of `command_flags_t`. + * @param[in] callback Command callback + * + * @return Command handle on success. + * @return NULL in case of failure. + */ +command_t *create(cluster_t *cluster, uint32_t command_id, uint8_t flags, callback_t callback); + +/** Get command + * + * Get the command present on the cluster. + * + * @param[in] cluster Cluster handle. + * @param[in] command_id Command ID for the command. + * @param[in] flags Command flags for the command to be fetched. + * + * @return Command handle on success. + * @return NULL in case of failure. + */ +command_t *get(cluster_t *cluster, uint32_t command_id, uint16_t flags); + +/** Get first command + * + * Get the first command present on the cluster. + * + * @param[in] cluster Cluster handle. + * + * @return Command handle on success. + * @return NULL in case of failure. + */ +command_t *get_first(cluster_t *cluster); + +/** Get next command + * + * Get the next command present on the cluster. + * + * @param[in] command Command handle. + * + * @return Command handle on success. + * @return NULL in case of failure. + */ +command_t *get_next(command_t *command); + +/** Get command ID + * + * Get the command ID for the command. + * + * @param[in] command Command handle. + * + * @return Command ID on success. + * @return Invalid Command ID (0xFFFF'FFFF) in case of failure. + */ +uint32_t get_id(command_t *command); + +/** Get command callback + * + * Get the command callback for the command. + * + * @param[in] command Command handle. + * + * @return Command callback on success. + * @return NULL in case of failure or if the callback was not set when creating the command. + */ +callback_t get_callback(command_t *command); + +/** Get command user_callback + * + * Get the command user_callback for the command. + * + * @param[in] command Command handle. + * + * @return Command user_callback on success. + * @return NULL in case of failure or if the callback was not set when creating the command. + */ +callback_t get_user_callback(command_t *command); + +/** Set command user_callback + * + * Set the user_callback for the command. + * + * @param[in] command Command handle. + * @param[in] user_callback callback_t. + * + * @return void + */ +void set_user_callback(command_t *command, callback_t user_callback); + +/** Get command flags + * + * Get the command flags for the command. + * + * @param[in] command Command handle. + * + * @return Command flags. + */ +uint16_t get_flags(command_t *command); + +} /* command */ + +namespace event { + +/** Create event + * + * This will create a new event and add it to the cluster. + * + * @param[in] cluster Cluster handle. + * @param[in] event_id Event ID for the event. + * + * @return Event handle on success. + * @return NULL in case of failure. + */ +event_t *create(cluster_t *cluster, uint32_t event_id); + +/** Get event + * + * Get the event present on the cluster. + * + * @param[in] cluster Cluster handle. + * @param[in] event_id Event ID for the command. + * + * @return Event handle on success. + * @return NULL in case of failure. + */ +event_t *get(cluster_t *cluster, uint32_t event_id); + +/** Get first event + * + * Get the first event present on the cluster. + * + * @param[in] cluster Cluster handle. + * + * @return Event handle on success. + * @return NULL in case of failure. + */ +event_t *get_first(cluster_t *cluster); + +/** Get next event + * + * Get the next event present on the cluster. + * + * @param[in] event Event handle. + * + * @return Event handle on success. + * @return NULL in case of failure. + */ +event_t *get_next(event_t *event); + +/** Get event ID + * + * Get the event ID for the event. + * + * @param[in] event Event handle. + * + * @return Event ID on success. + * @return Invalid Event ID (0xFFFF'FFFF) in case of failure. + */ +uint32_t get_id(event_t *event); + +} /* event */ +} /* esp_matter */ diff --git a/components/esp_matter/data_model/esp_matter_data_model_utils.cpp b/components/esp_matter/data_model/esp_matter_data_model_utils.cpp new file mode 100644 index 000000000..0c1d86a85 --- /dev/null +++ b/components/esp_matter/data_model/esp_matter_data_model_utils.cpp @@ -0,0 +1,118 @@ +// 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. + +#include +#include +#include +#include +#include +#include + +#include +#include + +using chip::Protocols::InteractionModel::Status; +using namespace chip; + +static const char *TAG = "data_model"; + +namespace esp_matter { + +static esp_err_t execute_override_callback(attribute_t *attribute, attribute::callback_type_t type, + uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, + esp_matter_attr_val_t *val) +{ + attribute::callback_t override_callback = attribute::get_override_callback(attribute); + void *priv_data = endpoint::get_priv_data(endpoint_id); + if (override_callback) { + return override_callback(type, endpoint_id, cluster_id, attribute_id, val, priv_data); + } else { + ESP_LOGW(TAG, + "Attribute override callback not set for Endpoint 0x%04" PRIX16 "'s Cluster 0x%08" PRIX32 + "'s Attribute 0x%08" PRIX32 ", calling the common callback", + endpoint_id, cluster_id, attribute_id); + } + return ESP_OK; +} +} // namespace esp_matter + +using namespace esp_matter; + +Status emberAfExternalAttributeReadCallback(EndpointId endpoint_id, ClusterId cluster_id, + const EmberAfAttributeMetadata *matter_attribute, uint8_t *buffer, + uint16_t max_read_length) +{ + /* Get value */ + uint32_t attribute_id = matter_attribute->attributeId; + attribute_t *attribute = attribute::get(endpoint_id, cluster_id, attribute_id); + VerifyOrReturnError(attribute, Status::Failure); + esp_matter_attr_val_t val = esp_matter_invalid(NULL); + + int flags = attribute::get_flags(attribute); + if (flags & ATTRIBUTE_FLAG_OVERRIDE) { + esp_err_t err = + execute_override_callback(attribute, attribute::READ, endpoint_id, cluster_id, attribute_id, &val); + VerifyOrReturnValue(err == ESP_OK, Status::Failure); + } else { + attribute::get_val(attribute, &val); + } + + /* Here, the val_print function gets called on attribute read. */ + attribute::val_print(endpoint_id, cluster_id, attribute_id, &val, true); + + /* Get size */ + uint16_t attribute_size = 0; + attribute::get_data_from_attr_val(&val, NULL, &attribute_size, NULL); + VerifyOrReturnValue(attribute_size <= max_read_length, Status::ResourceExhausted, + ESP_LOGE(TAG, + "Insufficient space for reading Endpoint 0x%04" PRIX16 "'s Cluster 0x%08" PRIX32 + "'s Attribute 0x%08" PRIX32 ": required: %" PRIu16 ", max: %" PRIu16 "", + endpoint_id, cluster_id, attribute_id, attribute_size, max_read_length)); + + /* Assign value */ + attribute::get_data_from_attr_val(&val, NULL, &attribute_size, buffer); + return Status::Success; +} + +Status emberAfExternalAttributeWriteCallback(EndpointId endpoint_id, ClusterId cluster_id, + const EmberAfAttributeMetadata *matter_attribute, uint8_t *buffer) +{ + /* Get value */ + uint32_t attribute_id = matter_attribute->attributeId; + attribute_t *attribute = attribute::get(endpoint_id, cluster_id, attribute_id); + VerifyOrReturnError(attribute, Status::Failure); + + /* Get val */ + /* This creates a new variable val, and stores the new attribute value in the new variable. + The value in esp-matter data model is updated only when attribute::set_val() is called */ + esp_matter_attr_val_t val = esp_matter_invalid(NULL); + attribute::get_attr_val_from_data(&val, matter_attribute->attributeType, matter_attribute->size, buffer, + matter_attribute); + + int flags = attribute::get_flags(attribute); + if (flags & ATTRIBUTE_FLAG_OVERRIDE) { + esp_err_t err = + execute_override_callback(attribute, attribute::WRITE, endpoint_id, cluster_id, attribute_id, &val); + Status status = (err == ESP_OK) ? Status::Success : Status::Failure; + return status; + } + + /* Update val */ + VerifyOrReturnValue(val.type != ESP_MATTER_VAL_TYPE_INVALID, Status::Failure); + attribute::set_val(attribute, &val); + return Status::Success; +} + +// No-op function, used to force linking this file, instead of the weak functions from other files. +extern "C" void data_model_utils_impl(void) {} diff --git a/components/esp_matter/esp_matter_delegate_callbacks.cpp b/components/esp_matter/data_model/esp_matter_delegate_callbacks.cpp similarity index 100% rename from components/esp_matter/esp_matter_delegate_callbacks.cpp rename to components/esp_matter/data_model/esp_matter_delegate_callbacks.cpp diff --git a/components/esp_matter/esp_matter_delegate_callbacks.h b/components/esp_matter/data_model/esp_matter_delegate_callbacks.h similarity index 100% rename from components/esp_matter/esp_matter_delegate_callbacks.h rename to components/esp_matter/data_model/esp_matter_delegate_callbacks.h diff --git a/components/esp_matter/esp_matter_endpoint.cpp b/components/esp_matter/data_model/esp_matter_endpoint.cpp similarity index 100% rename from components/esp_matter/esp_matter_endpoint.cpp rename to components/esp_matter/data_model/esp_matter_endpoint.cpp diff --git a/components/esp_matter/esp_matter_endpoint.h b/components/esp_matter/data_model/esp_matter_endpoint.h similarity index 100% rename from components/esp_matter/esp_matter_endpoint.h rename to components/esp_matter/data_model/esp_matter_endpoint.h diff --git a/components/esp_matter/esp_matter_event.cpp b/components/esp_matter/data_model/esp_matter_event.cpp similarity index 100% rename from components/esp_matter/esp_matter_event.cpp rename to components/esp_matter/data_model/esp_matter_event.cpp diff --git a/components/esp_matter/esp_matter_event.h b/components/esp_matter/data_model/esp_matter_event.h similarity index 99% rename from components/esp_matter/esp_matter_event.h rename to components/esp_matter/data_model/esp_matter_event.h index 6713c10cd..5a873705b 100644 --- a/components/esp_matter/esp_matter_event.h +++ b/components/esp_matter/data_model/esp_matter_event.h @@ -15,7 +15,7 @@ #pragma once #include -#include +#include #include namespace esp_matter { diff --git a/components/esp_matter/esp_matter_feature.cpp b/components/esp_matter/data_model/esp_matter_feature.cpp similarity index 100% rename from components/esp_matter/esp_matter_feature.cpp rename to components/esp_matter/data_model/esp_matter_feature.cpp diff --git a/components/esp_matter/esp_matter_feature.h b/components/esp_matter/data_model/esp_matter_feature.h similarity index 99% rename from components/esp_matter/esp_matter_feature.h rename to components/esp_matter/data_model/esp_matter_feature.h index 3409cc776..d2cb4f68a 100644 --- a/components/esp_matter/esp_matter_feature.h +++ b/components/esp_matter/data_model/esp_matter_feature.h @@ -16,6 +16,7 @@ #include #include +#include #define ESP_MATTER_NONE_FEATURE_ID 0x0000 diff --git a/components/esp_matter/data_model/private/esp_matter_data_model_priv.h b/components/esp_matter/data_model/private/esp_matter_data_model_priv.h new file mode 100644 index 000000000..7c39a6fad --- /dev/null +++ b/components/esp_matter/data_model/private/esp_matter_data_model_priv.h @@ -0,0 +1,43 @@ +// 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. + +#pragma once + +#include +#include +#include + +namespace esp_matter { +namespace node { + +esp_err_t store_min_unused_endpoint_id(); + +esp_err_t read_min_unused_endpoint_id(); + +} // namespace node +namespace endpoint { + +esp_err_t enable_all(); + +} + +namespace attribute { +esp_err_t get_data_from_attr_val(esp_matter_attr_val_t *val, EmberAfAttributeType *attribute_type, + uint16_t *attribute_size, uint8_t *value); + +esp_err_t get_attr_val_from_data(esp_matter_attr_val_t *val, EmberAfAttributeType attribute_type, + uint16_t attribute_size, uint8_t *value, + const EmberAfAttributeMetadata * attribute_metadata); +} +} // namespace esp_matter diff --git a/components/esp_matter/esp_matter.h b/components/esp_matter/esp_matter.h index 3d33224d0..9581274d3 100644 --- a/components/esp_matter/esp_matter.h +++ b/components/esp_matter/esp_matter.h @@ -18,94 +18,26 @@ This is a common include file which includes all the other esp_matter component files which would be required by the application. */ - +#include +#ifdef CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL #include -#include -#include #include #include -#include #include #include #include -#include - +#include +#endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL #include +#include +#include +#endif // CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER +#include +#include #include #include -namespace esp_matter { - -/** Endpoint flags */ -typedef enum endpoint_flags { - /** No specific flags */ - ENDPOINT_FLAG_NONE = 0x00, - /** The endpoint can be destroyed using `endpoint::destroy()` */ - ENDPOINT_FLAG_DESTROYABLE = 0x01, - /** The endpoint is a bridged node */ - ENDPOINT_FLAG_BRIDGE = 0x02, -} endpoint_flags_t; - -/** Cluster flags */ -typedef enum cluster_flags { - /** No specific flags */ - CLUSTER_FLAG_NONE = 0x00, - /** The cluster has an init function (function_flag) */ - CLUSTER_FLAG_INIT_FUNCTION = MATTER_CLUSTER_FLAG_INIT_FUNCTION, /* 0x01 */ - /** The cluster has an attribute changed function (function_flag) */ - CLUSTER_FLAG_ATTRIBUTE_CHANGED_FUNCTION = MATTER_CLUSTER_FLAG_ATTRIBUTE_CHANGED_FUNCTION, /* 0x02 */ - /** The cluster has a shutdown function (function_flag) */ - CLUSTER_FLAG_SHUTDOWN_FUNCTION = MATTER_CLUSTER_FLAG_SHUTDOWN_FUNCTION, /* 0x10 */ - /** The cluster has a pre attribute changed function (function_flag) */ - CLUSTER_FLAG_PRE_ATTRIBUTE_CHANGED_FUNCTION = MATTER_CLUSTER_FLAG_PRE_ATTRIBUTE_CHANGED_FUNCTION, /* 0x20 */ - /** The cluster is a server cluster */ - CLUSTER_FLAG_SERVER = MATTER_CLUSTER_FLAG_SERVER, /* 0x40 */ - /** The cluster is a client cluster */ - CLUSTER_FLAG_CLIENT = MATTER_CLUSTER_FLAG_CLIENT, /* 0x80 */ -} cluster_flags_t; - -/** Attribute flags */ -typedef enum attribute_flags { - /** No specific flags */ - ATTRIBUTE_FLAG_NONE = 0x00, - /** The attribute is writable and can be directly changed by clients */ - ATTRIBUTE_FLAG_WRITABLE = MATTER_ATTRIBUTE_FLAG_WRITABLE, /* 0x01 */ - /** The attribute is non volatile and its value will be stored in NVS */ - ATTRIBUTE_FLAG_NONVOLATILE = MATTER_ATTRIBUTE_FLAG_NONVOLATILE, /* 0x02 */ - /** The attribute has bounds */ - ATTRIBUTE_FLAG_MIN_MAX = MATTER_ATTRIBUTE_FLAG_MIN_MAX, /* 0x04 */ - ATTRIBUTE_FLAG_MUST_USE_TIMED_WRITE = MATTER_ATTRIBUTE_FLAG_MUST_USE_TIMED_WRITE, /* 0x08 */ - /** The attribute uses external storage for its value. If attributes - have this flag enabled, as all of them are stored in the ESP Matter database. */ - ATTRIBUTE_FLAG_EXTERNAL_STORAGE = MATTER_ATTRIBUTE_FLAG_EXTERNAL_STORAGE, /* 0x10 */ - ATTRIBUTE_FLAG_SINGLETON = MATTER_ATTRIBUTE_FLAG_SINGLETON, /* 0x20 */ - ATTRIBUTE_FLAG_NULLABLE = MATTER_ATTRIBUTE_FLAG_NULLABLE, /* 0x40 */ - /** The attribute read and write are overridden. The attribute value will be fetched from and will be updated using - the override callback. The value of this attribute is not maintained internally. */ - ATTRIBUTE_FLAG_OVERRIDE = ATTRIBUTE_FLAG_NULLABLE << 1, /* 0x80 */ - /** The attribute is non-volatile but its value will be changed frequently. If an attribute has this flag, its value - will not be written to flash immediately. A timer will be started and the attribute value will be written after - timeout. */ - ATTRIBUTE_FLAG_DEFERRED = ATTRIBUTE_FLAG_NULLABLE << 2, /* 0x100 */ - /** The attribute is managed internally and is not stored in the ESP Matter database. - If not set, ATTRIBUTE_FLAG_EXTERNAL_STORAGE flag will be enabled. */ - ATTRIBUTE_FLAG_MANAGED_INTERNALLY = ATTRIBUTE_FLAG_NULLABLE << 3, /* 0x200 */ -} attribute_flags_t; - -/** Command flags */ -typedef enum command_flags { - /** No specific flags */ - COMMAND_FLAG_NONE = 0x00, - /** The command is not a standard command */ - COMMAND_FLAG_CUSTOM = 0x01, - /** The command is client generated */ - COMMAND_FLAG_ACCEPTED = 0x02, - /** The command is server generated */ - COMMAND_FLAG_GENERATED = 0x04, -} command_flags_t; - -} /* esp_matter */ - namespace chip { namespace DeviceLayer { namespace DeviceEventType { diff --git a/components/esp_matter/esp_matter_attribute_utils.cpp b/components/esp_matter/esp_matter_attribute_utils.cpp index f2bc2b45a..49b73ab6c 100644 --- a/components/esp_matter/esp_matter_attribute_utils.cpp +++ b/components/esp_matter/esp_matter_attribute_utils.cpp @@ -1012,28 +1012,16 @@ static esp_err_t execute_callback(callback_type_t type, uint16_t endpoint_id, ui uint32_t attribute_id, esp_matter_attr_val_t *val) { if (attribute_callback) { +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL void *priv_data = endpoint::get_priv_data(endpoint_id); +#else + void *priv_data = nullptr; +#endif return attribute_callback(type, endpoint_id, cluster_id, attribute_id, val, priv_data); } return ESP_OK; } -static esp_err_t execute_override_callback(attribute_t *attribute, callback_type_t type, uint16_t endpoint_id, - uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *val) -{ - callback_t override_callback = attribute::get_override_callback(attribute); - void *priv_data = endpoint::get_priv_data(endpoint_id); - if (override_callback) { - return override_callback(type, endpoint_id, cluster_id, attribute_id, val, priv_data); - } else { - ESP_LOGI(TAG, "Attribute override callback not set for Endpoint 0x%04" PRIX16 "'s Cluster 0x%08" PRIX32 "'s Attribute 0x%08" PRIX32 ", calling the common callback", - endpoint_id, cluster_id, attribute_id); - if (attribute_callback) - return attribute_callback(type, endpoint_id, cluster_id, attribute_id, val, priv_data); - } - return ESP_OK; -} - static esp_matter_val_type_t get_val_type_from_attribute_type(int attribute_type) { switch (attribute_type) { @@ -2110,6 +2098,7 @@ esp_err_t report(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_i lock::status_t lock_status = lock::chip_stack_lock(portMAX_DELAY); VerifyOrReturnError(lock_status != lock::FAILED, ESP_FAIL, ESP_LOGE(TAG, "Could not get task context")); +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL /* Get attribute */ attribute_t *attribute = attribute::get(endpoint_id, cluster_id, attribute_id); if (!attribute) { @@ -2133,7 +2122,7 @@ esp_err_t report(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_i return ESP_FAIL; } attribute::set_val(attribute, val); - +#endif /* Report attribute */ MatterReportingAttributeChangeCallback(endpoint_id, cluster_id, attribute_id); @@ -2180,64 +2169,3 @@ void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath &p /* Callback to application */ execute_callback(attribute::POST_UPDATE, endpoint_id, cluster_id, attribute_id, &val); } - -Status emberAfExternalAttributeReadCallback(EndpointId endpoint_id, ClusterId cluster_id, - const EmberAfAttributeMetadata *matter_attribute, uint8_t *buffer, - uint16_t max_read_length) -{ - /* Get value */ - uint32_t attribute_id = matter_attribute->attributeId; - attribute_t *attribute = attribute::get(endpoint_id, cluster_id, attribute_id); - VerifyOrReturnError(attribute, Status::Failure); - esp_matter_attr_val_t val = esp_matter_invalid(NULL); - - int flags = attribute::get_flags(attribute); - if (flags & ATTRIBUTE_FLAG_OVERRIDE) { - esp_err_t err = execute_override_callback(attribute, attribute::READ, endpoint_id, cluster_id, attribute_id, - &val); - VerifyOrReturnValue(err == ESP_OK, Status::Failure); - } else { - attribute::get_val(attribute, &val); - } - - /* Here, the val_print function gets called on attribute read. */ - attribute::val_print(endpoint_id, cluster_id, attribute_id, &val, true); - - /* Get size */ - uint16_t attribute_size = 0; - attribute::get_data_from_attr_val(&val, NULL, &attribute_size, NULL); - VerifyOrReturnValue(attribute_size <= max_read_length, Status::ResourceExhausted, ESP_LOGE(TAG, "Insufficient space for reading Endpoint 0x%04" PRIX16 "'s Cluster 0x%08" PRIX32 "'s Attribute 0x%08" PRIX32 - ": required: %" PRIu16 ", max: %" PRIu16 "", endpoint_id, cluster_id, attribute_id, attribute_size, max_read_length)); - - /* Assign value */ - attribute::get_data_from_attr_val(&val, NULL, &attribute_size, buffer); - return Status::Success; -} - -Status emberAfExternalAttributeWriteCallback(EndpointId endpoint_id, ClusterId cluster_id, - const EmberAfAttributeMetadata *matter_attribute, uint8_t *buffer) -{ - /* Get value */ - uint32_t attribute_id = matter_attribute->attributeId; - attribute_t *attribute = attribute::get(endpoint_id, cluster_id, attribute_id); - VerifyOrReturnError(attribute, Status::Failure); - - /* Get val */ - /* This creates a new variable val, and stores the new attribute value in the new variable. - The value in esp-matter data model is updated only when attribute::set_val() is called */ - esp_matter_attr_val_t val = esp_matter_invalid(NULL); - attribute::get_attr_val_from_data(&val, matter_attribute->attributeType, matter_attribute->size, buffer, matter_attribute); - - int flags = attribute::get_flags(attribute); - if (flags & ATTRIBUTE_FLAG_OVERRIDE) { - esp_err_t err = execute_override_callback(attribute, attribute::WRITE, endpoint_id, cluster_id, attribute_id, - &val); - Status status = (err == ESP_OK) ? Status::Success : Status::Failure; - return status; - } - - /* Update val */ - VerifyOrReturnValue(val.type != ESP_MATTER_VAL_TYPE_INVALID, Status::Failure); - attribute::set_val(attribute, &val); - return Status::Success; -} diff --git a/components/esp_matter/esp_matter_attribute_utils.h b/components/esp_matter/esp_matter_attribute_utils.h index 51c5b9d9c..79ec698fa 100644 --- a/components/esp_matter/esp_matter_attribute_utils.h +++ b/components/esp_matter/esp_matter_attribute_utils.h @@ -450,5 +450,21 @@ esp_err_t report(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_i */ void val_print(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, esp_matter_attr_val_t *val, bool is_read); +/** Get attribute val raw + * + * Get the value of the attribute in the database, without the attribute handle. + * + * @param[in] endpoint_id Endpoint ID of the attribute. + * @param[in] cluster_id Cluster ID of the attribute. + * @param[in] attribute_id Attribute ID of the attribute. + * @param[out] value Pointer to an allocated buffer for the attribute value. + * @param[in] attribute_size Size of the allocated buffer. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t get_val_raw(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, uint8_t *value, + uint16_t attribute_size); + } /* attribute */ } /* esp_matter */ diff --git a/components/esp_matter/esp_matter_client.cpp b/components/esp_matter/esp_matter_client.cpp index 0fd7b1550..0a5c8b9be 100644 --- a/components/esp_matter/esp_matter_client.cpp +++ b/components/esp_matter/esp_matter_client.cpp @@ -25,10 +25,12 @@ #include #include #include -#include #include #include #include +#ifdef CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER +#include +#endif #include "app/CommandPathParams.h" #include "app/CommandSender.h" @@ -87,11 +89,12 @@ void esp_matter_connection_failure_callback(void *context, const ScopedNodeId &p esp_err_t connect(case_session_mgr_t *case_session_mgr, uint8_t fabric_index, uint64_t node_id, request_handle_t *req_handle) { + VerifyOrReturnError(req_handle, ESP_ERR_INVALID_ARG); VerifyOrReturnError(case_session_mgr, ESP_ERR_INVALID_ARG); static Callback success_callback(esp_matter_connection_success_callback, NULL); static Callback failure_callback(esp_matter_connection_failure_callback, NULL); - request_handle_t *context = chip::Platform::New(req_handle); + request_handle_t *context = chip::Platform::New(*req_handle); VerifyOrReturnError(context, ESP_ERR_NO_MEM, ESP_LOGE(TAG, "failed to alloc memory for the command handle")); success_callback.mContext = static_cast(context); failure_callback.mContext = static_cast(context); @@ -109,6 +112,7 @@ esp_err_t group_request_send(uint8_t fabric_index, request_handle_t *req_handle) return ESP_OK; } +#ifdef CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER static void esp_matter_command_client_binding_callback(const EmberBindingTableEntry &binding, OperationalDeviceProxy *peer_device, void *context) { @@ -151,7 +155,8 @@ static void esp_matter_binding_context_release(void *context) esp_err_t cluster_update(uint16_t local_endpoint_id, request_handle_t *req_handle) { - request_handle_t *context = chip::Platform::New(req_handle); + VerifyOrReturnError(req_handle, ESP_ERR_INVALID_ARG); + request_handle_t *context = chip::Platform::New(*req_handle); VerifyOrReturnError(context, ESP_ERR_NO_MEM, ESP_LOGE(TAG, "failed to alloc memory for the request handle")); chip::ClusterId notified_cluster_id = chip::kInvalidClusterId; if (req_handle->type == INVOKE_CMD) { @@ -199,6 +204,7 @@ void binding_init() { initialize_binding_manager = true; } +#endif // CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER namespace interaction { using chip::app::DataModel::EncodableToTLV; diff --git a/components/esp_matter/esp_matter_client.h b/components/esp_matter/esp_matter_client.h index 668f7dcb2..5be62ea0c 100644 --- a/components/esp_matter/esp_matter_client.h +++ b/components/esp_matter/esp_matter_client.h @@ -23,7 +23,151 @@ #include namespace esp_matter { +/* Client APIs */ namespace client { + +/** Client request types + */ +typedef enum { + INVOKE_CMD = 0, + READ_ATTR = 1, + READ_EVENT = 2, + WRITE_ATTR = 3, + SUBSCRIBE_ATTR = 4, + SUBSCRIBE_EVENT = 5, +} request_type_t; + +/** Request handle as the input when calling `connect()` or `cluster_update()` + * + */ + +typedef struct request_handle { + request_type_t type; + union { + chip::app::AttributePathParams attribute_path; + chip::app::EventPathParams event_path; + chip::app::CommandPathParams command_path; + }; + /* This could be the command data field when the request type is INVOKE_CMD, + * or the attribute value data when the request type is WRITE_ATTR. + */ + void *request_data; + request_handle() : type(INVOKE_CMD), request_data(NULL) {} + request_handle(struct request_handle& req) : type(req.type), request_data(req.request_data) + { + if (req.type == INVOKE_CMD) { + command_path = req.command_path; + } else if (req.type == WRITE_ATTR || req.type == READ_ATTR || req.type == SUBSCRIBE_ATTR) { + attribute_path = req.attribute_path; + } else if (req.type == READ_EVENT || req.type == SUBSCRIBE_EVENT) { + event_path = req.event_path; + } + } +} request_handle_t; + +/** Peer device handle */ +typedef chip::DeviceProxy peer_device_t; + +/** CASE Session Manager */ +typedef chip::CASESessionManager case_session_mgr_t; + +/** Request send callback + * + * This callback will be called when `connect()` or `cluster_update()` is called and the connection completes. The + * send_request APIs can then be called from the callback. + * + * @param[in] peer_device Peer device handle. This can be passed to the send_command APIs. + * @param[in] req_handle Request handle used by `connect()` or `cluster_update()`. + * @param[in] priv_data (Optional) Private data associated with the callback. This will be passed to callback. It + * should stay allocated throughout the lifetime of the device. + */ +typedef void (*request_callback_t)(peer_device_t *peer_device, request_handle_t *req_handle, void *priv_data); + +/** Group request send callback + * + * This callback will be called when `cluster_update()` is called and the group request is triggered for binding cluster. + * + * @note: The request type should be INVOKE_CMD and the command should not expect a response. + * + * @param[in] fabric_index The index of the fabric that the group command is sent to. + * @param[in] req_handle Request handle used by `cluster_update()`. + * @param[in] priv_data (Optional) Private data associated with the callback. This will be passed to callback. It + * should stay allocated throughout the lifetime of the device. + */ +typedef void (*group_request_callback_t)(uint8_t fabric_index, request_handle_t *req_handle, void *priv_data); + +#ifdef CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER +/** Initialize binding + * + * This should be called if the Binding cluster has been created. It just sets a flag for the binding manager to be + * initialized. + * If the cluster::binding::create() is being used, this is called internally. + */ +void binding_init(); + +/** Initialize binding manager + * + * This initializes the binding manager. It is called after the matter thread has been started. + */ +void binding_manager_init(); +#endif // CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER + +/** Connect + * + * Connect to another device on the same fabric to send a request. + * + * @param[in] case_session_mgr CASE Session Manager to find or establish the session + * @param[in] fabric_index Fabric index. + * @param[in] node_id Node ID of the other device. + * @param[in] req_handle Request to be sent to the remote device. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t connect(case_session_mgr_t *case_session_mgr, uint8_t fabric_index, uint64_t node_id, + request_handle_t *req_handle); + +/** group_request_send + * + * on the same fabric to send a group request. + * + * @param[in] fabric_index Fabric index. + * @param[in] req_handle Request to be sent to the group. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t group_request_send(uint8_t fabric_index, request_handle_t *req_handle); + +/** Set request send callback + * + * Set the common request send callback and the group request send callback. The common callback will be called + * when `connect()` or `cluster_update()` is called and the connection completes. The group callback will be called + * when `cluster_update()` is called and the group request is triggered. + * + * @param[in] callback request send callback. + * @param[in] g_callback group request send callback + * @param[in] priv_data (Optional) Private data associated with the callback. This will be passed to callback. It + * should stay allocated throughout the lifetime of the device. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t set_request_callback(request_callback_t callback, group_request_callback_t g_callback, void *priv_data); + +/** Cluster update + * + * For an already binded device, this API can be used to get the request send callback, and the send_request APIs can + * then be called from the callback. + * + * @param[in] local_endpoint_id The ID of the local endpoint with a binding cluster. + * @param[in] req_handle Request information to notify the bound cluster changed. + * + * @return ESP_OK on success. + * @return error in case of failure. + */ +esp_err_t cluster_update(uint16_t local_endpoint_id, request_handle_t *req_handle); + namespace interaction { using chip::Optional; diff --git a/components/esp_matter/esp_matter_core.cpp b/components/esp_matter/esp_matter_core.cpp index 04e272e43..2902b94e7 100644 --- a/components/esp_matter/esp_matter_core.cpp +++ b/components/esp_matter/esp_matter_core.cpp @@ -20,12 +20,17 @@ #include #include -#include -#include #include +#ifdef CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER +#include #include -#include -#include +#include +#include +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL +#include +#endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL +#endif // CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER +#include #include #include #include @@ -48,32 +53,16 @@ #include #include -#include -#include - -using chip::CommandId; -using chip::DataVersion; -using chip::EventId; -using chip::kInvalidAttributeId; -using chip::kInvalidCommandId; -using chip::kInvalidClusterId; -using chip::kInvalidEndpointId; -using chip::Credentials::SetDeviceAttestationCredentialsProvider; using chip::DeviceLayer::ChipDeviceEvent; using chip::DeviceLayer::ConfigurationMgr; using chip::DeviceLayer::ConnectivityManager; using chip::DeviceLayer::ConnectivityMgr; using chip::DeviceLayer::PlatformMgr; -using chip::DeviceLayer::DiagnosticDataProvider; using chip::DeviceLayer::GetDiagnosticDataProvider; #if CHIP_DEVICE_CONFIG_ENABLE_THREAD using chip::DeviceLayer::ThreadStackMgr; #endif -#define ESP_MATTER_NVS_PART_NAME CONFIG_ESP_MATTER_NVS_PART_NAME -#define ESP_MATTER_MAX_DEVICE_TYPE_COUNT CONFIG_ESP_MATTER_MAX_DEVICE_TYPE_COUNT -#define MAX_GROUPS_PER_FABRIC_PER_ENDPOINT CONFIG_MAX_GROUPS_PER_FABRIC_PER_ENDPOINT - static const char *TAG = "esp_matter_core"; static bool esp_matter_started = false; @@ -81,6 +70,7 @@ static bool esp_matter_started = false; // If Matter Server is disabled, these functions are required by InteractionModelEngine but not linked // as they are defined in other files. They will be never used if server is not enable. Define empty // functions in esp_matter_core.cpp to make sure that they are linked +// TODO: Use dynamic server defined in upstream repo void InitDataModelHandler() {} namespace chip { @@ -90,14 +80,30 @@ void DispatchSingleClusterCommand(const ConcreteCommandPath &command_path, TLVRe } // namespace app } // namespace chip -bool emberAfContainsAttribute(chip::EndpointId endpoint, chip::ClusterId clusterId, chip::AttributeId attributeId) +chip::Access::Privilege MatterGetAccessPrivilegeForReadAttribute(chip::ClusterId cluster, chip::AttributeId attribute) { - return false; + return chip::Access::Privilege::kView; +} + +chip::Access::Privilege MatterGetAccessPrivilegeForWriteAttribute(chip::ClusterId cluster, chip::AttributeId attribute) +{ + return chip::Access::Privilege::kOperate; +} + +chip::Access::Privilege MatterGetAccessPrivilegeForInvokeCommand(chip::ClusterId cluster, chip::CommandId command) +{ + return chip::Access::Privilege::kOperate; +} + +chip::Access::Privilege MatterGetAccessPrivilegeForReadEvent(chip::ClusterId cluster, chip::EventId event) +{ + return chip::Access::Privilege::kView; } #endif // !CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER namespace esp_matter { +#ifdef CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER namespace { void PostEvent(uint16_t eventType) @@ -161,591 +167,7 @@ AppDelegateImpl s_app_delegate; FabricDelegateImpl s_fabric_delegate; } // namespace - -struct _attribute_base_t { - uint16_t flags; // This struct is for attributes managed internally. - uint16_t index; - uint32_t attribute_id; - struct _attribute_base_t *next; -}; - -struct _attribute_t : public _attribute_base_t { - uint32_t cluster_id; // This struct is for attributes not managed internally. - esp_matter_attr_val_t val; - attribute::callback_t override_callback; - uint16_t endpoint_id; -}; - -typedef struct _command { - uint32_t command_id; - uint16_t flags; - command::callback_t callback; - command::callback_t user_callback; - struct _command *next; -} _command_t; - -typedef struct _event { - uint32_t event_id; - struct _event *next; -} _event_t; - -typedef struct _cluster { - uint8_t index; - uint16_t endpoint_id; - cluster::plugin_server_init_callback_t plugin_server_init_callback; - cluster::delegate_init_callback_t delegate_init_callback; - void * delegate_pointer; - cluster::add_bounds_callback_t add_bounds_callback; - _attribute_base_t *attribute_list; /* If attribute is managed internally, the actual pointer type is _internal_attribute_t. - When operating attribute_list, do check the flags first! */ - EmberAfAttributeMetadata *matter_attributes; - _command_t *command_list; - _event_t *event_list; - struct _cluster *next; -} _cluster_t; - -typedef struct _endpoint { - uint16_t endpoint_id; - uint8_t device_type_count; - uint8_t cluster_count; - uint8_t device_type_versions[ESP_MATTER_MAX_DEVICE_TYPE_COUNT]; - uint32_t device_type_ids[ESP_MATTER_MAX_DEVICE_TYPE_COUNT]; - uint16_t flags; - uint16_t parent_endpoint_id; - _cluster_t *cluster_list; - EmberAfEndpointType *endpoint_type; - DataVersion *data_versions_ptr; - EmberAfDeviceType *device_types_ptr; - void *priv_data; - Identify *identify; - struct _endpoint *next; -} _endpoint_t; - -typedef struct _node { - _endpoint_t *endpoint_list; - uint16_t min_unused_endpoint_id; -} _node_t; - -namespace node { - -static _node_t *node = NULL; - -#if defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) -// If Matter server or ESP-Matter data model is not enabled. we will never use minimum unused endpoint id. -static esp_err_t store_min_unused_endpoint_id() -{ - VerifyOrReturnError((node && esp_matter_started), ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "Node does not exist or esp_matter does not start")); - nvs_handle_t handle; - esp_err_t err = nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, ESP_MATTER_KVS_NAMESPACE, - NVS_READWRITE, &handle); - - VerifyOrReturnError(err == ESP_OK, err, ESP_LOGE(TAG, "Failed to open the node nvs_namespace")); - err = nvs_set_u16(handle, "min_uu_ep_id", node->min_unused_endpoint_id); - nvs_commit(handle); - nvs_close(handle); - return err; -} - -static esp_err_t read_min_unused_endpoint_id() -{ - VerifyOrReturnError((node && esp_matter_started), ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "Node does not exist or esp_matter does not start")); - - nvs_handle_t handle; - esp_err_t err = nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, ESP_MATTER_KVS_NAMESPACE, - NVS_READONLY, &handle); - if (err == ESP_OK) { - err = nvs_get_u16(handle, "min_uu_ep_id", &node->min_unused_endpoint_id); - nvs_close(handle); - } - - if (err == ESP_ERR_NVS_NOT_FOUND) { - ESP_LOGI(TAG, "Cannot find minimum unused endpoint_id, try to find in the previous namespace"); - // Try to read the minimum unused endpoint_id from the previous node namespace. - err = nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, "node", NVS_READONLY, &handle); - VerifyOrReturnError(err == ESP_OK, err, ESP_LOGI(TAG, "Failed to open node namespace")); - err = nvs_get_u16(handle, "min_uu_ep_id", &node->min_unused_endpoint_id); - nvs_close(handle); - if (err == ESP_OK) { - // If the minimum unused endpoint_id is got, we will erase it from the previous namespace - // and store it to the new namespace. - if (nvs_open_from_partition(ESP_MATTER_NVS_PART_NAME, "node", NVS_READWRITE, &handle) == ESP_OK) { - if (nvs_erase_key(handle, "min_uu_ep_id") != ESP_OK) { - ESP_LOGE(TAG, "Failed to erase minimum unused endpoint_id"); - } else { - nvs_commit(handle); - } - nvs_close(handle); - } - return store_min_unused_endpoint_id(); - } - } else if (err != ESP_OK) { - ESP_LOGE(TAG, "Failed to get minimum unused endpoint_id in the %s nvs_namespace", ESP_MATTER_KVS_NAMESPACE); - } - return err; -} -#endif // defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) -} /* node */ - -namespace command { -#if defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) -command_entry_t *get_cluster_accepted_command_list(uint32_t cluster_id); -size_t get_cluster_accepted_command_count(uint32_t cluster_id); -command_entry_t *get_cluster_generated_command_list(uint32_t cluster_id); -size_t get_cluster_generated_command_count(uint32_t cluster_id); -#else -command_entry_t *get_cluster_accepted_command_list(uint32_t cluster_id) { return nullptr; } -size_t get_cluster_accepted_command_count(uint32_t cluster_id) { return 0; } -command_entry_t *get_cluster_generated_command_list(uint32_t cluster_id) { return nullptr; } -size_t get_cluster_generated_command_count(uint32_t cluster_id) {return 0; } -#endif // defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) -} /* command */ - -namespace attribute { - -esp_err_t get_data_from_attr_val(esp_matter_attr_val_t *val, EmberAfAttributeType *attribute_type, - uint16_t *attribute_size, uint8_t *value); -esp_err_t get_attr_val_from_data(esp_matter_attr_val_t *val, EmberAfAttributeType attribute_type, - uint16_t attribute_size, uint8_t *value, - const EmberAfAttributeMetadata * attribute_metadata); - -static EmberAfAttributeMetadata *get_external_attribute_metadata(_attribute_t * attribute) -{ - if (NULL == attribute || (attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY)) { - return NULL; - } - _cluster_t *cluster = (_cluster_t *)cluster::get(attribute->endpoint_id, attribute->cluster_id); - if (NULL == cluster) { - return NULL; - } - return &cluster->matter_attributes[attribute->index]; -} - -static esp_err_t free_default_value(attribute_t *attribute) -{ - VerifyOrReturnError(attribute, ESP_FAIL, ESP_LOGE(TAG, "Attribute cannot be NULL")); - _attribute_t *current_attribute = (_attribute_t *)attribute; - EmberAfAttributeMetadata *matter_attribute = get_external_attribute_metadata(current_attribute); - if (!matter_attribute) { - ESP_LOGE(TAG, "Attribute Metadata is not found"); - return ESP_ERR_NOT_FOUND; - } - - /* Free value if data is more than 2 bytes or if it is min max attribute */ - if (current_attribute->flags & ATTRIBUTE_FLAG_MIN_MAX) { - if (matter_attribute->size > 2) { - esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToMinMaxValue->defaultValue.ptrToDefaultValue); - esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToMinMaxValue->minValue.ptrToDefaultValue); - esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToMinMaxValue->maxValue.ptrToDefaultValue); - } - esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToMinMaxValue); - } else if (matter_attribute->size > 2) { - esp_matter_mem_free((void *)matter_attribute->defaultValue.ptrToDefaultValue); - } - return ESP_OK; -} - -static EmberAfDefaultAttributeValue get_default_value_from_data(esp_matter_attr_val_t *val, - EmberAfAttributeType attribute_type, - uint16_t attribute_size) -{ - EmberAfDefaultAttributeValue default_value = (uint16_t)0; - uint8_t *value = (uint8_t *)esp_matter_mem_calloc(1, attribute_size); - VerifyOrReturnValue(value, default_value, ESP_LOGE(TAG, "Could not allocate value buffer for default value")); - get_data_from_attr_val(val, &attribute_type, &attribute_size, value); - - if (attribute_size > 2) { - /* Directly set the pointer */ - default_value = value; - } else { - /* This data is 2 bytes or less. This should be represented as uint16. Copy the bytes appropriately - for 0 or 1 or 2 bytes to be converted to uint16. Then free the allocated buffer. */ - uint16_t int_value = 0; - if (attribute_size == 2) { - memcpy(&int_value, value, attribute_size); - } else if (attribute_size == 1) { - int_value = (uint16_t)*value; - } - default_value = int_value; - esp_matter_mem_free(value); - } - return default_value; -} - -static esp_err_t set_default_value_from_current_val(attribute_t *attribute, esp_matter_attr_val_t *min, esp_matter_attr_val_t *max) -{ - VerifyOrReturnError(attribute, ESP_FAIL, ESP_LOGE(TAG, "Attribute cannot be NULL")); - _attribute_t *current_attribute = (_attribute_t *)attribute; - - EmberAfAttributeMetadata *matter_attribute = get_external_attribute_metadata(current_attribute); - if (!matter_attribute) { - ESP_LOGE(TAG, "Attribute Metadata is not found"); - return ESP_ERR_NOT_FOUND; - } - - esp_matter_attr_val_t *val = ¤t_attribute->val; - - /* Get size */ - EmberAfAttributeType attribute_type = 0; - uint16_t attribute_size = 0; - get_data_from_attr_val(val, &attribute_type, &attribute_size, NULL); - - /* Get and set value */ - if (current_attribute->flags & ATTRIBUTE_FLAG_MIN_MAX) { - EmberAfAttributeMinMaxValue *temp_value = (EmberAfAttributeMinMaxValue *)esp_matter_mem_calloc(1, - sizeof(EmberAfAttributeMinMaxValue)); - VerifyOrReturnError(temp_value, ESP_FAIL, ESP_LOGE(TAG, "Could not allocate ptrToMinMaxValue for default value")); - temp_value->defaultValue = get_default_value_from_data(val, attribute_type, attribute_size); - temp_value->minValue = get_default_value_from_data(min, attribute_type, attribute_size); - temp_value->maxValue = get_default_value_from_data(max, attribute_type, attribute_size); - matter_attribute->defaultValue.ptrToMinMaxValue = temp_value; - } else if (attribute_size > 2) { - EmberAfDefaultAttributeValue temp_value = get_default_value_from_data(val, attribute_type, attribute_size); - matter_attribute->defaultValue.ptrToDefaultValue = temp_value.ptrToDefaultValue; - } else { - EmberAfDefaultAttributeValue temp_value = get_default_value_from_data(val, attribute_type, attribute_size); - matter_attribute->defaultValue.defaultValue = temp_value.defaultValue; - } - return ESP_OK; -} -} /* attribute */ - -namespace endpoint { - -static int get_next_index() -{ - uint16_t endpoint_id = 0; - for (int index = 0; index < MAX_ENDPOINT_COUNT; index++) { - endpoint_id = emberAfEndpointFromIndex(index); - if (endpoint_id == kInvalidEndpointId) { - return index; - } - } - return 0xFFFF; -} - -#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL -// global instance so that we can reset it when needed. -// We may need to reset it when new endpoint is added or existing endpoint is removed. -// This is specifically for bridged device. -static chip::Credentials::GroupDataProviderImpl *s_group_data_provider = nullptr; -static uint16_t s_groups_server_cluster_count = 0; - -static void resize_group_data_provider() -{ - // don't do anything if the count is the same - uint16_t groups_server_cluster_count = node::get_server_cluster_endpoint_count(chip::app::Clusters::Groups::Id); - if (s_groups_server_cluster_count == groups_server_cluster_count) { - return; - } - - s_groups_server_cluster_count = groups_server_cluster_count; - uint16_t max_groups_per_fabric = s_groups_server_cluster_count * MAX_GROUPS_PER_FABRIC_PER_ENDPOINT; - auto group_data_provider = new (std::nothrow) chip::Credentials::GroupDataProviderImpl(max_groups_per_fabric, CHIP_CONFIG_MAX_GROUP_KEYS_PER_FABRIC); - if (!group_data_provider) { - ESP_LOGE(TAG, "Failed to allocate memory for group data provider"); - return; - } - - group_data_provider->SetStorageDelegate(&chip::Server::GetInstance().GetPersistentStorage()); - group_data_provider->SetSessionKeystore(chip::Server::GetInstance().GetSessionKeystore()); - - // As we are re-using the persistent storage instance from the Server class instance, - // which has all the data from the previous endpoints, so no harm in re-sizing. - group_data_provider->Init(); - - // delete the old one if it exists - if (s_group_data_provider) { - delete s_group_data_provider; - } - - s_group_data_provider = group_data_provider; - chip::Credentials::SetGroupDataProvider(s_group_data_provider); -} -#endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL - -static esp_err_t disable(endpoint_t *endpoint) -{ - /* Take lock if not already taken */ - lock::status_t lock_status = lock::chip_stack_lock(portMAX_DELAY); - - VerifyOrReturnError(lock_status != lock::FAILED, ESP_FAIL, ESP_LOGE(TAG, "Could not get task context")); - - /* Remove endpoint */ - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - int endpoint_index = emberAfGetDynamicIndexFromEndpoint(current_endpoint->endpoint_id); - if (endpoint_index == 0xFFFF) { - ESP_LOGE(TAG, "Could not find endpoint index"); - if (lock_status == lock::SUCCESS) { - lock::chip_stack_unlock(); - } - return ESP_FAIL; - } - emberAfClearDynamicEndpoint(endpoint_index); - - if (lock_status == lock::SUCCESS) { - lock::chip_stack_unlock(); - } - - /* Delete identify */ - if (current_endpoint->identify) { - chip::Platform::Delete(current_endpoint->identify); - current_endpoint->identify = NULL; - } - - return ESP_OK; -} - -esp_err_t enable(endpoint_t *endpoint) -{ - VerifyOrReturnError(endpoint, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Endpoint cannot be NULL")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - - /* Device types */ - EmberAfDeviceType *device_types_ptr = (EmberAfDeviceType *)esp_matter_mem_calloc(current_endpoint->device_type_count, sizeof(EmberAfDeviceType)); - if (!device_types_ptr) { - ESP_LOGE(TAG, "Couldn't allocate device_types"); - /* goto cleanup is not used here to avoid 'crosses initialization' of device_types below */ - return ESP_ERR_NO_MEM; - } - for (size_t i = 0; i < current_endpoint->device_type_count; ++i) { - device_types_ptr[i].deviceTypeId = current_endpoint->device_type_ids[i]; - device_types_ptr[i].deviceTypeRevision = current_endpoint->device_type_versions[i]; - } - chip::Span device_types(device_types_ptr, current_endpoint->device_type_count); - current_endpoint->device_types_ptr = device_types_ptr; - - /* Clusters */ - _cluster_t *cluster = current_endpoint->cluster_list; - int cluster_count = SinglyLinkedList<_cluster_t>::count(cluster); - int cluster_index = 0; - - DataVersion *data_versions_ptr = (DataVersion *)esp_matter_mem_calloc(1, cluster_count * sizeof(DataVersion)); - if (!data_versions_ptr) { - ESP_LOGE(TAG, "Couldn't allocate data_versions"); - esp_matter_mem_free(device_types_ptr); - current_endpoint->device_types_ptr = NULL; - /* goto cleanup is not used here to avoid 'crosses initialization' of data_versions below */ - return ESP_ERR_NO_MEM; - } - chip::Span data_versions(data_versions_ptr, cluster_count); - current_endpoint->data_versions_ptr = data_versions_ptr; - - /* Variables */ - /* This is needed to avoid 'crosses initialization' errors because of goto */ - esp_err_t err = ESP_OK; - lock::status_t lock_status = lock::FAILED; - CHIP_ERROR status = CHIP_NO_ERROR; - CommandId *accepted_command_ids = NULL; - CommandId *generated_command_ids = NULL; - _command_t *command = NULL; - command_entry_t *command_list = NULL; - uint32_t cluster_id = kInvalidClusterId; - int command_count = 0; - int command_index = 0; - int command_flag = COMMAND_FLAG_NONE; - EventId *event_ids = NULL; - _event_t *event = NULL; - int event_count = 0; - int event_index = 0; - int endpoint_index = 0; - - while (cluster) { - /* Attributes */ - /* Handled in attribute::create() */ - - /* Commands */ - command = NULL; - command_count = 0; - command_index = 0; - command_flag = COMMAND_FLAG_NONE; - accepted_command_ids = NULL; - generated_command_ids = NULL; - cluster_id = cluster::get_id((cluster_t*)cluster); - - /* Init identify if exists and not initialized */ - if (cluster_id == chip::app::Clusters::Identify::Id && current_endpoint->identify == NULL) { - _attribute_t *identify_type_attr = (_attribute_t *)attribute::get( - current_endpoint->endpoint_id, cluster_id, chip::app::Clusters::Identify::Attributes::IdentifyType::Id); - if (identify_type_attr) { - if (identification::init(current_endpoint->endpoint_id, identify_type_attr->val.val.u8) != ESP_OK) { - ESP_LOGE(TAG, "Failed to init identification"); - err = ESP_FAIL; - break; - } - } else { - ESP_LOGE(TAG, "Can't get IdentifyType attribute in Identify cluster"); - err = ESP_ERR_INVALID_STATE; - break; - } - } - - /* Client Generated Commands */ - command_flag = COMMAND_FLAG_ACCEPTED; - command = cluster->command_list; - command_count = SinglyLinkedList<_command_t>::count_with_flag(command, command_flag); - command_count += command::get_cluster_accepted_command_count(cluster_id); - if (command_count > 0) { - command_index = 0; - accepted_command_ids = (CommandId *)esp_matter_mem_calloc(1, (command_count + 1) * sizeof(CommandId)); - if (!accepted_command_ids) { - ESP_LOGE(TAG, "Couldn't allocate accepted_command_ids"); - err = ESP_ERR_NO_MEM; - break; - } - while (command) { - if (command->flags & command_flag) { - accepted_command_ids[command_index] = command->command_id; - command_index++; - } - command = command->next; - } - command_list = command::get_cluster_accepted_command_list(cluster_id); - for(size_t index = 0; command_index < command_count && command_list; index++) { - accepted_command_ids[command_index] = command_list[index].command_id; - command_index++; - } - accepted_command_ids[command_index] = kInvalidCommandId; - } - - /* Server Generated Commands */ - command_flag = COMMAND_FLAG_GENERATED; - command = cluster->command_list; - command_count = SinglyLinkedList<_command_t>::count_with_flag(command, command_flag); - command_count += command::get_cluster_generated_command_count(cluster_id); - if (command_count > 0) { - command_index = 0; - generated_command_ids = (CommandId *)esp_matter_mem_calloc(1, (command_count + 1) * sizeof(CommandId)); - if (!generated_command_ids) { - ESP_LOGE(TAG, "Couldn't allocate generated_command_ids"); - err = ESP_ERR_NO_MEM; - break; - } - while (command) { - if (command->flags & command_flag) { - generated_command_ids[command_index] = command->command_id; - command_index++; - } - command = command->next; - } - command_list = command::get_cluster_generated_command_list(cluster_id); - for(size_t index = 0; command_index < command_count && command_list; index++) { - generated_command_ids[command_index] = command_list[index].command_id; - command_index++; - } - generated_command_ids[command_index] = kInvalidCommandId; - } - - /* Event */ - event = cluster->event_list; - event_count = SinglyLinkedList<_event_t>::count(event); - if (event_count > 0) { - event_index = 0; - event_ids = (EventId *)esp_matter_mem_calloc(1, (event_count + 1) * sizeof(EventId)); - if (!event_ids) { - ESP_LOGE(TAG, "Couldn't allocate event_ids"); - err = ESP_ERR_NO_MEM; - break; - } - while (event) { - event_ids[event_index] = event->event_id; - event_index++; - event = event->next; - } - event_ids[event_index] = chip::kInvalidEventId; - } - - /* Fill up the cluster */ - EmberAfCluster *matter_clusters = (EmberAfCluster *)(¤t_endpoint->endpoint_type->cluster[cluster_index]); - matter_clusters->attributes = cluster->matter_attributes; - matter_clusters->acceptedCommandList = accepted_command_ids; - matter_clusters->generatedCommandList = generated_command_ids; - matter_clusters->eventList = event_ids; - matter_clusters->eventCount = event_count; - - /* Get next cluster */ - current_endpoint->endpoint_type->endpointSize += matter_clusters->clusterSize; - cluster = cluster->next; - cluster_index++; - - /* This is to avoid double free in case of errors */ - accepted_command_ids = NULL; - generated_command_ids = NULL; - event_ids = NULL; - } - if (err != ESP_OK) { - goto cleanup; - } - - current_endpoint->endpoint_type->clusterCount = cluster_count; - - /* Take lock if not already taken */ - lock_status = lock::chip_stack_lock(portMAX_DELAY); - if (lock_status == lock::FAILED) { - ESP_LOGE(TAG, "Could not get task context"); - goto cleanup; - } - - /* Add Endpoint */ - endpoint_index = endpoint::get_next_index(); - status = emberAfSetDynamicEndpoint(endpoint_index, current_endpoint->endpoint_id, current_endpoint->endpoint_type, data_versions, - device_types, current_endpoint->parent_endpoint_id); - if (status != CHIP_NO_ERROR) { - ESP_LOGE(TAG, "Error adding dynamic endpoint %" PRIu16 ": %" CHIP_ERROR_FORMAT, current_endpoint->endpoint_id, status.Format()); - err = ESP_FAIL; - if (lock_status == lock::SUCCESS) { - lock::chip_stack_unlock(); - } - goto cleanup; - } - if (lock_status == lock::SUCCESS) { - lock::chip_stack_unlock(); - } - ESP_LOGI(TAG, "Dynamic endpoint %" PRIu16 " added", current_endpoint->endpoint_id); - -#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL - // resize the group data provider to match the new endpoint count - resize_group_data_provider(); -#endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL - - return err; - -cleanup: - esp_matter_mem_free(generated_command_ids); - esp_matter_mem_free(accepted_command_ids); - esp_matter_mem_free(event_ids); - if (current_endpoint->endpoint_type->cluster) { - for (int cluster_index = 0; cluster_index < cluster_count; cluster_index++) { - /* Free attributes */ - esp_matter_mem_free((void *)current_endpoint->endpoint_type->cluster[cluster_index].attributes); - /* Free commands */ - esp_matter_mem_free((void *)current_endpoint->endpoint_type->cluster[cluster_index].acceptedCommandList); - esp_matter_mem_free((void *)current_endpoint->endpoint_type->cluster[cluster_index].generatedCommandList); - /* Free events */ - esp_matter_mem_free((void *)current_endpoint->endpoint_type->cluster[cluster_index].eventList); - } - - } - esp_matter_mem_free(data_versions_ptr); - current_endpoint->data_versions_ptr = NULL; - esp_matter_mem_free(device_types_ptr); - current_endpoint->device_types_ptr = NULL; - return err; -} - -static esp_err_t enable_all() -{ - node_t *node = node::get(); - /* Not returning error, since the node will not be initialized for application using the data model from zap */ - VerifyOrReturnError(node, ESP_OK); - - endpoint_t *endpoint = get_first(node); - while (endpoint) { - enable(endpoint); - endpoint = get_next(endpoint); - } - return ESP_OK; -} -} /* endpoint */ +#endif // CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER namespace lock { #define DEFAULT_TICKS (500 / portTICK_PERIOD_MS) /* 500 ms in ticks */ @@ -801,6 +223,7 @@ static void esp_matter_chip_init_task(intptr_t context) ESP_LOGE(TAG, "Failed to add fabric delegate, err:%" CHIP_ERROR_FORMAT, ret.Format()); } chip::Server::GetInstance().Init(initParams); +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL if (endpoint::enable_all() != ESP_OK) { ESP_LOGE(TAG, "Enable all endpoints failure"); } @@ -813,7 +236,9 @@ static void esp_matter_chip_init_task(intptr_t context) if (GetDiagnosticDataProvider().GetBootReason(bootReason) == CHIP_NO_ERROR) { chip::app::Clusters::GeneralDiagnosticsServer::Instance().OnDeviceReboot(bootReason); } - + // Initialise clusters which have delegate implemented + esp_matter::cluster::delegate_init_callback_common(); +#endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL #if CHIP_CONFIG_ENABLE_ICD_SERVER if (!icd::get_icd_server_enabled()) { // ICD server has been initialized in chip::Server::GetInstance().Init(). disable it here if @@ -827,10 +252,6 @@ static void esp_matter_chip_init_task(intptr_t context) chip::Server::GetInstance().GetICDManager().Shutdown(); } #endif // CHIP_CONFIG_ENABLE_ICD_SERVER - - // Initialise clusters which have delegate implemented - esp_matter::cluster::delegate_init_callback_common(); - PlatformMgr().ScheduleWork(deinit_ble_if_commissioned, reinterpret_cast(nullptr)); xTaskNotifyGive(task_to_notify); } @@ -916,8 +337,10 @@ static esp_err_t chip_init(event_callback_t callback, intptr_t callback_arg) } init_thread_stack_and_start_thread_task(); #if CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL // Add bounds to all attributes esp_matter::cluster::add_bounds_callback_common(); +#endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL PlatformMgr().ScheduleWork(esp_matter_chip_init_task, reinterpret_cast(xTaskGetCurrentTaskHandle())); // Wait for the matter stack to be initialized @@ -943,16 +366,17 @@ esp_err_t start(event_callback_t callback, intptr_t callback_arg) #if CHIP_DEVICE_CONFIG_ENABLE_WIFI VerifyOrReturnError(chip::DeviceLayer::Internal::ESP32Utils::InitWiFiStack() == CHIP_NO_ERROR, ESP_FAIL, ESP_LOGE(TAG, "Error initializing Wi-Fi stack")); #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL esp_matter_ota_requestor_init(); +#endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL err = chip_init(callback, callback_arg); VerifyOrReturnError(err == ESP_OK, err, ESP_LOGE(TAG, "Error initializing matter")); #if CHIP_DEVICE_CONFIG_ENABLE_THREAD -#ifdef CONFIG_ESP_MATTER_ENABLE_OPENTHREAD +#if defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_OPENTHREAD) // If Thread is Provisioned, publish the dns service if (chip::DeviceLayer::ConnectivityMgr().IsThreadProvisioned() && (chip::Server::GetInstance().GetFabricTable().FabricCount() != 0)) { - PlatformMgr().ScheduleWork([](intptr_t){ chip::app::DnssdServer::Instance().StartServer(); }, reinterpret_cast(nullptr)); } @@ -972,6 +396,7 @@ esp_err_t start(event_callback_t callback, intptr_t callback_arg) esp_err_t factory_reset() { esp_err_t err = ESP_OK; +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL node_t *node = node::get(); if (node) { /* ESP Matter data model is used. Erase all the data that we have added in nvs. */ @@ -989,1219 +414,14 @@ esp_err_t factory_reset() nvs_close(handle); } } - +#endif /* Submodule factory reset. This also restarts after completion. */ +#ifdef CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER chip::Server::GetInstance().ScheduleFactoryReset(); +#else // CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER + ConfigurationMgr().InitiateFactoryReset(); +#endif // !CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER return err; } -namespace attribute { -attribute_t *create(cluster_t *cluster, uint32_t attribute_id, uint16_t flags, esp_matter_attr_val_t val, - uint16_t max_val_size) -{ - /* Find */ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - attribute_t *existing_attribute = get(cluster, attribute_id); - if (existing_attribute) { - ESP_LOGW(TAG, "Attribute 0x%08" PRIX32 " on cluster 0x%08" PRIX32 " already exists. Not creating again.", attribute_id, - cluster::get_id(cluster)); - return existing_attribute; - } - - endpoint_t *endpoint = endpoint::get(current_cluster->endpoint_id); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - - /* Matter attributes */ - EmberAfCluster *matter_clusters = (EmberAfCluster *)(¤t_endpoint->endpoint_type->cluster[current_cluster->index]); - matter_clusters->attributeCount++; - int attribute_count = matter_clusters->attributeCount; - - if (current_cluster->matter_attributes) { - current_cluster->matter_attributes = (EmberAfAttributeMetadata *)esp_matter_mem_realloc(current_cluster->matter_attributes, attribute_count * sizeof(EmberAfAttributeMetadata)); - } else { - current_cluster->matter_attributes = (EmberAfAttributeMetadata *)esp_matter_mem_calloc(1, attribute_count * sizeof(EmberAfAttributeMetadata)); - } - if (!current_cluster->matter_attributes) { - ESP_LOGE(TAG, "Couldn't allocate matter_attributes"); - return NULL; - } - - /* Set */ - EmberAfAttributeMetadata *matter_attribute = ¤t_cluster->matter_attributes[attribute_count - 1]; - matter_attribute->attributeId = attribute_id; - - /* esp-matter uses uint16_t as the flags for the extras, EmberAfAttributeMetadata uses uint8_t as the mask. - The conversion from uint16 to uint8 is as expected for that the extra flags are only used in esp-matter. */ - matter_attribute->mask = static_cast(flags); - if (!(flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY)) { - matter_attribute->mask |= ATTRIBUTE_FLAG_EXTERNAL_STORAGE; - } - matter_attribute->attributeType = 0; - matter_attribute->size = 0; - _attribute_t *attribute = NULL; - if (!(flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY)) { - /* Allocate */ - attribute = (_attribute_t *)esp_matter_mem_calloc(1, sizeof(_attribute_t)); - if (!attribute) { - ESP_LOGE(TAG, "Couldn't allocate _attribute_t"); - return NULL; - } - attribute->index = attribute_count - 1; - attribute->attribute_id = attribute_id; - attribute->cluster_id = matter_clusters->clusterId; - attribute->endpoint_id = current_cluster->endpoint_id; - attribute->flags = flags; - attribute->flags |= ATTRIBUTE_FLAG_EXTERNAL_STORAGE; - - // After reboot, string and array are treated as Invalid. So need to store val.type and size of attribute value. - attribute->val.type = val.type; - if (val.type == ESP_MATTER_VAL_TYPE_CHAR_STRING || - val.type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING || - val.type == ESP_MATTER_VAL_TYPE_OCTET_STRING || - val.type == ESP_MATTER_VAL_TYPE_LONG_OCTET_STRING || - val.type == ESP_MATTER_VAL_TYPE_ARRAY) { - attribute->val.val.a.s = val.val.a.s; - attribute->val.val.a.n = val.val.a.n; - attribute->val.val.a.t = val.val.a.t; - } - - bool attribute_updated = false; - if (flags & ATTRIBUTE_FLAG_NONVOLATILE) { - // Lets directly read into attribute->val so that we don't have to set the attribute value again. - esp_err_t err = get_val_from_nvs(attribute->endpoint_id, attribute->cluster_id, attribute_id, - attribute->val); - if (err == ESP_OK) { - attribute_updated = true; - } - } - if (!attribute_updated) { - set_val((attribute_t *)attribute, &val); - } - - set_default_value_from_current_val((attribute_t *)attribute, NULL, NULL); - - attribute::get_data_from_attr_val(&attribute->val, &matter_attribute->attributeType, - &matter_attribute->size, NULL); - if (attribute->val.type == ESP_MATTER_VAL_TYPE_CHAR_STRING || - attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING) { - uint16_t size_for_storing_str_len = attribute->val.val.a.t - attribute->val.val.a.s; - matter_attribute->size = max_val_size + size_for_storing_str_len; - } - matter_clusters->clusterSize += matter_attribute->size; - } else { - attribute = (_attribute_t *)esp_matter_mem_calloc(1, sizeof(_attribute_base_t)); - attribute->attribute_id = attribute_id; - attribute->index = attribute_count - 1; - attribute->flags = flags; - } - - /* Add */ - SinglyLinkedList<_attribute_base_t>::append(¤t_cluster->attribute_list, attribute); - return (attribute_t *)attribute; -} - -static esp_err_t destroy(attribute_t *attribute) -{ - VerifyOrReturnError(attribute, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Attribute cannot be NULL")); - _attribute_t *current_attribute = (_attribute_t *)attribute; - - if (current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY) { - // For attribute managed internally, free as the _attribute_base_t pointer. - esp_matter_mem_free((_attribute_base_t *)attribute); - return ESP_OK; - } - - /* Default value needs to be deleted first since it uses the current val. */ - free_default_value(attribute); - - /* Delete val here, if required */ - if (current_attribute->val.type == ESP_MATTER_VAL_TYPE_CHAR_STRING || - current_attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING || - current_attribute->val.type == ESP_MATTER_VAL_TYPE_OCTET_STRING || - current_attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_OCTET_STRING || - current_attribute->val.type == ESP_MATTER_VAL_TYPE_ARRAY) { - /* Free buf */ - esp_matter_mem_free(current_attribute->val.val.a.b); - } - - /* Erase the persistent data */ - if (attribute::get_flags(attribute) & ATTRIBUTE_FLAG_NONVOLATILE) { - erase_val_in_nvs(current_attribute->endpoint_id, current_attribute->cluster_id, current_attribute->attribute_id); - } - - /* Free */ - esp_matter_mem_free(current_attribute); - return ESP_OK; -} - -attribute_t *get(cluster_t *cluster, uint32_t attribute_id) -{ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - _attribute_base_t *current_attribute = current_cluster->attribute_list; - while (current_attribute) { - if (current_attribute->attribute_id == attribute_id) { - break; - } - current_attribute = current_attribute->next; - } - - return (attribute_t *)current_attribute; -} - -attribute_t *get(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id) -{ - cluster_t *cluster = cluster::get(endpoint_id, cluster_id); - return get(cluster, attribute_id); -} - -attribute_t *get_first(cluster_t *cluster) -{ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - return (attribute_t *)current_cluster->attribute_list; -} - -attribute_t *get_next(attribute_t *attribute) -{ - VerifyOrReturnValue(attribute, NULL, ESP_LOGE(TAG, "Attribute cannot be NULL")); - _attribute_t *current_attribute = (_attribute_t *)attribute; - return (attribute_t *)current_attribute->next; -} - -uint32_t get_id(attribute_t *attribute) -{ - VerifyOrReturnValue(attribute, kInvalidAttributeId, ESP_LOGE(TAG, "Attribute cannot be NULL")); - _attribute_t *current_attribute = (_attribute_t *)attribute; - return current_attribute->attribute_id; -} - -constexpr uint16_t k_deferred_attribute_persistence_time_ms = CONFIG_ESP_MATTER_DEFERRED_ATTR_PERSISTENCE_TIME_MS; - -static void deferred_attribute_write(chip::System::Layer *layer, void *attribute_ptr) -{ - _attribute_t *current_attribute = (_attribute_t *)attribute_ptr; - ESP_LOGI(TAG, "Store the deferred attribute 0x%" PRIx32 " of cluster 0x%" PRIX32 " on endpoint 0x%" PRIx16, - current_attribute->attribute_id, current_attribute->cluster_id, current_attribute->endpoint_id); - store_val_in_nvs(current_attribute->endpoint_id, current_attribute->cluster_id, current_attribute->attribute_id, - current_attribute->val); -} - -esp_err_t set_val(attribute_t *attribute, esp_matter_attr_val_t *val) -{ - VerifyOrReturnError(attribute, ESP_FAIL, ESP_LOGE(TAG, "Attribute cannot be NULL")); - _attribute_t *current_attribute = (_attribute_t *)attribute; - - ESP_RETURN_ON_FALSE(!(current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY), ESP_ERR_NOT_SUPPORTED, TAG, - "Attribute is not managed by esp matter data model"); - - if (val->type == ESP_MATTER_VAL_TYPE_CHAR_STRING || val->type == ESP_MATTER_VAL_TYPE_OCTET_STRING || - val->type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING || val->type == ESP_MATTER_VAL_TYPE_LONG_OCTET_STRING || - val->type == ESP_MATTER_VAL_TYPE_ARRAY) { - /* Free old buf */ - esp_matter_mem_free(current_attribute->val.val.a.b); - current_attribute->val.val.a.b = NULL; - if (val->val.a.s > 0) { - /* Alloc new buf */ - uint8_t *new_buf = (uint8_t *)esp_matter_mem_calloc(1, val->val.a.s); - VerifyOrReturnError(new_buf, ESP_ERR_NO_MEM, ESP_LOGE(TAG, "Could not allocate new buffer")); - /* Copy to new buf and assign */ - memcpy(new_buf, val->val.a.b, val->val.a.s); - current_attribute->val.val.a.b = new_buf; - current_attribute->val.val.a.s = val->val.a.s; - current_attribute->val.val.a.n = val->val.a.n; - current_attribute->val.val.a.t = val->val.a.t; - } else { - ESP_LOGD(TAG, "Set val called with string with size 0"); - } - } else { - memcpy((void *)¤t_attribute->val, (void *)val, sizeof(esp_matter_attr_val_t)); - } - - if (current_attribute->flags & ATTRIBUTE_FLAG_NONVOLATILE) { - if (current_attribute->flags & ATTRIBUTE_FLAG_DEFERRED) { - if (!chip::DeviceLayer::SystemLayer().IsTimerActive(deferred_attribute_write, current_attribute)) { - auto & system_layer = chip::DeviceLayer::SystemLayer(); - system_layer.StartTimer(chip::System::Clock::Milliseconds16(k_deferred_attribute_persistence_time_ms), - deferred_attribute_write, current_attribute); - } - } else { - store_val_in_nvs(current_attribute->endpoint_id, current_attribute->cluster_id, - current_attribute->attribute_id, current_attribute->val); - } - } - return ESP_OK; -} - -esp_err_t get_val(attribute_t *attribute, esp_matter_attr_val_t *val) -{ - VerifyOrReturnError(attribute, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Attribute cannot be NULL")); - _attribute_t *current_attribute = (_attribute_t *)attribute; - - ESP_RETURN_ON_FALSE(!(current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY), ESP_ERR_NOT_SUPPORTED, TAG, - "Attribute is not managed by esp matter data model"); - memcpy((void *)val, (void *)¤t_attribute->val, sizeof(esp_matter_attr_val_t)); - return ESP_OK; -} - -esp_err_t add_bounds(attribute_t *attribute, esp_matter_attr_val_t min, esp_matter_attr_val_t max) -{ - VerifyOrReturnError(attribute, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Attribute cannot be NULL")); - _attribute_t *current_attribute = (_attribute_t *)attribute; - - ESP_RETURN_ON_FALSE(!(current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY), ESP_ERR_NOT_SUPPORTED, TAG, - "Attribute is not managed by esp matter data model"); - - /* Check if bounds can be set */ - if (current_attribute->val.type == ESP_MATTER_VAL_TYPE_CHAR_STRING || - current_attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING || - current_attribute->val.type == ESP_MATTER_VAL_TYPE_OCTET_STRING || - current_attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_OCTET_STRING || - current_attribute->val.type == ESP_MATTER_VAL_TYPE_ARRAY) { - ESP_LOGE(TAG, "Bounds cannot be set for string/array type attributes"); - return ESP_ERR_INVALID_ARG; - } - VerifyOrReturnError(((current_attribute->val.type == min.type) && (current_attribute->val.type == max.type)), ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Cannot set bounds because of val type mismatch: expected: %d, min: %d, max: %d", - current_attribute->val.type, min.type, max.type)); - - EmberAfAttributeMetadata *matter_attribute= get_external_attribute_metadata(current_attribute); - if (!matter_attribute) { - ESP_LOGE(TAG, "Attribute Metadata is not found"); - return ESP_ERR_NOT_FOUND; - } - matter_attribute->mask |= ATTRIBUTE_FLAG_MIN_MAX; - current_attribute->flags |= ATTRIBUTE_FLAG_MIN_MAX; - - /* Set the default value again after setting the bounds and the flag */ - set_default_value_from_current_val(attribute, &min, &max); - return ESP_OK; -} - -esp_err_t get_bounds(attribute_t *attribute, esp_matter_attr_bounds_t *bounds) -{ - if (!attribute || !bounds) { - ESP_LOGE(TAG, "Attribute or bounds cannot be NULL"); - return ESP_ERR_INVALID_ARG; - } - _attribute_t *current_attribute = (_attribute_t *)attribute; - - EmberAfAttributeMetadata *matter_attribute= get_external_attribute_metadata(current_attribute); - if (!matter_attribute) { - ESP_LOGE(TAG, "Attribute Metadata is not found"); - return ESP_ERR_NOT_FOUND; - } - - if (!(matter_attribute->mask & ATTRIBUTE_FLAG_MIN_MAX)) { - ESP_LOGW(TAG, "Endpoint 0x%04" PRIX16 "'s Cluster 0x%08" PRIX32 "'s Attribute 0x%08" PRIX32 " has not set bounds", - current_attribute->endpoint_id, current_attribute->cluster_id, matter_attribute->attributeId); - return ESP_ERR_INVALID_ARG; - } - - if (matter_attribute->size > 2) { - get_attr_val_from_data(&bounds->min, matter_attribute->attributeType, matter_attribute->size, (uint8_t *)matter_attribute->defaultValue.ptrToMinMaxValue->minValue.ptrToDefaultValue, matter_attribute); - get_attr_val_from_data(&bounds->max, matter_attribute->attributeType, matter_attribute->size, (uint8_t *)matter_attribute->defaultValue.ptrToMinMaxValue->maxValue.ptrToDefaultValue, matter_attribute); - } else { - uint8_t value[2]; - uint16_t min_value = matter_attribute->defaultValue.ptrToMinMaxValue->minValue.defaultValue; - memcpy(value, &min_value, matter_attribute->size); - get_attr_val_from_data(&bounds->min, matter_attribute->attributeType, matter_attribute->size, value, matter_attribute); - uint16_t max_value = matter_attribute->defaultValue.ptrToMinMaxValue->maxValue.defaultValue; - memcpy(value, &max_value, matter_attribute->size); - get_attr_val_from_data(&bounds->max, matter_attribute->attributeType, matter_attribute->size, value, matter_attribute); - } - return ESP_OK; -} - -uint16_t get_flags(attribute_t *attribute) -{ - VerifyOrReturnValue(attribute, 0, ESP_LOGE(TAG, "Attribute cannot be NULL")); - _attribute_t *current_attribute = (_attribute_t *)attribute; - return current_attribute->flags; -} - -esp_err_t set_override_callback(attribute_t *attribute, callback_t callback) -{ - VerifyOrReturnError(attribute, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Attribute cannot be NULL")); - _attribute_t *current_attribute = (_attribute_t *)attribute; - - ESP_RETURN_ON_FALSE(!(current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY), ESP_ERR_NOT_SUPPORTED, TAG, - "Attribute is not managed by esp matter data model"); - - cluster_t *cluster = cluster::get(current_attribute->endpoint_id, current_attribute->cluster_id); - - if (current_attribute->val.type == ESP_MATTER_VAL_TYPE_ARRAY || - current_attribute->val.type == ESP_MATTER_VAL_TYPE_OCTET_STRING || - current_attribute->val.type == ESP_MATTER_VAL_TYPE_CHAR_STRING || - current_attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_CHAR_STRING || - current_attribute->val.type == ESP_MATTER_VAL_TYPE_LONG_OCTET_STRING) { - // The override callback might allocate memory and we have no way to free the memory - // TODO: Add memory-safe override callback for these attribute types - ESP_LOGE(TAG, "Cannot set override callback for attribute 0x%" PRIX32 " on cluster 0x%" PRIX32, - current_attribute->attribute_id, cluster::get_id(cluster)); - return ESP_ERR_NOT_SUPPORTED; - } - current_attribute->override_callback = callback; - current_attribute->flags |= ATTRIBUTE_FLAG_OVERRIDE; - return ESP_OK; -} - -callback_t get_override_callback(attribute_t *attribute) -{ - VerifyOrReturnValue(attribute, NULL, ESP_LOGE(TAG, "Attribute cannot be NULL")); - _attribute_t *current_attribute = (_attribute_t *)attribute; - - VerifyOrReturnValue(!(current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY), NULL, ESP_LOGE(TAG, "Attribute is not managed by esp matter data model")); - - return current_attribute->override_callback; -} - -esp_err_t set_deferred_persistence(attribute_t *attribute) -{ - VerifyOrReturnError(attribute, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Attribute cannot be NULL")); - _attribute_t *current_attribute = (_attribute_t *)attribute; - - ESP_RETURN_ON_FALSE(!(current_attribute->flags & ATTRIBUTE_FLAG_MANAGED_INTERNALLY), ESP_ERR_NOT_SUPPORTED, TAG, - "Attribute is not managed by esp matter data model"); - - if (!(current_attribute->flags & ATTRIBUTE_FLAG_NONVOLATILE)) { - ESP_LOGE(TAG, "Attribute should be non-volatile to set a deferred persistence time"); - return ESP_ERR_INVALID_ARG; - } - current_attribute->flags |= ATTRIBUTE_FLAG_DEFERRED; - return ESP_OK; -} - -} /* attribute */ - -namespace command { -command_t *create(cluster_t *cluster, uint32_t command_id, uint8_t flags, callback_t callback) -{ - /* Find */ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - command_t *existing_command = get(cluster, command_id, flags); - if (existing_command) { - ESP_LOGW(TAG, "Command 0x%08" PRIX32 " on cluster 0x%08" PRIX32 " already exists. Not creating again.", command_id, - cluster::get_id(cluster)); - return existing_command; - } - - /* Allocate */ - _command_t *command = (_command_t *)esp_matter_mem_calloc(1, sizeof(_command_t)); - VerifyOrReturnValue(command, NULL, ESP_LOGE(TAG, "Couldn't allocate _command_t")); - - /* Set */ - command->command_id = command_id; - command->flags = flags; - command->callback = callback; - command->user_callback = NULL; - - /* Add */ - SinglyLinkedList<_command_t>::append(¤t_cluster->command_list, command); - return (command_t *)command; -} - -command_t *get(cluster_t *cluster, uint32_t command_id, uint16_t flags) -{ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - _command_t *current_command = (_command_t *)current_cluster->command_list; - while (current_command) { - if ((current_command->command_id == command_id) && (current_command->flags & flags)) { - break; - } - current_command = current_command->next; - } - return (command_t *)current_command; -} - -command_t *get_first(cluster_t *cluster) -{ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - return (command_t *)current_cluster->command_list; -} - -command_t *get_next(command_t *command) -{ - VerifyOrReturnValue(command, NULL, ESP_LOGE(TAG, "Command cannot be NULL")); - _command_t *current_command = (_command_t *)command; - return (command_t *)current_command->next; -} - -uint32_t get_id(command_t *command) -{ - VerifyOrReturnValue(command, kInvalidCommandId, ESP_LOGE(TAG, "Command cannot be NULL")); - _command_t *current_command = (_command_t *)command; - return current_command->command_id; -} - -callback_t get_callback(command_t *command) -{ - VerifyOrReturnValue(command, NULL, ESP_LOGE(TAG, "Command cannot be NULL")); - _command_t *current_command = (_command_t *)command; - return current_command->callback; -} - -callback_t get_user_callback(command_t *command) -{ - VerifyOrReturnValue(command, NULL, ESP_LOGE(TAG, "Command cannot be NULL")); - _command_t *current_command = (_command_t *)command; - return current_command->user_callback; -} - -void set_user_callback(command_t *command, callback_t user_callback) -{ - if (!command) { - ESP_LOGE(TAG, "Command cannot be NULL"); - } - _command_t *current_command = (_command_t *)command; - current_command->user_callback = user_callback; -} - -uint16_t get_flags(command_t *command) -{ - VerifyOrReturnValue(command, 0, ESP_LOGE(TAG, "Command cannot be NULL")); - _command_t *current_command = (_command_t *)command; - return current_command->flags; -} - -} /* command */ - -namespace event { - -event_t *create(cluster_t *cluster, uint32_t event_id) -{ - /* Find */ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - event_t *existing_event = get(cluster, event_id); - if (existing_event) { - ESP_LOGW(TAG, "Event 0x%08" PRIX32 " on cluster 0x%08" PRIX32 " already exists. Not creating again.", event_id, - cluster::get_id(cluster)); - return existing_event; - } - - /* Allocate */ - _event_t *event = (_event_t *)esp_matter_mem_calloc(1, sizeof(_event_t)); - VerifyOrReturnValue(event, NULL, ESP_LOGE(TAG, "Couldn't allocate _event_t")); - - /* Set */ - event->event_id = event_id; - - /* Add */ - SinglyLinkedList<_event_t>::append(¤t_cluster->event_list, event); - return (event_t *)event; -} - -event_t *get(cluster_t *cluster, uint32_t event_id) -{ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - _event_t *current_event = (_event_t *)current_cluster->event_list; - while (current_event) { - if (current_event->event_id == event_id) { - break; - } - current_event = current_event->next; - } - return (event_t *)current_event; -} - -event_t *get_first(cluster_t *cluster) -{ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - return (event_t *)current_cluster->event_list; -} - -event_t *get_next(event_t *event) -{ - VerifyOrReturnValue(event, NULL, ESP_LOGE(TAG, "Event cannot be NULL")); - _event_t *current_event = (_event_t *)event; - return (event_t *)current_event->next; -} - -uint32_t get_id(event_t *event) -{ - VerifyOrReturnValue(event, chip::kInvalidEventId, ESP_LOGE(TAG, "Event cannot be NULL")); - _event_t *current_event = (_event_t *)event; - return current_event->event_id; -} - -} /* event */ - - -namespace cluster { - -cluster_t *create(endpoint_t *endpoint, uint32_t cluster_id, uint8_t flags) -{ - /* Find */ - VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Endpoint cannot be NULL")); - VerifyOrReturnValue(((flags & CLUSTER_FLAG_SERVER) || (flags & CLUSTER_FLAG_CLIENT)), NULL, ESP_LOGE(TAG, "Server or client cluster flag not set")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - cluster_t *existing_cluster = get(endpoint, cluster_id); - if (existing_cluster) { - /* If a server already exists, do not create it again */ - _cluster_t *_existing_cluster = (_cluster_t *)existing_cluster; - // The member EmberAfCluster * in EmberAfEndpointType is const, do a non-const cast to change the mask. - EmberAfClusterMask *cluster_flags = (EmberAfClusterMask *)¤t_endpoint->endpoint_type->cluster[_existing_cluster->index].mask; - if ((*cluster_flags & CLUSTER_FLAG_SERVER) && (flags & CLUSTER_FLAG_SERVER)) { - ESP_LOGW(TAG, "Server Cluster 0x%08" PRIX32 " on endpoint 0x%04" PRIx16 " already exists. Not creating again.", cluster_id, - current_endpoint->endpoint_id); - return existing_cluster; - } - - /* If a client already exists, do not create it again */ - if ((*cluster_flags & CLUSTER_FLAG_CLIENT) && (flags & CLUSTER_FLAG_CLIENT)) { - ESP_LOGW(TAG, "Client Cluster 0x%08" PRIX32 " on endpoint 0x%04" PRIx16 " already exists. Not creating again.", cluster_id, - current_endpoint->endpoint_id); - return existing_cluster; - } - - /* The cluster already exists, but is of a different type. Just update the 'Set' part from below. */ - ESP_LOGI(TAG, "Cluster 0x%08" PRIX32 " on endpoint 0x%04" PRIx16 " already exists. Updating values.", cluster_id, - current_endpoint->endpoint_id); - *cluster_flags |= flags; - return existing_cluster; - } - - /* Allocate */ - _cluster_t *cluster = (_cluster_t *)esp_matter_mem_calloc(1, sizeof(_cluster_t)); - if (!cluster) { - ESP_LOGE(TAG, "Couldn't allocate _cluster_t"); - return NULL; - } - - /* Matter clusters */ - EmberAfCluster *matter_clusters = (EmberAfCluster *)current_endpoint->endpoint_type->cluster; - current_endpoint->cluster_count++; - cluster->index = current_endpoint->cluster_count - 1; - if (matter_clusters) { - matter_clusters = (EmberAfCluster *)esp_matter_mem_realloc(matter_clusters, current_endpoint->cluster_count * sizeof(EmberAfCluster)); - } else { - matter_clusters = (EmberAfCluster *)esp_matter_mem_calloc(1, current_endpoint->cluster_count * sizeof(EmberAfCluster)); - } - if (!matter_clusters) { - ESP_LOGE(TAG, "Couldn't allocate EmberAfCluster"); - return NULL; - } - current_endpoint->endpoint_type->cluster = matter_clusters; - - /* Set */ - EmberAfCluster *matter_cluster = (EmberAfCluster *)¤t_endpoint->endpoint_type->cluster[cluster->index]; - cluster->endpoint_id = current_endpoint->endpoint_id; - - matter_cluster->clusterId = cluster_id; - matter_cluster->mask = flags; - matter_cluster->clusterSize = 0; - matter_cluster->attributeCount = 0; - matter_cluster->functions = NULL; - - /* Add */ - SinglyLinkedList<_cluster_t>::append(¤t_endpoint->cluster_list, cluster); - return (cluster_t *)cluster; -} - -esp_err_t destroy(cluster_t *cluster) -{ - VerifyOrReturnError(cluster, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Cluster cannot be NULL")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - - /* Parse and delete all commands */ - SinglyLinkedList<_command_t>::delete_list(¤t_cluster->command_list); - - /* Parse and delete all attributes */ - _attribute_base_t *attribute = current_cluster->attribute_list; - while (attribute) { - _attribute_base_t *next_attribute = attribute->next; - attribute::destroy((attribute_t *)attribute); - attribute = next_attribute; - } - - /* Parse and delete all events */ - SinglyLinkedList<_event_t>::delete_list(¤t_cluster->event_list); - - /* Free matter_attributes if allocated */ - if (current_cluster->matter_attributes) { - esp_matter_mem_free(current_cluster->matter_attributes); - current_cluster->matter_attributes = NULL; - } - - /* Free */ - esp_matter_mem_free(current_cluster); - return ESP_OK; -} - -cluster_t *get(endpoint_t *endpoint, uint32_t cluster_id) -{ - VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Endpoint cannot be NULL")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - _cluster_t *current_cluster = (_cluster_t *)current_endpoint->cluster_list; - - uint8_t cluster_index = 0; - for (cluster_index = 0; cluster_index < current_endpoint->cluster_count; cluster_index++) { - if (current_endpoint->endpoint_type->cluster[cluster_index].clusterId == cluster_id) { - break; - } - } - if (cluster_index == current_endpoint->cluster_count) { - ESP_LOGD(TAG, "Cluster not found"); - return NULL; - } - - while (current_cluster) { - if (current_cluster->index == cluster_index) { - break; - } - current_cluster = current_cluster->next; - } - return (cluster_t *)current_cluster; -} - -cluster_t *get(uint16_t endpoint_id, uint32_t cluster_id) -{ - endpoint_t *endpoint = endpoint::get(endpoint_id); - return get(endpoint, cluster_id); -} - -cluster_t *get_first(endpoint_t *endpoint) -{ - VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Endpoint cannot be NULL")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - return (cluster_t *)current_endpoint->cluster_list; -} - -cluster_t *get_next(cluster_t *cluster) -{ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - return (cluster_t *)current_cluster->next; -} - -uint32_t get_id(cluster_t *cluster) -{ - VerifyOrReturnValue(cluster, kInvalidClusterId, ESP_LOGE(TAG, "Cluster cannot be NULL")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - endpoint_t *endpoint = endpoint::get(current_cluster->endpoint_id); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - return current_endpoint->endpoint_type->cluster[current_cluster->index].clusterId; -} - -void *get_delegate_impl(cluster_t *cluster) -{ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - return current_cluster->delegate_pointer; -} - -esp_err_t set_plugin_server_init_callback(cluster_t *cluster, plugin_server_init_callback_t callback) -{ - VerifyOrReturnError(cluster, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Cluster cannot be NULL")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - current_cluster->plugin_server_init_callback = callback; - return ESP_OK; -} - -plugin_server_init_callback_t get_plugin_server_init_callback(cluster_t *cluster) -{ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - return current_cluster->plugin_server_init_callback; -} - -esp_err_t set_delegate_and_init_callback(cluster_t *cluster, delegate_init_callback_t callback, void *delegate) -{ - VerifyOrReturnError(cluster, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Cluster cannot be NULL")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - current_cluster->delegate_init_callback = callback; - current_cluster->delegate_pointer = delegate; - return ESP_OK; -} - -delegate_init_callback_t get_delegate_init_callback(cluster_t *cluster) -{ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL.")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - return current_cluster->delegate_init_callback; -} - -esp_err_t set_add_bounds_callback(cluster_t *cluster, add_bounds_callback_t callback) -{ - VerifyOrReturnError(cluster, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Cluster cannot be NULL")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - current_cluster->add_bounds_callback = callback; - return ESP_OK; -} - -add_bounds_callback_t get_add_bounds_callback(cluster_t *cluster) -{ - VerifyOrReturnValue(cluster, NULL, ESP_LOGE(TAG, "Cluster cannot be NULL")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - return current_cluster->add_bounds_callback; -} - -esp_err_t add_function_list(cluster_t *cluster, const function_generic_t *function_list, int function_flags) -{ - VerifyOrReturnError(cluster, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Cluster cannot be NULL")); - _cluster_t *current_cluster = (_cluster_t *)cluster; - - endpoint_t *endpoint = endpoint::get(current_cluster->endpoint_id); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - EmberAfCluster *matter_clusters = (EmberAfCluster *)current_endpoint->endpoint_type->cluster; - matter_clusters[current_cluster->index].mask |= function_flags; - matter_clusters[current_cluster->index].functions = (const EmberAfGenericClusterFunction *)function_list; - return ESP_OK; -} - -} /* cluster */ - -namespace endpoint { - -endpoint_t *create(node_t *node, uint8_t flags, void *priv_data) -{ - /* Find */ - VerifyOrReturnValue(node, NULL, ESP_LOGE(TAG, "Node cannot be NULL")); - _node_t *current_node = (_node_t *)node; - - VerifyOrReturnValue(get_count(node) < CONFIG_ESP_MATTER_MAX_DYNAMIC_ENDPOINT_COUNT, NULL, ESP_LOGE(TAG, "Dynamic endpoint count cannot be greater than CONFIG_ESP_MATTER_MAX_DYNAMIC_ENDPOINT_COUNT:%u", - CONFIG_ESP_MATTER_MAX_DYNAMIC_ENDPOINT_COUNT)); - - /* Allocate */ - _endpoint_t *endpoint = (_endpoint_t *)esp_matter_mem_calloc(1, sizeof(_endpoint_t)); - VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Couldn't allocate _endpoint_t")); - - endpoint->endpoint_type = (EmberAfEndpointType *)esp_matter_mem_calloc(1, sizeof(EmberAfEndpointType)); - if (!endpoint->endpoint_type) { - ESP_LOGE(TAG, "Couldn't allocate EmberAfEndpointType"); - esp_matter_mem_free(endpoint); - return NULL; - } - - /* Set */ - endpoint->endpoint_id = current_node->min_unused_endpoint_id++; - endpoint->device_type_count = 0; - endpoint->parent_endpoint_id = chip::kInvalidEndpointId; - endpoint->flags = flags; - endpoint->priv_data = priv_data; -#if defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) - /* Store */ - if (esp_matter_started) { - node::store_min_unused_endpoint_id(); - } -#endif // defined(CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) && defined(CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) - - /* Add */ - SinglyLinkedList<_endpoint_t>::append(¤t_node->endpoint_list, endpoint); - return (endpoint_t *)endpoint; -} - -endpoint_t *resume(node_t *node, uint8_t flags, uint16_t endpoint_id, void *priv_data) -{ - /* Find */ - VerifyOrReturnValue(node, NULL, ESP_LOGE(TAG, "Node cannot be NULL")); - _node_t *current_node = (_node_t *)node; - _endpoint_t *previous_endpoint = NULL; - _endpoint_t *current_endpoint = current_node->endpoint_list; - while (current_endpoint) { - VerifyOrReturnValue(current_endpoint->endpoint_id != endpoint_id, NULL, ESP_LOGE(TAG, "Could not resume an endpoint that has been added to the node")); - previous_endpoint = current_endpoint; - current_endpoint = current_endpoint->next; - } - - /* Check */ - VerifyOrReturnError(endpoint_id < current_node->min_unused_endpoint_id, NULL, ESP_LOGE(TAG, "The endpoint_id of the resumed endpoint should have been used")); - - /* Allocate */ - _endpoint_t *endpoint = (_endpoint_t *)esp_matter_mem_calloc(1, sizeof(_endpoint_t)); - VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Couldn't allocate _endpoint_t")); - - endpoint->endpoint_type = (EmberAfEndpointType *)esp_matter_mem_calloc(1, sizeof(EmberAfEndpointType)); - if (!endpoint->endpoint_type) { - ESP_LOGE(TAG, "Couldn't allocate EmberAfEndpointType"); - esp_matter_mem_free(endpoint); - return NULL; - } - - /* Set */ - endpoint->endpoint_id = endpoint_id; - endpoint->device_type_count = 0; - endpoint->flags = flags; - endpoint->priv_data = priv_data; - - /* Add */ - if (previous_endpoint == NULL) { - current_node->endpoint_list = endpoint; - } else { - previous_endpoint->next = endpoint; - } - - return (endpoint_t *)endpoint; -} - -esp_err_t destroy(node_t *node, endpoint_t *endpoint) -{ - VerifyOrReturnError((node && endpoint), ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Node or endpoint cannot be NULL")); - _node_t *current_node = (_node_t *)node; - _endpoint_t *_endpoint = (_endpoint_t *)endpoint; - - VerifyOrReturnError((_endpoint->flags & ENDPOINT_FLAG_DESTROYABLE), ESP_FAIL, ESP_LOGE(TAG, "This endpoint cannot be deleted since the ENDPOINT_FLAG_DESTROYABLE is not set")); - - /* Disable */ - disable(endpoint); - - /* Find current endpoint */ - _endpoint_t *current_endpoint = current_node->endpoint_list; - _endpoint_t *previous_endpoint = NULL; - while (current_endpoint) { - if (current_endpoint == _endpoint) { - break; - } - previous_endpoint = current_endpoint; - current_endpoint = current_endpoint->next; - } - VerifyOrReturnError(current_endpoint != NULL, ESP_FAIL, ESP_LOGE(TAG, "Could not find the endpoint to delete")); - - /* Parse and delete all clusters */ - _cluster_t *cluster = current_endpoint->cluster_list; - while (cluster) { - _cluster_t *next_cluster = cluster->next; - cluster::destroy((cluster_t *)cluster); - cluster = next_cluster; - /* Move cluster_list to find the remain cluster */ - current_endpoint->cluster_list = cluster; - } - - /* Free endpoint_type after freeing cluster_list */ - { - /* Free all clusters in endpoint_type */ - EmberAfEndpointType *endpoint_type = current_endpoint->endpoint_type; - VerifyOrReturnError(endpoint_type, ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "endpoint %" PRIu16 "'s endpoint_type is NULL", current_endpoint->endpoint_id)); - int cluster_count = endpoint_type->clusterCount; - for (int cluster_index = 0; cluster_index < cluster_count; cluster_index++) { - /* Free commands */ - if (endpoint_type->cluster[cluster_index].acceptedCommandList) { - esp_matter_mem_free((void *)endpoint_type->cluster[cluster_index].acceptedCommandList); - } - if (endpoint_type->cluster[cluster_index].generatedCommandList) { - esp_matter_mem_free((void *)endpoint_type->cluster[cluster_index].generatedCommandList); - } - /* Free events */ - if (endpoint_type->cluster[cluster_index].eventList) { - esp_matter_mem_free((void *)endpoint_type->cluster[cluster_index].eventList); - } - } - esp_matter_mem_free((void *)endpoint_type->cluster); - - /* Free data versions */ - if (current_endpoint->data_versions_ptr) { - esp_matter_mem_free(current_endpoint->data_versions_ptr); - current_endpoint->data_versions_ptr = NULL; - } - - /* Free device types */ - if (current_endpoint->device_types_ptr) { - esp_matter_mem_free(current_endpoint->device_types_ptr); - current_endpoint->device_types_ptr = NULL; - } - - /* Free endpoint type */ - esp_matter_mem_free(endpoint_type); - current_endpoint->endpoint_type = NULL; - } - - /* Remove from list */ - if (previous_endpoint == NULL) { - current_node->endpoint_list = current_endpoint->next; - } else { - previous_endpoint->next = current_endpoint->next; - } - - /* Free */ - if (current_endpoint->identify != NULL) { - chip::Platform::Delete(current_endpoint->identify); - current_endpoint->identify = NULL; - } - esp_matter_mem_free(current_endpoint); - -#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL - // resize the group data provider to match the new endpoint count - resize_group_data_provider(); -#endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL - - return ESP_OK; -} - -endpoint_t *get(node_t *node, uint16_t endpoint_id) -{ - VerifyOrReturnValue(node, NULL, ESP_LOGE(TAG, "Node cannot be NULL")); - _node_t *current_node = (_node_t *)node; - _endpoint_t *current_endpoint = (_endpoint_t *)current_node->endpoint_list; - while (current_endpoint) { - if (current_endpoint->endpoint_id == endpoint_id) { - break; - } - current_endpoint = current_endpoint->next; - } - return (endpoint_t *)current_endpoint; -} - -endpoint_t *get(uint16_t endpoint_id) -{ - node_t *node = node::get(); - return get(node, endpoint_id); -} - - -endpoint_t *get_first(node_t *node) -{ - VerifyOrReturnValue(node, NULL, ESP_LOGE(TAG, "Node cannot be NULL")); - _node_t *current_node = (_node_t *)node; - return (endpoint_t *)current_node->endpoint_list; -} - -endpoint_t *get_next(endpoint_t *endpoint) -{ - VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Endpoint cannot be NULL")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - return (endpoint_t *)current_endpoint->next; -} - -uint16_t get_count(node_t *node) -{ - VerifyOrReturnValue(node, 0, ESP_LOGE(TAG, "Node cannot be NULL")); - uint16_t count = 0; - endpoint_t *endpoint = get_first(node); - while (endpoint) { - count++; - endpoint = get_next(endpoint); - } - return count; - -} - -uint16_t get_id(endpoint_t *endpoint) -{ - VerifyOrReturnValue(endpoint, kInvalidEndpointId, ESP_LOGE(TAG, "Endpoint cannot be NULL")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - return current_endpoint->endpoint_id; -} - -esp_err_t add_device_type(endpoint_t *endpoint, uint32_t device_type_id, uint8_t device_type_version) -{ - VerifyOrReturnError(endpoint, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Endpoint cannot be NULL")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - VerifyOrReturnError(current_endpoint->device_type_count < ESP_MATTER_MAX_DEVICE_TYPE_COUNT, ESP_FAIL, - ESP_LOGE(TAG, "Could not add a new device-type:%" PRIu32 " to the endpoint", device_type_id)); - current_endpoint->device_type_ids[current_endpoint->device_type_count] = device_type_id; - current_endpoint->device_type_versions[current_endpoint->device_type_count] = device_type_version; - current_endpoint->device_type_count++; - return ESP_OK; -} - -uint32_t *get_device_type_ids(endpoint_t *endpoint, uint8_t *device_type_count_ptr) -{ - VerifyOrReturnValue((endpoint && device_type_count_ptr), NULL, ESP_LOGE(TAG, "Endpoint and device type count pointer cannot be NULL")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - *device_type_count_ptr = current_endpoint->device_type_count; - return current_endpoint->device_type_ids; -} - -uint8_t *get_device_type_versions(endpoint_t *endpoint, uint8_t *device_type_count_ptr) -{ - VerifyOrReturnValue((endpoint && device_type_count_ptr), NULL, ESP_LOGE(TAG, "Endpoint and device type count pointer cannot be NULL")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - *device_type_count_ptr = current_endpoint->device_type_count; - return current_endpoint->device_type_versions; -} - -esp_err_t set_parent_endpoint(endpoint_t *endpoint, endpoint_t *parent_endpoint) -{ - VerifyOrReturnError((endpoint && parent_endpoint), ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Endpoint or parent_endpoint cannot be NULL")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - _endpoint_t *current_parent_endpoint = (_endpoint_t *)parent_endpoint; - current_endpoint->parent_endpoint_id = current_parent_endpoint->endpoint_id; - return ESP_OK; -} - -void *get_priv_data(uint16_t endpoint_id) -{ - endpoint_t *endpoint = get(endpoint_id); - VerifyOrReturnValue(endpoint, NULL, ESP_LOGE(TAG, "Endpoint not found")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - return current_endpoint->priv_data; -} - -esp_err_t set_priv_data(uint16_t endpoint_id, void *priv_data) -{ - endpoint_t *endpoint = get(endpoint_id); - VerifyOrReturnError(endpoint, ESP_ERR_NOT_FOUND, ESP_LOGE(TAG, "Endpoint not found")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - current_endpoint->priv_data = priv_data; - return ESP_OK; -} - -esp_err_t set_identify(uint16_t endpoint_id, void *identify) -{ - endpoint_t *endpoint = get(endpoint_id); - VerifyOrReturnError(endpoint, ESP_ERR_INVALID_ARG, ESP_LOGE(TAG, "Endpoint not found")); - _endpoint_t *current_endpoint = (_endpoint_t *)endpoint; - current_endpoint->identify = (Identify *)identify; - return ESP_OK; -} - -} /* endpoint */ - -namespace node { - -node_t *create_raw() -{ - VerifyOrReturnValue(!node, (node_t*) node, ESP_LOGE(TAG, "Node already exists")); - node = (_node_t *)esp_matter_mem_calloc(1, sizeof(_node_t)); - VerifyOrReturnValue(node, NULL, ESP_LOGE(TAG, "Couldn't allocate _node_t")); - return (node_t *)node; -} - -esp_err_t destroy_raw() -{ - VerifyOrReturnError(node, ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "NULL node cannot be destroyed")); - _node_t *current_node = (_node_t *)node; - esp_matter_mem_free(current_node); - node = NULL; - return ESP_OK; -} - -node_t *get() -{ - return (node_t *)node; -} - -esp_err_t destroy() -{ - esp_err_t err = ESP_OK; - node_t *current_node = get(); - VerifyOrReturnError(current_node, ESP_ERR_INVALID_STATE, ESP_LOGE(TAG, "Node cannot be NULL")); - - attribute::set_callback(nullptr); - identification::set_callback(nullptr); - - endpoint_t *current_endpoint = endpoint::get_first(current_node); - endpoint_t *next_endpoint = nullptr; - while (current_endpoint != nullptr) { - next_endpoint = endpoint::get_next(current_endpoint); - // Endpoints should have destroyable flag set to true before destroying - ((_endpoint_t *)current_endpoint)->flags |= ENDPOINT_FLAG_DESTROYABLE; - err = endpoint::destroy((node_t *)current_node, current_endpoint); - VerifyOrDo(err == ESP_OK, ESP_LOGE(TAG, "Failed to destroy endpoint")); - - current_endpoint = next_endpoint; - } - - return destroy_raw(); -} - -// Treat 0xFFFF'FFFF as wildcard cluster -static inline bool is_wildcard_cluster_id(uint32_t cluster_id) -{ - return cluster_id == chip::kInvalidClusterId; -} - -// Treat 0xFFFF as wildcard endpoint -static inline bool is_wildcard_endpoint_id(uint16_t endpoint_id) -{ - return endpoint_id == chip::kInvalidEndpointId; -} - -/** - * @brief Get the number of clusters that match the given flags - * - * @param endpoint_id: The endpoint ID to check, 0xFFFF is treated as wildcard endpoint id - * @param cluster_id: The cluster ID to check, 0xFFFF is treated as wildcard cluster id - * @param cluster_flags: The flags to check - * @return The number of clusters that match the given flags - */ -static uint32_t get_cluster_count(uint32_t endpoint_id, uint32_t cluster_id, uint8_t cluster_flags) -{ - uint32_t count = 0; - node_t *node = get(); - VerifyOrReturnValue(node, count, ESP_LOGE(TAG, "Node cannot be NULL")); - - // lambda to check if cluster matches flags and return 1 if it does, 0 otherwise - auto check_cluster_flags = [cluster_flags](const endpoint_t *endpoint, const cluster_t *cluster) -> uint32_t { - if (cluster && endpoint) { - const _endpoint_t *_endpoint = (_endpoint_t *)endpoint; - const _cluster_t *_cluster = (_cluster_t *)cluster; - EmberAfClusterMask flags = _endpoint->endpoint_type->cluster[_cluster->index].mask; - return (flags & cluster_flags) ? 1 : 0; - } - return 0; - }; - - // lambda to count all matching clusters for an endpoint - auto get_count_on_all_clusters = [&check_cluster_flags](endpoint_t *endpoint) -> uint32_t { - uint32_t result = 0; - if (!endpoint) return result; - - cluster_t *cluster = cluster::get_first(endpoint); - while (cluster) { - result += check_cluster_flags(endpoint, cluster); - cluster = cluster::get_next(cluster); - } - return result; - }; - - // lambda to find and count a specific cluster - auto get_count_on_specific_cluster = [&check_cluster_flags](const endpoint_t *endpoint, uint32_t cluster_id) -> uint32_t { - if (!endpoint) return 0; - cluster_t *cluster = cluster::get((endpoint_t *)endpoint, cluster_id); - return check_cluster_flags(endpoint, cluster); - }; - - // Case 1: Wildcard endpoint - if (is_wildcard_endpoint_id(endpoint_id)) { - endpoint_t *endpoint = endpoint::get_first(node); - while (endpoint) { - // Case 1.1: Wildcard cluster - count all clusters with matching flags - if (is_wildcard_cluster_id(cluster_id)) { - count += get_count_on_all_clusters(endpoint); - } - // Case 1.2: Specific cluster - count if it exists and has matching flags - else { - count += get_count_on_specific_cluster(endpoint, cluster_id); - } - endpoint = endpoint::get_next(endpoint); - } - } - // Case 2: Specific endpoint - else { - endpoint_t *endpoint = endpoint::get(endpoint_id); - if (!endpoint) { - return count; - } - - // Case 2.1: Wildcard cluster - count all clusters with matching flags - if (is_wildcard_cluster_id(cluster_id)) { - count += get_count_on_all_clusters(endpoint); - } - // Case 2.2: Specific cluster - count if it exists and has matching flags - else { - count += get_count_on_specific_cluster(endpoint, cluster_id); - } - } - - return count; -} - -uint32_t get_server_cluster_endpoint_count(uint32_t cluster_id) -{ - return get_cluster_count(chip::kInvalidEndpointId, cluster_id, CLUSTER_FLAG_SERVER); -} - -uint32_t get_client_cluster_endpoint_count(uint32_t cluster_id) -{ - return get_cluster_count(chip::kInvalidEndpointId, cluster_id, CLUSTER_FLAG_CLIENT); -} - -} /* node */ } /* esp_matter */ diff --git a/components/esp_matter/esp_matter_core.h b/components/esp_matter/esp_matter_core.h index b22ca69fd..50399826f 100644 --- a/components/esp_matter/esp_matter_core.h +++ b/components/esp_matter/esp_matter_core.h @@ -30,21 +30,6 @@ using chip::TLV::TLVReader; namespace esp_matter { -/** Generic handle */ -typedef size_t handle_t; -/** Node handle */ -typedef handle_t node_t; -/** Endpoint handle */ -typedef handle_t endpoint_t; -/** Cluster handle */ -typedef handle_t cluster_t; -/** Attribute handle */ -typedef handle_t attribute_t; -/** Command handle */ -typedef handle_t command_t; -/** Event handle */ -typedef handle_t event_t; - /** Event callback * * @param[in] event event data pointer. @@ -72,6 +57,13 @@ bool is_started(); */ esp_err_t start(event_callback_t callback, intptr_t callback_arg = static_cast(NULL)); +/** Return whether the Matter is intialized and started + * + * @return true if Matter is started + * @return false if Matter is not started + */ +bool is_started(); + /** Factory reset * * Perform factory reset and erase the data stored in the non volatile storage. This also restarts the device. @@ -118,1009 +110,4 @@ esp_err_t chip_stack_unlock(); } /* lock */ -namespace node { - -/** Create raw node - * - * @return Node handle on success. - * @return NULL in case of failure. - */ -node_t *create_raw(); - -/** Destroy raw node - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t destroy_raw(); - -/** Get node - * - * @return Node handle on success. - * @return NULL in case of failure. - */ -node_t *get(); - -/** Destroy node - * - * This will destroy the node and all the endpoints, clusters, attributes, commands and events associated with it. - * - * @note: Call this function only if matter is not running. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t destroy(); - -/** Get the endpoint count for a server cluster - * - * Get the number of endpoints that have the given cluster ID as a server cluster. - * - * @param[in] cluster_id Cluster ID. - * - * @return Endpoint count on success. - * @return 0 in case of failure or if not found on any endpoint. - */ - -uint32_t get_server_cluster_endpoint_count(uint32_t cluster_id); - -/** Get the endpoint count for a client cluster - * - * Get the number of endpoints that have the given cluster ID as a client cluster. - * - * @param[in] cluster_id Cluster ID. - * - * @return Endpoint count on success. - * @return 0 in case of failure or if not found on any endpoint. - */ -uint32_t get_client_cluster_endpoint_count(uint32_t cluster_id); -} /* node */ - -namespace endpoint { - -/** Create endpoint - * - * This will create a new endpoint with a unique endpoint_id and add the endpoint to the node. - * - * @param[in] node Node handle. - * @param[in] flags Bitmap of `endpoint_flags_t`. - * @param[in] priv_data (Optional) Private data associated with the endpoint. This will be passed to the - * attribute_update and identify callbacks. It should stay allocated throughout the lifetime of the device. - * - * @return Endpoint handle on success. - * @return NULL in case of failure. - */ -endpoint_t *create(node_t *node, uint8_t flags, void *priv_data); - -/** Resume endpoint - * - * This will resume an endpoint after reboot and add it to the node. - * - * @param[in] node Node handle. - * @param[in] flags Bitmap of `endpoint_flags_t`. - * @param[in] endpoint_id Endpoint ID of the endpoint resumed. - * @param[in] priv_data (Optional) Private data associated with the endpoint. This will be passed to the - * attribute_update and identify callbacks. It should stay allocated throughout the lifetime of the device. - * - * @return Endpoint handle on success. - * @return NULL in case of failure. - */ -endpoint_t *resume(node_t *node, uint8_t flags, uint16_t endpoint_id, void *priv_data); - -/** Destroy endpoint - * - * This will destroy the endpoint which has been created and added to the node. It also destroys the associated - * clusters, attributes and commands. - * - * @param[in] node Node handle. - * @param[in] endpoint Endpoint handle. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t destroy(node_t *node, endpoint_t *endpoint); - -/** Get endpoint - * - * Get the endpoint present on the node. - * - * @param[in] node Node handle. - * @param[in] endpoint_id Endpoint ID of the endpoint. - * - * @return Endpoint handle on success. - * @return NULL in case of failure. - */ -endpoint_t *get(node_t *node, uint16_t endpoint_id); - -/** Get endpoint - * - * Get the endpoint present on the node. - * - * @param[in] endpoint_id Endpoint ID of the endpoint. - * - * @return Endpoint handle on success. - * @return NULL in case of failure. - */ -endpoint_t *get(uint16_t endpoint_id); - -/** Get first endpoint - * - * Get the first endpoint present on the node. - * - * @param[in] node Node handle. - * - * @return Endpoint handle on success. - * @return NULL in case of failure. - */ -endpoint_t *get_first(node_t *node); - -/** Get next endpoint - * - * Get the next endpoint present on the node. - * - * @param[in] endpoint Endpoint handle. - * - * @return Endpoint handle on success. - * @return NULL in case of failure. - */ -endpoint_t *get_next(endpoint_t *endpoint); - -/** Get endpoint count - * - * Get the endpoint count present on the node. - * - * @param[in] node Node handle. - * - * @return Endpoint count on success. - * @return 0 in case of failure. - */ -uint16_t get_count(node_t *node); - -/** Get endpoint ID - * - * Get the endpoint ID for the endpoint. - * - * @param[in] endpoint Endpoint handle. - * - * @return Endpoint ID on success. - * @return Invalid Endpoint ID (0xFFFF) in case of failure. - */ -uint16_t get_id(endpoint_t *endpoint); - -/** Add device type ID and verision - * - * Add the device type ID and version for the endpoint. - * - * @param[in] endpoint Endpoint handle. - * @param[in] device_type_id Device type ID. - * @param[in] device_type_version Device type version. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t add_device_type(endpoint_t *endpoint, uint32_t device_type_id, uint8_t device_type_version); - -/** Get device type ID array - * - * Get the device type ID array for the endpoint. This array is aligned with the device type version array. - * - * @param[in] endpoint Endpoint handle. - * @param[out] device_type_count_ptr the pointer of device type ID array length. - * - * @return device type ID array on success. - * @return NULL when the endpoint or the device_type_count_ptr is NULL. - */ -uint32_t *get_device_type_ids(endpoint_t *endpoint, uint8_t *device_type_count_ptr); - -/** Get device type version array - * - * Get the device type version array for the endpoint. This array is aligned with the device type ID array. - * - * @param[in] endpoint Endpoint handle. - * @param[out] device_type_count_ptr the pointer of device type version array length. - * - * @return device type version array on success. - * @return NULL when the endpoint or the device_type_count_ptr is NULL. - */ -uint8_t *get_device_type_versions(endpoint_t *endpoint, uint8_t *device_type_count_ptr); - -/** Set parent endpoint - * - * Set the parent endpoint. This is useful in correctly setting the parts_list attribute for the parent, when the - * parent is a composite endpoint. - * - * @param[in] endpoint Endpoint handle. - * @param[out] parent_endpoint Parent endpoint handle. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t set_parent_endpoint(endpoint_t *endpoint, endpoint_t *parent_endpoint); - -/** Get private data - * - * Get the private data passed while creating the endpoint. - * - * @param[in] endpoint_id Endpoint ID of the endpoint. - * - * @return Private data on success. - * @return NULL in case of failure. - */ -void *get_priv_data(uint16_t endpoint_id); - -/** Set private data - * - * Set the private data after creating the endpoint. - * - * @param[in] endpoint_id Endpoint ID of the endpoint. - * @param[in] priv_data Private data of the endpoint. - * - * @return ESP_OK on success. - * @return ESP_ERR_INVALID_STATE or ESP_ERR_NOT_FOUND in case of failure. - */ -esp_err_t set_priv_data(uint16_t endpoint_id, void *priv_data); - -/** Set identify - * - * Set identify to the endpoint. The identify pointer should be dynamically allocated using 'chip::Platform::New()', - * and once Matter stack is done using it, it will be freed by 'chip::Platform::Delete()'. - * - * @param[in] endpoint_id Endpoint id. - * @param[in] identify Identify pointer. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t set_identify(uint16_t endpoint_id, void *identify); - -/** Enable endpoint - * - * Enable the endpoint which has been previously created. - * - * @note: This API only needs to be called for endpoints created after calling esp_matter::start(). It should be - * called after all the clusters, attributes and commands have been added to the created endpoint. - * - * @param[in] endpoint Endpoint handle. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t enable(endpoint_t *endpoint); - -} /* endpoint */ - -namespace cluster { - -/** Cluster plugin server init callback - * - * This callback will be called when the endpoints are initialised. This should be set to upstream's - * `MatterPluginServerInitCallback` API, if it exists. - */ -typedef void (*plugin_server_init_callback_t)(); - -/** Cluster delegate server init callback - * - * This callback will be called when the endpoints are initialised. - */ -typedef void (*delegate_init_callback_t)(void *ptr, uint16_t endpoint_id); - -/** Cluster add bounds callback - * - * This callback will be called when the endpoints are initialised. - */ -typedef void (*add_bounds_callback_t)(cluster_t *cluster); - -/** Generic function - * - * This can be used to add additional functions based on `cluster_flags_t`. - */ -typedef void (*function_generic_t)(); - -/** Create cluster - * - * This will create a new cluster and add it to the endpoint. - * - * @param[in] endpoint Endpoint handle. - * @param[in] cluster_id Cluster ID for the cluster. - * @param[in] flags Bitmap of `cluster_flags_t`. - * - * @return Cluster handle on success. - * @return NULL in case of failure. - */ -cluster_t *create(endpoint_t *endpoint, uint32_t cluster_id, uint8_t flags); - -/** Destroy cluster - * - * This will destroy the cluster which has been created and added to the endpoint. It also destroys the associated - * attributes, commands and events. - * - * @param[in] cluster Cluster handle. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t destroy(cluster_t *cluster); - -/** Get cluster - * - * Get the cluster present on the endpoint. - * - * @param[in] endpoint Endpoint handle. - * @param[in] cluster_id Cluster ID for the cluster. - * - * @return Cluster handle on success. - * @return NULL in case of failure. - */ -cluster_t *get(endpoint_t *endpoint, uint32_t cluster_id); - -/** Get cluster - * - * Get the cluster present on the endpoint. - * - * @param[in] endpoint_id Endpoint id. - * @param[in] cluster_id Cluster ID for the cluster. - * - * @return Cluster handle on success. - * @return NULL in case of failure. - */ -cluster_t *get(uint16_t endpoint_id, uint32_t cluster_id); - -/** Get first cluster - * - * Get the first cluster present on the endpoint. - * - * @param[in] endpoint Endpoint handle. - * - * @return Cluster handle on success. - * @return NULL in case of failure. - */ -cluster_t *get_first(endpoint_t *endpoint); - -/** Get next cluster - * - * Get the next cluster present on the endpoint. - * - * @param[in] cluster Cluster handle. - * - * @return Cluster handle on success. - * @return NULL in case of failure. - */ -cluster_t *get_next(cluster_t *cluster); - -/** Get cluster ID - * - * Get the cluster ID for the cluster. - * - * @param[in] cluster Cluster handle. - * - * @return Cluster ID on success. - * @return Invalid CLuster ID (0xFFFF'FFFF) in case of failure. - */ -uint32_t get_id(cluster_t *cluster); - -/** Get delegate pointer - * - * Get the delegate pointer for the cluster. - * - * @param[in] cluster Cluster handle. - * - * @return pointer of delegate class on success. - * @return nullptr in case of failure. - */ -void *get_delegate_impl(cluster_t *cluster); - -/** Set cluster plugin server init callback - * - * Set the cluster plugin server init callback. This callback will be called when the endpoints are initialised. The - * callback should be set to upstream's `MatterPluginServerInitCallback` API for the cluster, if it - * exists. - * - * @param[in] cluster Cluster handle. - * @param[in] callback Plugin server init callback. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t set_plugin_server_init_callback(cluster_t *cluster, plugin_server_init_callback_t callback); - -/** Set server cluster delegate init callback - * - * @param[in] cluster Cluster handle. - * @param[in] callback Delegate server init callback. - * @param[in] delegate Pointer to delegate impl.. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t set_delegate_and_init_callback(cluster_t *cluster, delegate_init_callback_t callback, void *delegate); - -/** Set server cluster add bounds callback - * - * @param[in] cluster Cluster handle. - * @param[in] callback Add bounds callback. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t set_add_bounds_callback(cluster_t *cluster, add_bounds_callback_t callback); - -/** Get cluster plugin server init callback - * - * Get the cluster plugin server init callback which has previously been set. - * - * @param[in] cluster Cluster handle. - * - * @return Plugin server init callback. - * @return NULL in case of failure or if it has not been set. - */ -plugin_server_init_callback_t get_plugin_server_init_callback(cluster_t *cluster); - -/** Get server cluster delegate init callback - * - * @param[in] cluster Cluster handle. - * - * @return Delegate init callback. - * @return NULL in case of failure or if it has not been set. - */ -delegate_init_callback_t get_delegate_init_callback(cluster_t *cluster); - -/** Get server cluster add bounds callback - * - * @param[in] cluster Cluster handle. - * - * @return add bounds callback. - * @return NULL in case of failure or if it has not been set. - */ -add_bounds_callback_t get_add_bounds_callback(cluster_t *cluster); - -/** Add cluster function list - * - * This API can be used to add additional cluster functions based on `cluster_flags_t`. This should be set - * to upstream's `MatterServerCallback` or - * `emberAfServerCallback` API, if it exists. The corresponding function_flags must be be - * set. - * - * @param[in] cluster Cluster handle. - * @param[in] function_list Array of function_generic_t. - * @param[in] function_flags Bitmap of cluster flags corresponding to the function_list. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t add_function_list(cluster_t *cluster, const function_generic_t *function_list, int function_flags); - -} /* cluster */ - -namespace attribute { - -/** Create attribute - * - * This will create a new attribute and add it to the cluster. - * - * @param[in] cluster Cluster handle. - * @param[in] attribute_id Attribute ID for the attribute. - * @param[in] flags Bitmap of `attribute_flags_t`. - * @param[in] val Default type and value of the attribute. Use appropriate elements as per the value type. - * @param[in] max_val_size For attributes of type char string and long char string, the size should correspond to the - * maximum size defined in the specification. However, for other types of attributes, this - * parameter remains unused, and therefore the default value is set to 0 - * - * @return Attribute handle on success. - * @return NULL in case of failure. - */ -attribute_t *create(cluster_t *cluster, uint32_t attribute_id, uint16_t flags, esp_matter_attr_val_t val, - uint16_t max_val_size = 0); - -/** Get attribute - * - * Get the attribute present on the cluster. - * - * @param[in] cluster Cluster handle. - * @param[in] attribute_id Attribute ID for the attribute. - * - * @return Attribute handle on success. - * @return NULL in case of failure. - */ -attribute_t *get(cluster_t *cluster, uint32_t attribute_id); - -/** Get attribute - * - * Get the attribute present on the cluster. - * - * @param[in] endpoint_id Endpoint id.. - * @param[in] cluster_id Cluster ID for the Cluster. - * @param[in] attribute_id Attribute ID for the attribute. - * - * @return Attribute handle on success. - * @return NULL in case of failure. - */ -attribute_t *get(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id); - - -/** Get first attribute - * - * Get the first attribute present on the cluster. - * - * @param[in] cluster Cluster handle. - * - * @return Attribute handle on success. - * @return NULL in case of failure. - */ -attribute_t *get_first(cluster_t *cluster); - -/** Get next attribute - * - * Get the next attribute present on the cluster. - * - * @param[in] attribute Attribute handle. - * - * @return Attribute handle on success. - * @return NULL in case of failure. - */ -attribute_t *get_next(attribute_t *attribute); - -/** Get attribute ID - * - * Get the attribute ID for the attribute. - * - * @param[in] attribute Attribute handle. - * - * @return Attribute ID on success. - * @return Invalid Attribute ID (0xFFFF'FFFF) in case of failure. - */ -uint32_t get_id(attribute_t *attribute); - -/** Set attribute val - * - * Set/Update the value of the attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag) in the database. - * - * @note: Once `esp_matter::start()` is done, `attribute::update()` should be used to update the attribute value. - * - * @param[in] attribute Attribute handle. - * @param[in] val Pointer to `esp_matter_attr_val_t`. Use appropriate elements as per the value type. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t set_val(attribute_t *attribute, esp_matter_attr_val_t *val); - -/** Get attribute val - * - * Get the value of the attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag) from the database. - * - * @param[in] attribute Attribute handle. - * @param[out] val Pointer to `esp_matter_attr_val_t`. Use appropriate elements as per the value type. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t get_val(attribute_t *attribute, esp_matter_attr_val_t *val); - -/** Get attribute val raw - * - * Get the value of the attribute in the database, without the attribute handle. - * - * @param[in] endpoint_id Endpoint ID of the attribute. - * @param[in] cluster_id Cluster ID of the attribute. - * @param[in] attribute_id Attribute ID of the attribute. - * @param[out] value Pointer to an allocated buffer for the attribute value. - * @param[in] attribute_size Size of the allocated buffer. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t get_val_raw(uint16_t endpoint_id, uint32_t cluster_id, uint32_t attribute_id, uint8_t *value, - uint16_t attribute_size); - -/** Add attribute bounds - * - * Add bounds to the attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag). Bounds cannot be added to string/array type attributes. - * - * @param[in] attribute Attribute handle. - * @param[in] min Minimum allowed value. - * @param[in] max Maximum allowed value. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t add_bounds(attribute_t *attribute, esp_matter_attr_val_t min, esp_matter_attr_val_t max); - -/** Get attribute bounds - * - * Get the bounds which have been added to the attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag). - * - * @param[in] attribute Attribute handle. - * @param[in] bounds Pointer to `esp_matter_attr_bounds_t`. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t get_bounds(attribute_t *attribute, esp_matter_attr_bounds_t *bounds); - -/** Get attribute flags - * - * Get the attribute flags for the attribute. - * - * @param[in] attribute Attribute handle. - * - * @return Attribute flags. - */ -uint16_t get_flags(attribute_t *attribute); - -/** Set attribute override - * - * Set the override callback for the attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag). For attribute read and write calls, instead of doing that from the - * common database, this callback will be called. - * - * This can be used if the application or some component wants to maintain the attribute's value in the application or - * in that component respectively. It can also be used if the attribute value needs to be dynamically fetched and is - * difficult to maintain in the database. - * - * @param[in] attribute Attribute handle. - * @param[in] callback Override callback. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t set_override_callback(attribute_t *attribute, callback_t callback); - -/** Get attribute override - * - * Get the override callback for the attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag). - * - * @param[in] attribute Attribute handle. - * - * @return Attribute override callback. - */ -callback_t get_override_callback(attribute_t *attribute); - -/** Set attribute (has `ATTRIBUTE_FLAG_EXTERNAL_STORAGE` flag) deferred persistence - * - * Only non-volatile attributes can be set with deferred presistence. If an attribute is configured with deferred - * presistence, any modifications to it will be enacted in its persistent storage with a specific delay - * (CONFIG_ESP_MATTER_DEFERRED_ATTR_PERSISTENCE_TIME_MS) - * - * It could be used for the non-volatile attribues which might be changed rapidly, such as CurrentLevel in LevelControl - * cluster. - * - * @param[in] attribute Attribute handle. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t set_deferred_persistence(attribute_t *attribute); - -} /* attribute */ - -namespace command { - -/** Command callback - * - * Command callback which is called when the command is invoked. - * - * @note: If the `COMMAND_FLAG_CUSTOM` is set, the default command response is sent internally based on the - * return value from the callback. - * - * @param[in] command_path Common structure for endpoint, cluster and commands IDs. - * @param[in] tlv_data Command data in TLV format. - * @param[in] opaque_ptr This is a pointer which is used internally. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -typedef esp_err_t (*callback_t)(const ConcreteCommandPath &command_path, TLVReader &tlv_data, void *opaque_ptr); - -/** Create command - * - * This will create a new command and add it to the cluster. - * - * @note: For commands which are not defined in the spec the `COMMAND_FLAG_CUSTOM` flag must be set. This - * will send the command response internally, after the command callback is called. - * - * @param[in] cluster Cluster handle. - * @param[in] command_id Command ID for the command. - * @param[in] flags Bitmap of `command_flags_t`. - * @param[in] callback Command callback - * - * @return Command handle on success. - * @return NULL in case of failure. - */ -command_t *create(cluster_t *cluster, uint32_t command_id, uint8_t flags, callback_t callback); - -/** Get command - * - * Get the command present on the cluster. - * - * @param[in] cluster Cluster handle. - * @param[in] command_id Command ID for the command. - * @param[in] flags Command flags for the command to be fetched. - * - * @return Command handle on success. - * @return NULL in case of failure. - */ -command_t *get(cluster_t *cluster, uint32_t command_id, uint16_t flags); - -/** Get first command - * - * Get the first command present on the cluster. - * - * @param[in] cluster Cluster handle. - * - * @return Command handle on success. - * @return NULL in case of failure. - */ -command_t *get_first(cluster_t *cluster); - -/** Get next command - * - * Get the next command present on the cluster. - * - * @param[in] command Command handle. - * - * @return Command handle on success. - * @return NULL in case of failure. - */ -command_t *get_next(command_t *command); - -/** Get command ID - * - * Get the command ID for the command. - * - * @param[in] command Command handle. - * - * @return Command ID on success. - * @return Invalid Command ID (0xFFFF'FFFF) in case of failure. - */ -uint32_t get_id(command_t *command); - -/** Get command callback - * - * Get the command callback for the command. - * - * @param[in] command Command handle. - * - * @return Command callback on success. - * @return NULL in case of failure or if the callback was not set when creating the command. - */ -callback_t get_callback(command_t *command); - -/** Get command user_callback - * - * Get the command user_callback for the command. - * - * @param[in] command Command handle. - * - * @return Command user_callback on success. - * @return NULL in case of failure or if the callback was not set when creating the command. - */ -callback_t get_user_callback(command_t *command); - -/** Set command user_callback - * - * Set the user_callback for the command. - * - * @param[in] command Command handle. - * @param[in] user_callback callback_t. - * - * @return void - */ -void set_user_callback(command_t *command, callback_t user_callback); - -/** Get command flags - * - * Get the command flags for the command. - * - * @param[in] command Command handle. - * - * @return Command flags. - */ -uint16_t get_flags(command_t *command); - -} /* command */ - -namespace event { - -/** Create event - * - * This will create a new event and add it to the cluster. - * - * @param[in] cluster Cluster handle. - * @param[in] event_id Event ID for the event. - * - * @return Event handle on success. - * @return NULL in case of failure. - */ -event_t *create(cluster_t *cluster, uint32_t event_id); - -/** Get event - * - * Get the event present on the cluster. - * - * @param[in] cluster Cluster handle. - * @param[in] event_id Event ID for the command. - * - * @return Event handle on success. - * @return NULL in case of failure. - */ -event_t *get(cluster_t *cluster, uint32_t event_id); - -/** Get first event - * - * Get the first event present on the cluster. - * - * @param[in] cluster Cluster handle. - * - * @return Event handle on success. - * @return NULL in case of failure. - */ -event_t *get_first(cluster_t *cluster); - -/** Get next event - * - * Get the next event present on the cluster. - * - * @param[in] event Event handle. - * - * @return Event handle on success. - * @return NULL in case of failure. - */ -event_t *get_next(event_t *event); - -/** Get event ID - * - * Get the event ID for the event. - * - * @param[in] event Event handle. - * - * @return Event ID on success. - * @return Invalid Event ID (0xFFFF'FFFF) in case of failure. - */ -uint32_t get_id(event_t *event); - -} /* event */ - -/* Client APIs */ -namespace client { - -/** Client request types - */ -typedef enum { - INVOKE_CMD = 0, - READ_ATTR = 1, - READ_EVENT = 2, - WRITE_ATTR = 3, - SUBSCRIBE_ATTR = 4, - SUBSCRIBE_EVENT = 5, -} request_type_t; - -/** Request handle as the input when calling `connect()` or `cluster_update()` - * - */ - -typedef struct request_handle { - request_type_t type; - union { - chip::app::AttributePathParams attribute_path; - chip::app::EventPathParams event_path; - chip::app::CommandPathParams command_path; - }; - /* This could be the command data field when the request type is INVOKE_CMD, - * or the attribute value data when the request type is WRITE_ATTR. - */ - void *request_data; - request_handle() : type(INVOKE_CMD), request_data(NULL) {} - request_handle(struct request_handle* req) : type(req->type), request_data(req->request_data) - { - if (req->type == INVOKE_CMD) { - command_path = req->command_path; - } else if (req->type == WRITE_ATTR || req->type == READ_ATTR || req->type == SUBSCRIBE_ATTR) { - attribute_path = req->attribute_path; - } else if (req->type == READ_EVENT || req->type == SUBSCRIBE_EVENT) { - event_path = req->event_path; - } - } -} request_handle_t; - -/** Peer device handle */ -typedef chip::DeviceProxy peer_device_t; - -/** CASE Session Manager */ -typedef chip::CASESessionManager case_session_mgr_t; - -/** Request send callback - * - * This callback will be called when `connect()` or `cluster_update()` is called and the connection completes. The - * send_request APIs can then be called from the callback. - * - * @param[in] peer_device Peer device handle. This can be passed to the send_command APIs. - * @param[in] req_handle Request handle used by `connect()` or `cluster_update()`. - * @param[in] priv_data (Optional) Private data associated with the callback. This will be passed to callback. It - * should stay allocated throughout the lifetime of the device. - */ -typedef void (*request_callback_t)(peer_device_t *peer_device, request_handle_t *req_handle, void *priv_data); - -/** Group request send callback - * - * This callback will be called when `cluster_update()` is called and the group request is triggered for binding cluster. - * - * @note: The request type should be INVOKE_CMD and the command should not expect a response. - * - * @param[in] fabric_index The index of the fabric that the group command is sent to. - * @param[in] req_handle Request handle used by `cluster_update()`. - * @param[in] priv_data (Optional) Private data associated with the callback. This will be passed to callback. It - * should stay allocated throughout the lifetime of the device. - */ -typedef void (*group_request_callback_t)(uint8_t fabric_index, request_handle_t *req_handle, void *priv_data); - -/** Initialize binding - * - * This should be called if the Binding cluster has been created. It just sets a flag for the binding manager to be - * initialized. - * If the cluster::binding::create() is being used, this is called internally. - */ -void binding_init(); - -/** Initialize binding manager - * - * This initializes the binding manager. It is called after the matter thread has been started. - */ -void binding_manager_init(); - -/** Connect - * - * Connect to another device on the same fabric to send a request. - * - * @param[in] case_session_mgr CASE Session Manager to find or establish the session - * @param[in] fabric_index Fabric index. - * @param[in] node_id Node ID of the other device. - * @param[in] req_handle Request to be sent to the remote device. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t connect(case_session_mgr_t *case_session_mgr, uint8_t fabric_index, uint64_t node_id, - request_handle_t *req_handle); - -/** group_request_send - * - * on the same fabric to send a group request. - * - * @param[in] fabric_index Fabric index. - * @param[in] req_handle Request to be sent to the group. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t group_request_send(uint8_t fabric_index, request_handle_t *req_handle); - -/** Set request send callback - * - * Set the common request send callback and the group request send callback. The common callback will be called - * when `connect()` or `cluster_update()` is called and the connection completes. The group callback will be called - * when `cluster_update()` is called and the group request is triggered. - * - * @param[in] callback request send callback. - * @param[in] g_callback group request send callback - * @param[in] priv_data (Optional) Private data associated with the callback. This will be passed to callback. It - * should stay allocated throughout the lifetime of the device. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t set_request_callback(request_callback_t callback, group_request_callback_t g_callback, void *priv_data); - -/** Cluster update - * - * For an already binded device, this API can be used to get the request send callback, and the send_request APIs can - * then be called from the callback. - * - * @param[in] local_endpoint_id The ID of the local endpoint with a binding cluster. - * @param[in] req_handle Request information to notify the bound cluster changed. - * - * @return ESP_OK on success. - * @return error in case of failure. - */ -esp_err_t cluster_update(uint16_t local_endpoint_id, request_handle_t *req_handle); - -} /* client */ } /* esp_matter */ diff --git a/components/esp_matter/esp_matter_icd_configuration.cpp b/components/esp_matter/esp_matter_icd_configuration.cpp index 7001a3b05..df1ef0bdf 100644 --- a/components/esp_matter/esp_matter_icd_configuration.cpp +++ b/components/esp_matter/esp_matter_icd_configuration.cpp @@ -16,6 +16,9 @@ #include #include #include +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL +#include +#endif #include #include @@ -107,21 +110,25 @@ static esp_err_t set_active_threshold(uint32_t active_threshold_ms) return chip::Test::ICDConfigurationDataTestAccess::SetActiveThreshold(Milliseconds32(active_threshold_ms)); } +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL static bool s_enable_icd_server = true; bool get_icd_server_enabled() { return s_enable_icd_server; } +#endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL esp_err_t set_configuration_data(config_t *config) { ESP_RETURN_ON_FALSE(config, ESP_ERR_INVALID_ARG, TAG, "config cannot be NULL"); +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL if (!config->enable_icd_server) { - ESP_RETURN_ON_FALSE(!node::get(), ESP_ERR_INVALID_STATE, TAG, + ESP_RETURN_ON_FALSE(!esp_matter::node::get(), ESP_ERR_INVALID_STATE, TAG, "Could not disable ICD server after data model is created"); } s_enable_icd_server = config->enable_icd_server; +#endif // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL ESP_RETURN_ON_FALSE(!is_started(), ESP_ERR_INVALID_STATE, TAG, "Could not change ICD configuration data after Matter is started"); ESP_RETURN_ON_ERROR(set_polling_intervals(config->fast_interval_ms, config->slow_interval_ms), TAG, diff --git a/components/esp_matter/esp_matter_icd_configuration.h b/components/esp_matter/esp_matter_icd_configuration.h index 60a131484..a47191fda 100644 --- a/components/esp_matter/esp_matter_icd_configuration.h +++ b/components/esp_matter/esp_matter_icd_configuration.h @@ -19,7 +19,9 @@ namespace esp_matter { namespace icd { typedef struct config { +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL bool enable_icd_server; +#endif std::optional fast_interval_ms; std::optional slow_interval_ms; std::optional active_mode_duration_ms; @@ -27,9 +29,11 @@ typedef struct config { std::optional active_threshold_ms; } config_t; +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL /** Get whether ICD server is enabled for Matter end-device */ bool get_icd_server_enabled(); +#endif /** Set ICD configuration data * diff --git a/components/esp_matter/esp_matter_identify.cpp b/components/esp_matter/esp_matter_identify.cpp index 69fee90a0..e22f055f4 100644 --- a/components/esp_matter/esp_matter_identify.cpp +++ b/components/esp_matter/esp_matter_identify.cpp @@ -18,12 +18,23 @@ #include +#ifndef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL +#include +#include +#if defined(MATTER_DM_IDENTIFY_CLUSTER_SERVER_ENDPOINT_COUNT) && MATTER_DM_IDENTIFY_CLUSTER_SERVER_ENDPOINT_COUNT > 0 +#define USE_IDENTIFY_ARRAY +#endif +#endif // !CONFIG_ESP_MATTER_ENABLE_DATA_MODEL + static const char *TAG = "esp_matter_identify"; namespace esp_matter { namespace identification { static callback_t identification_callback = NULL; +#ifdef USE_IDENTIFY_ARRAY +static Identify *g_identifies[MATTER_DM_IDENTIFY_CLUSTER_SERVER_ENDPOINT_COUNT]; +#endif esp_err_t set_callback(callback_t callback) { @@ -34,8 +45,18 @@ esp_err_t set_callback(callback_t callback) static esp_err_t execute_callback(callback_type_t type, uint16_t endpoint_id, uint8_t effect_id, uint8_t effect_variant) { if (identification_callback) { +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL void *priv_data = endpoint::get_priv_data(endpoint_id); return identification_callback(type, endpoint_id, effect_id, effect_variant, priv_data); +#else // CONFIG_ESP_MATTER_ENABLE_DATA_MODEL + void *ctx = nullptr; +#ifdef USE_IDENTIFY_ARRAY + uint16_t index = emberAfGetClusterServerEndpointIndex(endpoint_id, chip::app::Clusters::Identify::Id, + MATTER_DM_IDENTIFY_CLUSTER_SERVER_ENDPOINT_COUNT); + ctx = index < MATTER_ARRAY_SIZE(g_identifies) ? g_identifies[index] : nullptr; +#endif // USE_IDENTIFY_ARRAY + return identification_callback(type, endpoint_id, effect_id, effect_variant, ctx); +#endif // !CONFIG_ESP_MATTER_ENABLE_DATA_MODEL } return ESP_OK; } @@ -43,30 +64,42 @@ static esp_err_t execute_callback(callback_type_t type, uint16_t endpoint_id, ui static void start_cb(Identify *identify) { ESP_LOGI(TAG, "Start callback"); - execute_callback(START, identify->mEndpoint, static_cast(identify->mCurrentEffectIdentifier), static_cast(identify->mEffectVariant)); + execute_callback(START, identify->mEndpoint, static_cast(identify->mCurrentEffectIdentifier), + static_cast(identify->mEffectVariant)); } static void stop_cb(Identify *identify) { ESP_LOGI(TAG, "Stop callback"); - execute_callback(STOP, identify->mEndpoint, static_cast(identify->mCurrentEffectIdentifier), static_cast(identify->mEffectVariant)); + execute_callback(STOP, identify->mEndpoint, static_cast(identify->mCurrentEffectIdentifier), + static_cast(identify->mEffectVariant)); } static void effect_cb(Identify *identify) { ESP_LOGI(TAG, "Effect callback"); - execute_callback(EFFECT, identify->mEndpoint, static_cast(identify->mCurrentEffectIdentifier), static_cast(identify->mEffectVariant)); + execute_callback(EFFECT, identify->mEndpoint, static_cast(identify->mCurrentEffectIdentifier), + static_cast(identify->mEffectVariant)); } esp_err_t init(uint16_t endpoint_id, uint8_t identify_type, uint8_t effect_identifier, uint8_t effect_variant) { - Identify *identify = chip::Platform::New(endpoint_id, start_cb, stop_cb, (chip::app::Clusters::Identify::IdentifyTypeEnum)identify_type, - effect_cb, static_cast(effect_identifier), - static_cast(effect_variant)); + Identify *identify = chip::Platform::New( + endpoint_id, start_cb, stop_cb, (chip::app::Clusters::Identify::IdentifyTypeEnum)identify_type, effect_cb, + static_cast(effect_identifier), + static_cast(effect_variant)); VerifyOrReturnError(identify, ESP_FAIL, ESP_LOGE(TAG, "Fail to create identify object")); +#ifdef CONFIG_ESP_MATTER_ENABLE_DATA_MODEL endpoint::set_identify(endpoint_id, (void *)identify); +#elif defined(USE_IDENTIFY_ARRAY) + uint16_t index = emberAfGetClusterServerEndpointIndex(endpoint_id, chip::app::Clusters::Identify::Id, + MATTER_DM_IDENTIFY_CLUSTER_SERVER_ENDPOINT_COUNT); + if (index < MATTER_ARRAY_SIZE(g_identifies)) { + g_identifies[index] = identify; + } +#endif return ESP_OK; } -} /* identification */ -} /* esp_matter */ +} // namespace identification +} // namespace esp_matter diff --git a/components/esp_matter/esp_matter_identify.h b/components/esp_matter/esp_matter_identify.h index 66b1d485f..1d4bc9a88 100644 --- a/components/esp_matter/esp_matter_identify.h +++ b/components/esp_matter/esp_matter_identify.h @@ -15,6 +15,7 @@ #pragma once #include +#include namespace esp_matter { namespace identification { diff --git a/components/esp_matter/esp_matter_ota.cpp b/components/esp_matter/esp_matter_ota.cpp index e6fc86e5c..e733a7a5e 100644 --- a/components/esp_matter/esp_matter_ota.cpp +++ b/components/esp_matter/esp_matter_ota.cpp @@ -40,8 +40,6 @@ using chip::Server; using chip::DeviceLayer::ExtendedOTARequestorDriver; using namespace esp_matter; -using namespace esp_matter::endpoint; -using namespace esp_matter::cluster; #if CONFIG_ENABLE_OTA_REQUESTOR DefaultOTARequestor gRequestorCore; diff --git a/components/esp_matter_bridge/CMakeLists.txt b/components/esp_matter_bridge/CMakeLists.txt index 17fe53c95..90edebb1a 100644 --- a/components/esp_matter_bridge/CMakeLists.txt +++ b/components/esp_matter_bridge/CMakeLists.txt @@ -1,3 +1,10 @@ -idf_component_register(SRC_DIRS "${CMAKE_CURRENT_LIST_DIR}" - INCLUDE_DIRS "${CMAKE_CURRENT_LIST_DIR}" +set(src_dirs_list ) +set(include_dirs_list ) + +if (CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) + list(APPEND src_dirs_list "${CMAKE_CURRENT_LIST_DIR}") + list(APPEND include_dirs_list "${CMAKE_CURRENT_LIST_DIR}") +endif() +idf_component_register(SRC_DIRS ${src_dirs_list} + INCLUDE_DIRS ${include_dirs_list} REQUIRES esp_matter) diff --git a/components/esp_matter_bridge/esp_matter_bridge.h b/components/esp_matter_bridge/esp_matter_bridge.h index a819876b6..9c2304fa4 100644 --- a/components/esp_matter_bridge/esp_matter_bridge.h +++ b/components/esp_matter_bridge/esp_matter_bridge.h @@ -16,7 +16,7 @@ #include #include -#include +#include #define MAX_BRIDGED_DEVICE_COUNT \ CONFIG_ESP_MATTER_MAX_DYNAMIC_ENDPOINT_COUNT - 1 - CONFIG_ESP_MATTER_AGGREGATOR_ENDPOINT_COUNT diff --git a/components/esp_matter_controller/CMakeLists.txt b/components/esp_matter_controller/CMakeLists.txt index 69f0e5c41..4b56f5e17 100644 --- a/components/esp_matter_controller/CMakeLists.txt +++ b/components/esp_matter_controller/CMakeLists.txt @@ -16,7 +16,8 @@ if (CONFIG_ESP_MATTER_CONTROLLER_ENABLE) list(APPEND include_dirs_list "${CMAKE_CURRENT_SOURCE_DIR}/core" "${CMAKE_CURRENT_SOURCE_DIR}/commands" "${MATTER_SDK_PATH}/zzz_generated/chip-tool" - "${MATTER_SDK_PATH}/examples/chip-tool/") + "${MATTER_SDK_PATH}/examples/chip-tool/" + "${CMAKE_CURRENT_SOURCE_DIR}/data_model_provider") if (CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER) list(APPEND exclude_srcs_list "${CMAKE_CURRENT_SOURCE_DIR}/core/esp_matter_controller_client.cpp" diff --git a/components/esp_matter_controller/commands/esp_matter_controller_cluster_command.cpp b/components/esp_matter_controller/commands/esp_matter_controller_cluster_command.cpp index e72556d30..fed548298 100644 --- a/components/esp_matter_controller/commands/esp_matter_controller_cluster_command.cpp +++ b/components/esp_matter_controller/commands/esp_matter_controller_cluster_command.cpp @@ -29,7 +29,6 @@ #include using namespace chip::app::Clusters; -using namespace esp_matter::cluster; using namespace esp_matter::client; static const char *TAG = "cluster_command"; diff --git a/components/esp_matter_controller/core/esp_matter_controller_client.cpp b/components/esp_matter_controller/core/esp_matter_controller_client.cpp index ce2c67ff9..e13579ede 100644 --- a/components/esp_matter_controller/core/esp_matter_controller_client.cpp +++ b/components/esp_matter_controller/core/esp_matter_controller_client.cpp @@ -27,7 +27,7 @@ #include #include #include -#include +#include #include #include #include @@ -70,7 +70,7 @@ esp_err_t matter_controller_client::init(NodeId node_id, FabricId fabric_id, uin factory_init_params.opCertStore = &m_operational_cert_store; factory_init_params.enableServerInteractions = m_operational_advertising; factory_init_params.sessionKeystore = &m_session_key_store; - factory_init_params.dataModelProvider = chip::app::CodegenDataModelProviderInstance(&m_default_storage); + factory_init_params.dataModelProvider = &data_model::provider::get_instance(); m_controller_node_id = node_id; m_controller_fabric_id = fabric_id; diff --git a/components/esp_matter_controller/data_model_provider/controller_data_model_provider.h b/components/esp_matter_controller/data_model_provider/controller_data_model_provider.h new file mode 100644 index 000000000..741d2867a --- /dev/null +++ b/components/esp_matter_controller/data_model_provider/controller_data_model_provider.h @@ -0,0 +1,130 @@ +// 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. + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using chip::ClusterId; +using chip::CommandId; +using chip::EndpointId; +using chip::ReadOnlyBufferBuilder; +using chip::app::AttributePathParams; +using chip::app::AttributeValueDecoder; +using chip::app::AttributeValueEncoder; +using chip::app::CommandHandler; +using chip::app::ConcreteAttributePath; +using chip::app::ConcreteClusterPath; +using chip::app::ConcreteCommandPath; +using chip::app::DataModel::AcceptedCommandEntry; +using chip::app::DataModel::ActionReturnStatus; +using chip::app::DataModel::AttributeEntry; +using chip::app::DataModel::ClusterInfo; +using chip::app::DataModel::DeviceTypeEntry; +using chip::app::DataModel::EndpointEntry; +using chip::app::DataModel::InvokeRequest; +using chip::app::DataModel::ListWriteOperation; +using chip::app::DataModel::ReadAttributeRequest; +using chip::app::DataModel::ServerClusterEntry; +using chip::app::DataModel::WriteAttributeRequest; +using chip::TLV::TLVReader; + +namespace esp_matter { +namespace controller { +namespace data_model { + +// TODO: The client-only controller has no data model, use an empty data model provider for it. +// We should finish the functions after enabling dynamic server for the controller. +class provider : public chip::app::DataModel::Provider { +public: + static provider &get_instance() + { + static provider instance; + return instance; + } + + CHIP_ERROR Shutdown() override { return CHIP_NO_ERROR; } + + ActionReturnStatus ReadAttribute(const ReadAttributeRequest &request, AttributeValueEncoder &encoder) override + { + return CHIP_NO_ERROR; + } + + ActionReturnStatus WriteAttribute(const WriteAttributeRequest &request, AttributeValueDecoder &decoder) override + { + return CHIP_NO_ERROR; + } + + void ListAttributeWriteNotification(const ConcreteAttributePath &aPath, ListWriteOperation opType) override {} + + std::optional InvokeCommand(const InvokeRequest &request, TLVReader &input_arguments, + CommandHandler *handler) override + { + return std::nullopt; + } + + // ProviderMetadataTree overrides + CHIP_ERROR Endpoints(ReadOnlyBufferBuilder &builder) override { return CHIP_NO_ERROR; } + CHIP_ERROR SemanticTags(EndpointId endpointId, ReadOnlyBufferBuilder &builder) override + { + return CHIP_NO_ERROR; + } + CHIP_ERROR DeviceTypes(EndpointId endpointId, ReadOnlyBufferBuilder &builder) override + { + return CHIP_NO_ERROR; + } + CHIP_ERROR ClientClusters(EndpointId endpointId, ReadOnlyBufferBuilder &builder) override + { + return CHIP_NO_ERROR; + } + CHIP_ERROR ServerClusters(EndpointId endpointId, ReadOnlyBufferBuilder &builder) override + { + return CHIP_NO_ERROR; + } + + CHIP_ERROR Attributes(const ConcreteClusterPath &path, ReadOnlyBufferBuilder &builder) override + { + return CHIP_NO_ERROR; + } + CHIP_ERROR GeneratedCommands(const ConcreteClusterPath &path, ReadOnlyBufferBuilder &builder) override + { + return CHIP_NO_ERROR; + } + CHIP_ERROR AcceptedCommands(const ConcreteClusterPath &path, + ReadOnlyBufferBuilder &builder) override + { + return CHIP_NO_ERROR; + } + + void Temporary_ReportAttributeChanged(const AttributePathParams &path) override {} + +private: + provider() = default; + ~provider() = default; +}; + +} // namespace data_model +} // namespace controller +} // namespace esp_matter diff --git a/docs/Doxyfile b/docs/Doxyfile index a3f15e54b..032a0ffce 100644 --- a/docs/Doxyfile +++ b/docs/Doxyfile @@ -21,13 +21,14 @@ PROJECT_NAME = "Programming Guide" ## and used to include in API reference documentation INPUT = \ - $(PROJECT_PATH)/components/esp_matter/esp_matter_endpoint.h \ - $(PROJECT_PATH)/components/esp_matter/esp_matter_cluster.h \ - $(PROJECT_PATH)/components/esp_matter/esp_matter_attribute.h \ - $(PROJECT_PATH)/components/esp_matter/esp_matter_command.h \ - $(PROJECT_PATH)/components/esp_matter/esp_matter_core.h \ - $(PROJECT_PATH)/components/esp_matter/esp_matter_event.h \ - $(PROJECT_PATH)/components/esp_matter/esp_matter_client.h \ + $(PROJECT_PATH)/components/esp_matter/data_model/esp_matter_endpoint.h \ + $(PROJECT_PATH)/components/esp_matter/data_model/esp_matter_cluster.h \ + $(PROJECT_PATH)/components/esp_matter/data_model/esp_matter_attribute.h \ + $(PROJECT_PATH)/components/esp_matter/data_model/esp_matter_command.h \ + $(PROJECT_PATH)/components/esp_matter/data_model/esp_matter_event.h \ + $(PROJECT_PATH)/components/esp_matter/data_model/esp_matter_data_model.h \ + $(PROJECT_PATH)/components/esp_matter/esp_matter_core.h \ + $(PROJECT_PATH)/components/esp_matter/esp_matter_client.h \ ## Get warnings for functions that have no documentation for their parameters or return value ## diff --git a/docs/en/api-reference/esp_matter_data_model.rst b/docs/en/api-reference/esp_matter_data_model.rst new file mode 100644 index 000000000..cf3609552 --- /dev/null +++ b/docs/en/api-reference/esp_matter_data_model.rst @@ -0,0 +1,9 @@ +Data Model +========== + +This has the high level APIs for Data Model. + +API reference +------------- + +.. include-build-file:: inc/esp_matter_data_model.inc diff --git a/docs/en/api-reference/index.rst b/docs/en/api-reference/index.rst index d0f6d113d..50b30d141 100644 --- a/docs/en/api-reference/index.rst +++ b/docs/en/api-reference/index.rst @@ -4,6 +4,7 @@ .. toctree:: :maxdepth: 1 + esp_matter_data_model.rst esp_matter_endpoint.rst esp_matter_cluster.rst esp_matter_attribute.rst diff --git a/docs/en/developing.rst b/docs/en/developing.rst index 2f434eb36..ab17b61f1 100644 --- a/docs/en/developing.rst +++ b/docs/en/developing.rst @@ -648,7 +648,7 @@ for clarity on the terms like endpoints, clusters, etc. that are used in this se node_t *node = node::create(&node_config, app_attribute_update_cb, NULL); - We will use the ``color_temperature_light`` standard device type in this - case. All standard device types are available in :project_file:`esp_matter_endpoint.h ` header file. + case. All standard device types are available in :project_file:`esp_matter_endpoint.h ` header file. Each device type has a set of default configuration that can be specific as well. diff --git a/docs/en/faq.rst b/docs/en/faq.rst index fed1344ba..2a9f964dd 100644 --- a/docs/en/faq.rst +++ b/docs/en/faq.rst @@ -170,7 +170,7 @@ A1.8 Why does free RAM increase after first commissioning After the first commissioning, you may notice that the free RAM increases. This is because, by default, BLE is only used for the commissioning process. Once the commissioning is complete, BLE is deinitialized, and all the memory allocated to it is recovered. Here's the link to the -:project_file:`implementation which frees the BLE memory `. +:project_file:`implementation which frees the BLE memory `. However, if you want to continue using the BLE even after the commissioning process, you can disable the ``CONFIG_USE_BLE_ONLY_FOR_COMMISSIONING``. This will ensure that the memory allocated to the BLE functionality diff --git a/examples/common/app_bridge/CMakeLists.txt b/examples/common/app_bridge/CMakeLists.txt index 79a3af679..cdd51b872 100644 --- a/examples/common/app_bridge/CMakeLists.txt +++ b/examples/common/app_bridge/CMakeLists.txt @@ -1,3 +1,10 @@ -idf_component_register(SRCS "app_bridged_device.cpp" - INCLUDE_DIRS "${CMAKE_CURRENT_LIST_DIR}" +set(srcs_list ) +set(include_dirs_list ) +if (CONFIG_ESP_MATTER_ENABLE_DATA_MODEL) + list(APPEND srcs_list "app_bridged_device.cpp") + list(APPEND include_dirs_list "${CMAKE_CURRENT_LIST_DIR}") +endif() + +idf_component_register(SRCS ${srcs_list} + INCLUDE_DIRS ${include_dirs_list} REQUIRES esp_matter_bridge) diff --git a/examples/controller/CMakeLists.txt b/examples/controller/CMakeLists.txt index d83cf47cb..d78b9eb0d 100644 --- a/examples/controller/CMakeLists.txt +++ b/examples/controller/CMakeLists.txt @@ -6,31 +6,15 @@ if(NOT DEFINED ENV{ESP_MATTER_PATH}) message(FATAL_ERROR "Please set ESP_MATTER_PATH to the path of esp-matter repo") endif(NOT DEFINED ENV{ESP_MATTER_PATH}) -if(NOT DEFINED ENV{ESP_MATTER_DEVICE_PATH}) - if("${IDF_TARGET}" STREQUAL "esp32" OR "${IDF_TARGET}" STREQUAL "") - set(ENV{ESP_MATTER_DEVICE_PATH} $ENV{ESP_MATTER_PATH}/device_hal/device/esp32_devkit_c) - elseif("${IDF_TARGET}" STREQUAL "esp32c3") - set(ENV{ESP_MATTER_DEVICE_PATH} $ENV{ESP_MATTER_PATH}/device_hal/device/esp32c3_devkit_m) - elseif("${IDF_TARGET}" STREQUAL "esp32s3") - set(ENV{ESP_MATTER_DEVICE_PATH} $ENV{ESP_MATTER_PATH}/device_hal/device/esp32s3_devkit_c) - else() - message(FATAL_ERROR "Unsupported IDF_TARGET") - endif() -endif(NOT DEFINED ENV{ESP_MATTER_DEVICE_PATH}) - set(ESP_MATTER_PATH $ENV{ESP_MATTER_PATH}) set(MATTER_SDK_PATH ${ESP_MATTER_PATH}/connectedhomeip/connectedhomeip) # This should be done before using the IDF_TARGET variable. include($ENV{IDF_PATH}/tools/cmake/project.cmake) -include($ENV{ESP_MATTER_DEVICE_PATH}/esp_matter_device.cmake) set(EXTRA_COMPONENT_DIRS - "${ESP_MATTER_PATH}/examples/common" "${MATTER_SDK_PATH}/config/esp32/components" - "${ESP_MATTER_PATH}/components" - "${ESP_MATTER_PATH}/device_hal/device" - ${extra_components_dirs_append}) + "${ESP_MATTER_PATH}/components") project(controller) diff --git a/examples/controller/main/app_main.cpp b/examples/controller/main/app_main.cpp index d180ed46f..d59954353 100644 --- a/examples/controller/main/app_main.cpp +++ b/examples/controller/main/app_main.cpp @@ -23,7 +23,6 @@ #include #include #endif // CONFIG_OPENTHREAD_BORDER_ROUTER -#include #include #include @@ -32,10 +31,6 @@ static const char *TAG = "app_main"; uint16_t switch_endpoint_id = 0; -using namespace esp_matter; -using namespace esp_matter::attribute; -using namespace esp_matter::endpoint; - static void app_event_cb(const ChipDeviceEvent *event, intptr_t arg) { switch (event->Type) { diff --git a/examples/mfg_test_app/sdkconfig.defaults b/examples/mfg_test_app/sdkconfig.defaults index d8b921c44..d1bf46913 100644 --- a/examples/mfg_test_app/sdkconfig.defaults +++ b/examples/mfg_test_app/sdkconfig.defaults @@ -27,3 +27,6 @@ CONFIG_DEVICE_VENDOR_ID=0x131B # Disable STA and AP CONFIG_ENABLE_WIFI_STATION=n CONFIG_ENABLE_WIFI_AP=n + +# Disable Matter server as the test app doesn't start Matter server +CONFIG_ESP_MATTER_ENABLE_MATTER_SERVER=n diff --git a/examples/zap_light/main/app_main.cpp b/examples/zap_light/main/app_main.cpp index 39808313b..79c266197 100644 --- a/examples/zap_light/main/app_main.cpp +++ b/examples/zap_light/main/app_main.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include @@ -110,6 +111,9 @@ extern "C" void app_main() err = esp_matter::start(app_event_cb); ABORT_APP_ON_FAILURE(err == ESP_OK, ESP_LOGE(TAG, "Failed to start Matter, err:%d", err)); + esp_matter::identification::init(1, 0); + esp_matter::identification::set_callback(nullptr); + /* Starting driver with default values */ app_driver_light_set_defaults(light_endpoint_id);