Matter SDK Coverage Report
Current view: top level - app/util - attribute-storage.cpp (source / functions) Coverage Total Hit
Test: SHA:4d2388ac7eed75b2fe5e05e20de377999c632502 Lines: 44.0 % 582 256
Test Date: 2025-07-27 07:17:09 Functions: 50.7 % 75 38

            Line data    Source code
       1              : /**
       2              :  *
       3              :  *    Copyright (c) 2020-2023 Project CHIP Authors
       4              :  *
       5              :  *    Licensed under the Apache License, Version 2.0 (the "License");
       6              :  *    you may not use this file except in compliance with the License.
       7              :  *    You may obtain a copy of the License at
       8              :  *
       9              :  *        http://www.apache.org/licenses/LICENSE-2.0
      10              :  *
      11              :  *    Unless required by applicable law or agreed to in writing, software
      12              :  *    distributed under the License is distributed on an "AS IS" BASIS,
      13              :  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      14              :  *    See the License for the specific language governing permissions and
      15              :  *    limitations under the License.
      16              :  */
      17              : #include "lib/support/Span.h"
      18              : #include <app/util/attribute-storage.h>
      19              : 
      20              : #include <app/AttributeAccessInterfaceRegistry.h>
      21              : #include <app/CommandHandlerInterfaceRegistry.h>
      22              : #include <app/InteractionModelEngine.h>
      23              : #include <app/persistence/AttributePersistenceProvider.h>
      24              : #include <app/persistence/AttributePersistenceProviderInstance.h>
      25              : #include <app/persistence/PascalString.h>
      26              : #include <app/reporting/reporting.h>
      27              : #include <app/util/attribute-metadata.h>
      28              : #include <app/util/attribute-storage-detail.h>
      29              : #include <app/util/config.h>
      30              : #include <app/util/ember-io-storage.h>
      31              : #include <app/util/ember-strings.h>
      32              : #include <app/util/endpoint-config-api.h>
      33              : #include <app/util/generic-callbacks.h>
      34              : #include <lib/core/CHIPConfig.h>
      35              : #include <lib/core/CHIPError.h>
      36              : #include <lib/support/CodeUtils.h>
      37              : #include <lib/support/logging/CHIPLogging.h>
      38              : #include <platform/LockTracker.h>
      39              : #include <protocols/interaction_model/StatusCode.h>
      40              : 
      41              : using chip::Protocols::InteractionModel::Status;
      42              : 
      43              : // Attribute storage depends on knowing the current layout/setup of attributes
      44              : // and corresponding callbacks. Specifically:
      45              : //   - zap-generated/callback.h is needed because endpoint_config will call the
      46              : //     corresponding callbacks (via GENERATED_FUNCTION_ARRAYS) and the include
      47              : //     for it is:
      48              : //     util/config.h -> zap-generated/endpoint_config.h
      49              : #include <app-common/zap-generated/callback.h>
      50              : 
      51              : using namespace chip;
      52              : using namespace chip::app;
      53              : 
      54              : //------------------------------------------------------------------------------
      55              : // Globals
      56              : // This is not declared CONST in order to handle dynamic endpoint information
      57              : // retrieved from tokens.
      58              : EmberAfDefinedEndpoint emAfEndpoints[MAX_ENDPOINT_COUNT];
      59              : 
      60              : #if (ATTRIBUTE_MAX_SIZE == 0)
      61              : #define ACTUAL_ATTRIBUTE_SIZE 1
      62              : #else
      63              : #define ACTUAL_ATTRIBUTE_SIZE ATTRIBUTE_MAX_SIZE
      64              : #endif
      65              : 
      66              : uint8_t attributeData[ACTUAL_ATTRIBUTE_SIZE];
      67              : 
      68              : // ----- internal-only methods, not part of the external API -----
      69              : 
      70              : // Loads the attributes from built-in default and storage.
      71              : static void emAfLoadAttributeDefaults(EndpointId endpoint, Optional<ClusterId> = NullOptional);
      72              : 
      73              : static bool emAfMatchCluster(const EmberAfCluster * cluster, const EmberAfAttributeSearchRecord * attRecord);
      74              : static bool emAfMatchAttribute(const EmberAfCluster * cluster, const EmberAfAttributeMetadata * am,
      75              :                                const EmberAfAttributeSearchRecord * attRecord);
      76              : 
      77              : // If server == true, returns the number of server clusters,
      78              : // otherwise number of client clusters on the endpoint at the given index.
      79              : static uint8_t emberAfClusterCountByIndex(uint16_t endpointIndex, bool server);
      80              : 
      81              : // Check whether there is an endpoint defined with the given endpoint id that is
      82              : // enabled.
      83              : static bool emberAfEndpointIsEnabled(EndpointId endpoint);
      84              : 
      85              : namespace {
      86              : 
      87              : uint16_t emberEndpointCount = 0;
      88              : 
      89              : /// Determines a incremental unique index for ember
      90              : /// metadata that is increased whenever a structural change is made to the
      91              : /// ember metadata (e.g. changing dynamic endpoints or enabling/disabling endpoints)
      92              : unsigned emberMetadataStructureGeneration = 0;
      93              : 
      94              : // If we have attributes that are more than 4 bytes, then
      95              : // we need this data block for the defaults
      96              : #if (defined(GENERATED_DEFAULTS) && GENERATED_DEFAULTS_COUNT)
      97              : constexpr const uint8_t generatedDefaults[] = GENERATED_DEFAULTS;
      98              : #define ZAP_LONG_DEFAULTS_INDEX(index)                                                                                             \
      99              :     {                                                                                                                              \
     100              :         &generatedDefaults[index]                                                                                                  \
     101              :     }
     102              : #endif // GENERATED_DEFAULTS
     103              : 
     104              : #if (defined(GENERATED_MIN_MAX_DEFAULTS) && GENERATED_MIN_MAX_DEFAULT_COUNT)
     105              : constexpr const EmberAfAttributeMinMaxValue minMaxDefaults[] = GENERATED_MIN_MAX_DEFAULTS;
     106              : #define ZAP_MIN_MAX_DEFAULTS_INDEX(index)                                                                                          \
     107              :     {                                                                                                                              \
     108              :         &minMaxDefaults[index]                                                                                                     \
     109              :     }
     110              : #endif // GENERATED_MIN_MAX_DEFAULTS
     111              : 
     112              : #ifdef GENERATED_FUNCTION_ARRAYS
     113              : GENERATED_FUNCTION_ARRAYS
     114              : #endif
     115              : 
     116              : #ifdef GENERATED_COMMANDS
     117              : constexpr const CommandId generatedCommands[] = GENERATED_COMMANDS;
     118              : #define ZAP_GENERATED_COMMANDS_INDEX(index) (&generatedCommands[index])
     119              : #endif // GENERATED_COMMANDS
     120              : 
     121              : #if (defined(GENERATED_EVENTS) && (GENERATED_EVENT_COUNT > 0))
     122              : constexpr const EventId generatedEvents[] = GENERATED_EVENTS;
     123              : #define ZAP_GENERATED_EVENTS_INDEX(index) (&generatedEvents[index])
     124              : #endif // GENERATED_EVENTS
     125              : 
     126              : [[maybe_unused]] constexpr const EmberAfAttributeMetadata generatedAttributes[] = GENERATED_ATTRIBUTES;
     127              : #define ZAP_ATTRIBUTE_INDEX(index) (&generatedAttributes[index])
     128              : 
     129              : #ifdef GENERATED_CLUSTERS
     130              : constexpr const EmberAfCluster generatedClusters[] = GENERATED_CLUSTERS;
     131              : #define ZAP_CLUSTER_INDEX(index) (&generatedClusters[index])
     132              : #endif
     133              : 
     134              : #if FIXED_ENDPOINT_COUNT > 0
     135              : constexpr const EmberAfEndpointType generatedEmberAfEndpointTypes[] = GENERATED_ENDPOINT_TYPES;
     136              : constexpr const EmberAfDeviceType fixedDeviceTypeList[]             = FIXED_DEVICE_TYPES;
     137              : 
     138              : // Not const, because these need to mutate.
     139              : DataVersion fixedEndpointDataVersions[ZAP_FIXED_ENDPOINT_DATA_VERSION_COUNT];
     140              : #endif // FIXED_ENDPOINT_COUNT > 0
     141              : 
     142            0 : bool emberAfIsThisDataTypeAListType(EmberAfAttributeType dataType)
     143              : {
     144            0 :     return dataType == ZCL_ARRAY_ATTRIBUTE_TYPE;
     145              : }
     146              : 
     147        13919 : uint16_t findIndexFromEndpoint(EndpointId endpoint, bool ignoreDisabledEndpoints)
     148              : {
     149        13919 :     if (endpoint == kInvalidEndpointId)
     150              :     {
     151            0 :         return kEmberInvalidEndpointIndex;
     152              :     }
     153              : 
     154              :     uint16_t epi;
     155        28184 :     for (epi = 0; epi < emberAfEndpointCount(); epi++)
     156              :     {
     157        42009 :         if (emAfEndpoints[epi].endpoint == endpoint &&
     158        13878 :             (!ignoreDisabledEndpoints || emAfEndpoints[epi].bitmask.Has(EmberAfEndpointOptions::isEnabled)))
     159              :         {
     160        13866 :             return epi;
     161              :         }
     162              :     }
     163           53 :     return kEmberInvalidEndpointIndex;
     164              : }
     165              : 
     166              : // Returns the index of a given endpoint.  Considers disabled endpoints.
     167            0 : uint16_t emberAfIndexFromEndpointIncludingDisabledEndpoints(EndpointId endpoint)
     168              : {
     169            0 :     return findIndexFromEndpoint(endpoint, false /* ignoreDisabledEndpoints */);
     170              : }
     171              : 
     172            0 : CHIP_ERROR ValidateDataContent(ByteSpan span, const EmberAfAttributeMetadata * am)
     173              : {
     174            0 :     if (emberAfIsStringAttributeType(am->attributeType))
     175              :     {
     176            0 :         VerifyOrReturnValue(Storage::ShortPascalBytes::IsValid(span), CHIP_ERROR_INCORRECT_STATE);
     177            0 :         return CHIP_NO_ERROR;
     178              :     }
     179              : 
     180            0 :     if (emberAfIsLongStringAttributeType(am->attributeType))
     181              :     {
     182            0 :         VerifyOrReturnValue(Storage::LongPascalBytes::IsValid(span), CHIP_ERROR_INCORRECT_STATE);
     183            0 :         return CHIP_NO_ERROR;
     184              :     }
     185              : 
     186            0 :     VerifyOrReturnValue(span.size() == am->size, CHIP_ERROR_INCORRECT_STATE);
     187            0 :     return CHIP_NO_ERROR;
     188              : }
     189              : 
     190              : } // anonymous namespace
     191              : 
     192              : // Initial configuration
     193           25 : void emberAfEndpointConfigure()
     194              : {
     195              :     uint16_t ep;
     196              : 
     197              :     static_assert(FIXED_ENDPOINT_COUNT <= std::numeric_limits<decltype(ep)>::max(),
     198              :                   "FIXED_ENDPOINT_COUNT must not exceed the size of the endpoint data type");
     199              : 
     200           25 :     emberEndpointCount = FIXED_ENDPOINT_COUNT;
     201              : 
     202              : #if FIXED_ENDPOINT_COUNT > 0
     203              : 
     204           25 :     constexpr uint16_t fixedEndpoints[]             = FIXED_ENDPOINT_ARRAY;
     205           25 :     constexpr uint16_t fixedDeviceTypeListLengths[] = FIXED_DEVICE_TYPE_LENGTHS;
     206           25 :     constexpr uint16_t fixedDeviceTypeListOffsets[] = FIXED_DEVICE_TYPE_OFFSETS;
     207           25 :     constexpr uint8_t fixedEmberAfEndpointTypes[]   = FIXED_ENDPOINT_TYPES;
     208           25 :     constexpr EndpointId fixedParentEndpoints[]     = FIXED_PARENT_ENDPOINTS;
     209              : 
     210              : #if ZAP_FIXED_ENDPOINT_DATA_VERSION_COUNT > 0
     211              :     // Initialize our data version storage.  If
     212              :     // ZAP_FIXED_ENDPOINT_DATA_VERSION_COUNT == 0, gcc complains about a memset
     213              :     // with size equal to number of elements without multiplication by element
     214              :     // size, because the sizeof() is also 0 in that case...
     215              :     if (Crypto::DRBG_get_bytes(reinterpret_cast<uint8_t *>(fixedEndpointDataVersions), sizeof(fixedEndpointDataVersions)) !=
     216              :         CHIP_NO_ERROR)
     217              :     {
     218              :         // Now what?  At least 0-init it.
     219              :         memset(fixedEndpointDataVersions, 0, sizeof(fixedEndpointDataVersions));
     220              :     }
     221              : #endif // ZAP_FIXED_ENDPOINT_DATA_VERSION_COUNT > 0
     222              : 
     223           25 :     DataVersion * currentDataVersions = fixedEndpointDataVersions;
     224           50 :     for (ep = 0; ep < FIXED_ENDPOINT_COUNT; ep++)
     225              :     {
     226           25 :         emAfEndpoints[ep].endpoint = fixedEndpoints[ep];
     227           25 :         emAfEndpoints[ep].deviceTypeList =
     228           25 :             Span<const EmberAfDeviceType>(&fixedDeviceTypeList[fixedDeviceTypeListOffsets[ep]], fixedDeviceTypeListLengths[ep]);
     229           25 :         emAfEndpoints[ep].endpointType     = &generatedEmberAfEndpointTypes[fixedEmberAfEndpointTypes[ep]];
     230           25 :         emAfEndpoints[ep].dataVersions     = currentDataVersions;
     231           25 :         emAfEndpoints[ep].parentEndpointId = fixedParentEndpoints[ep];
     232              : 
     233           25 :         constexpr const DeviceTypeId kRootnodeId   = 0x0016;
     234           25 :         constexpr const DeviceTypeId kAggregatorId = 0x000E;
     235           25 :         constexpr const DeviceTypeId kBridgedNode  = 0x0013;
     236           25 :         emAfEndpoints[ep].bitmask.Set(EmberAfEndpointOptions::isEnabled);
     237           25 :         for (const auto & deviceType : emAfEndpoints[ep].deviceTypeList)
     238              :         {
     239              :             // Default composition for all device types is set to tree. Except rootnode, aggregator and
     240              :             // bridgednode, which are full-family. Clients can manually override these defaults using
     241              :             // SetFlatCompositionForEndpoint / SetTreeCompositionForEndpoint at application init.
     242              :             // TODO: This information should come from the schema XML, not be hardcoded.
     243           25 :             if ((deviceType.deviceTypeId == kRootnodeId) || (deviceType.deviceTypeId == kAggregatorId) ||
     244            0 :                 (deviceType.deviceTypeId == kBridgedNode))
     245              :             {
     246           25 :                 emAfEndpoints[ep].bitmask.Set(EmberAfEndpointOptions::isFlatComposition);
     247           25 :                 break;
     248              :             }
     249              :         }
     250              : 
     251              :         // Increment currentDataVersions by 1 (slot) for every server cluster
     252              :         // this endpoint has.
     253           25 :         currentDataVersions += emberAfClusterCountByIndex(ep, /* server = */ true);
     254              :     }
     255              : 
     256              : #endif // FIXED_ENDPOINT_COUNT > 0
     257              : 
     258              : #if CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT
     259              :     if (MAX_ENDPOINT_COUNT > FIXED_ENDPOINT_COUNT)
     260              :     {
     261              :         //
     262              :         // Reset instances tracking dynamic endpoints to safe defaults.
     263              :         //
     264          125 :         for (ep = FIXED_ENDPOINT_COUNT; ep < MAX_ENDPOINT_COUNT; ep++)
     265              :         {
     266          100 :             emAfEndpoints[ep] = EmberAfDefinedEndpoint();
     267              :         }
     268              :     }
     269              : #endif
     270           25 : }
     271              : 
     272           28 : void emberAfSetDynamicEndpointCount(uint16_t dynamicEndpointCount)
     273              : {
     274           28 :     emberEndpointCount = static_cast<uint16_t>(FIXED_ENDPOINT_COUNT + dynamicEndpointCount);
     275           28 : }
     276              : 
     277            0 : uint16_t emberAfGetDynamicIndexFromEndpoint(EndpointId id)
     278              : {
     279            0 :     if (id == kInvalidEndpointId)
     280              :     {
     281            0 :         return kEmberInvalidEndpointIndex;
     282              :     }
     283              : 
     284              :     uint16_t index;
     285            0 :     for (index = FIXED_ENDPOINT_COUNT; index < MAX_ENDPOINT_COUNT; index++)
     286              :     {
     287            0 :         if (emAfEndpoints[index].endpoint == id)
     288              :         {
     289            0 :             return static_cast<uint16_t>(index - FIXED_ENDPOINT_COUNT);
     290              :         }
     291              :     }
     292            0 :     return kEmberInvalidEndpointIndex;
     293              : }
     294              : 
     295           28 : CHIP_ERROR emberAfSetDynamicEndpoint(uint16_t index, EndpointId id, const EmberAfEndpointType * ep,
     296              :                                      const Span<DataVersion> & dataVersionStorage, Span<const EmberAfDeviceType> deviceTypeList,
     297              :                                      EndpointId parentEndpointId)
     298              : {
     299           28 :     return emberAfSetDynamicEndpointWithEpUniqueId(index, id, ep, dataVersionStorage, deviceTypeList, {}, parentEndpointId);
     300              : }
     301              : 
     302           28 : CHIP_ERROR emberAfSetDynamicEndpointWithEpUniqueId(uint16_t index, EndpointId id, const EmberAfEndpointType * ep,
     303              :                                                    const Span<DataVersion> & dataVersionStorage,
     304              :                                                    Span<const EmberAfDeviceType> deviceTypeList, CharSpan endpointUniqueId,
     305              :                                                    EndpointId parentEndpointId)
     306              : {
     307           28 :     auto realIndex = index + FIXED_ENDPOINT_COUNT;
     308              : 
     309           28 :     if (realIndex >= MAX_ENDPOINT_COUNT)
     310              :     {
     311            0 :         return CHIP_ERROR_NO_MEMORY;
     312              :     }
     313           28 :     if (id == kInvalidEndpointId)
     314              :     {
     315            0 :         return CHIP_ERROR_INVALID_ARGUMENT;
     316              :     }
     317              : 
     318           28 :     auto serverClusterCount = emberAfClusterCountForEndpointType(ep, /* server = */ true);
     319           28 :     if (dataVersionStorage.size() < serverClusterCount)
     320              :     {
     321            0 :         return CHIP_ERROR_NO_MEMORY;
     322              :     }
     323              : 
     324           28 :     index = static_cast<uint16_t>(realIndex);
     325          140 :     for (uint16_t i = FIXED_ENDPOINT_COUNT; i < MAX_ENDPOINT_COUNT; i++)
     326              :     {
     327          112 :         if (emAfEndpoints[i].endpoint == id)
     328              :         {
     329            0 :             return CHIP_ERROR_ENDPOINT_EXISTS;
     330              :         }
     331              :     }
     332              : 
     333           28 :     const size_t bufferSize = Compatibility::Internal::gEmberAttributeIOBufferSpan.size();
     334           62 :     for (uint8_t i = 0; i < ep->clusterCount; i++)
     335              :     {
     336           34 :         const EmberAfCluster * cluster = &(ep->cluster[i]);
     337           34 :         if (!cluster->attributes)
     338              :         {
     339            0 :             continue;
     340              :         }
     341              : 
     342          146 :         for (uint16_t j = 0; j < cluster->attributeCount; j++)
     343              :         {
     344          112 :             const EmberAfAttributeMetadata * attr = &(cluster->attributes[j]);
     345          112 :             uint16_t attrSize                     = emberAfAttributeSize(attr);
     346          112 :             if (attrSize > bufferSize)
     347              :             {
     348            0 :                 ChipLogError(DataManagement,
     349              :                              "Attribute size %u exceeds max size %lu, (attrId=" ChipLogFormatMEI ", clusterId=" ChipLogFormatMEI
     350              :                              ")",
     351              :                              attrSize, static_cast<unsigned long>(bufferSize), ChipLogValueMEI(attr->attributeId),
     352              :                              ChipLogValueMEI(cluster->clusterId));
     353            0 :                 return CHIP_ERROR_NO_MEMORY;
     354              :             }
     355              :         }
     356              :     }
     357           28 :     emAfEndpoints[index].endpoint       = id;
     358           28 :     emAfEndpoints[index].deviceTypeList = deviceTypeList;
     359           28 :     emAfEndpoints[index].endpointType   = ep;
     360           28 :     emAfEndpoints[index].dataVersions   = dataVersionStorage.data();
     361              : #if CHIP_CONFIG_USE_ENDPOINT_UNIQUE_ID
     362              :     MutableCharSpan targetSpan(emAfEndpoints[index].endpointUniqueId);
     363              :     if (CopyCharSpanToMutableCharSpan(endpointUniqueId, targetSpan) != CHIP_NO_ERROR)
     364              :     {
     365              :         return CHIP_ERROR_BUFFER_TOO_SMALL;
     366              :     }
     367              : 
     368              :     // Ensure that the size of emAfEndpoints[index].endpointUniqueId fits within uint8_t
     369              :     static_assert(sizeof(emAfEndpoints[0].endpointUniqueId) <= UINT8_MAX,
     370              :                   "The size of emAfEndpoints[index].endpointUniqueId must fit within uint8_t");
     371              : 
     372              :     emAfEndpoints[index].endpointUniqueIdSize = static_cast<uint8_t>(targetSpan.size());
     373              : #endif
     374              :     // Start the endpoint off as disabled.
     375           28 :     emAfEndpoints[index].bitmask.Clear(EmberAfEndpointOptions::isEnabled);
     376           28 :     emAfEndpoints[index].parentEndpointId = parentEndpointId;
     377              : 
     378           28 :     emberAfSetDynamicEndpointCount(MAX_ENDPOINT_COUNT - FIXED_ENDPOINT_COUNT);
     379              : 
     380              :     // Initialize the data versions.
     381           28 :     size_t dataSize = sizeof(DataVersion) * serverClusterCount;
     382           28 :     if (dataSize != 0)
     383              :     {
     384           28 :         if (Crypto::DRBG_get_bytes(reinterpret_cast<uint8_t *>(dataVersionStorage.data()), dataSize) != CHIP_NO_ERROR)
     385              :         {
     386              :             // Now what?  At least 0-init it.
     387            0 :             memset(dataVersionStorage.data(), 0, dataSize);
     388              :         }
     389              :     }
     390              : 
     391              :     // Now enable the endpoint.
     392           28 :     emberAfEndpointEnableDisable(id, true);
     393              : 
     394           28 :     emberMetadataStructureGeneration++;
     395           28 :     return CHIP_NO_ERROR;
     396              : }
     397              : 
     398           27 : EndpointId emberAfClearDynamicEndpoint(uint16_t index)
     399              : {
     400           27 :     EndpointId ep = 0;
     401              : 
     402           27 :     index = static_cast<uint16_t>(index + FIXED_ENDPOINT_COUNT);
     403              : 
     404           54 :     if ((index < MAX_ENDPOINT_COUNT) && (emAfEndpoints[index].endpoint != kInvalidEndpointId) &&
     405           27 :         (emberAfEndpointIndexIsEnabled(index)))
     406              :     {
     407           27 :         ep = emAfEndpoints[index].endpoint;
     408           27 :         emberAfEndpointEnableDisable(ep, false);
     409           27 :         emAfEndpoints[index].endpoint = kInvalidEndpointId;
     410              :     }
     411              : 
     412           27 :     emberMetadataStructureGeneration++;
     413           27 :     return ep;
     414              : }
     415              : 
     416        13853 : uint16_t emberAfFixedEndpointCount()
     417              : {
     418        13853 :     return FIXED_ENDPOINT_COUNT;
     419              : }
     420              : 
     421        62616 : uint16_t emberAfEndpointCount()
     422              : {
     423        62616 :     return emberEndpointCount;
     424              : }
     425              : 
     426        14216 : bool emberAfEndpointIndexIsEnabled(uint16_t index)
     427              : {
     428        14216 :     return (emAfEndpoints[index].bitmask.Has(EmberAfEndpointOptions::isEnabled));
     429              : }
     430              : 
     431              : // This function is used to call the per-cluster attribute changed callback
     432            0 : void emAfClusterAttributeChangedCallback(const ConcreteAttributePath & attributePath)
     433              : {
     434            0 :     const EmberAfCluster * cluster = emberAfFindServerCluster(attributePath.mEndpointId, attributePath.mClusterId);
     435            0 :     if (cluster != nullptr)
     436              :     {
     437            0 :         EmberAfGenericClusterFunction f = emberAfFindClusterFunction(cluster, MATTER_CLUSTER_FLAG_ATTRIBUTE_CHANGED_FUNCTION);
     438            0 :         if (f != nullptr)
     439              :         {
     440            0 :             ((EmberAfClusterAttributeChangedCallback) f)(attributePath);
     441              :         }
     442              :     }
     443            0 : }
     444              : 
     445              : // This function is used to call the per-cluster pre-attribute changed callback
     446            0 : Status emAfClusterPreAttributeChangedCallback(const ConcreteAttributePath & attributePath, EmberAfAttributeType attributeType,
     447              :                                               uint16_t size, uint8_t * value)
     448              : {
     449            0 :     const EmberAfCluster * cluster = emberAfFindServerCluster(attributePath.mEndpointId, attributePath.mClusterId);
     450            0 :     if (cluster == nullptr)
     451              :     {
     452            0 :         if (!emberAfEndpointIsEnabled(attributePath.mEndpointId))
     453              :         {
     454            0 :             return Status::UnsupportedEndpoint;
     455              :         }
     456            0 :         return Status::UnsupportedCluster;
     457              :     }
     458              : 
     459            0 :     Status status = Status::Success;
     460              :     // Casting and calling a function pointer on the same line results in ignoring the return
     461              :     // of the call on gcc-arm-none-eabi-9-2019-q4-major
     462            0 :     EmberAfClusterPreAttributeChangedCallback f = (EmberAfClusterPreAttributeChangedCallback) (emberAfFindClusterFunction(
     463              :         cluster, MATTER_CLUSTER_FLAG_PRE_ATTRIBUTE_CHANGED_FUNCTION));
     464            0 :     if (f != nullptr)
     465              :     {
     466            0 :         status = f(attributePath, attributeType, size, value);
     467              :     }
     468            0 :     return status;
     469              : }
     470              : 
     471           54 : static void initializeEndpoint(EmberAfDefinedEndpoint * definedEndpoint)
     472              : {
     473              :     uint8_t clusterIndex;
     474           54 :     const EmberAfEndpointType * epType = definedEndpoint->endpointType;
     475         2964 :     for (clusterIndex = 0; clusterIndex < epType->clusterCount; clusterIndex++)
     476              :     {
     477         2910 :         const EmberAfCluster * cluster = &(epType->cluster[clusterIndex]);
     478              :         EmberAfGenericClusterFunction f;
     479         2910 :         emberAfClusterInitCallback(definedEndpoint->endpoint, cluster->clusterId);
     480         2910 :         f = emberAfFindClusterFunction(cluster, MATTER_CLUSTER_FLAG_INIT_FUNCTION);
     481         2910 :         if (f != nullptr)
     482              :         {
     483            0 :             ((EmberAfInitFunction) f)(definedEndpoint->endpoint);
     484              :         }
     485              :     }
     486           54 : }
     487              : 
     488           28 : static void shutdownEndpoint(EmberAfDefinedEndpoint * definedEndpoint)
     489              : {
     490              :     // Call shutdown callbacks from clusters, mainly for canceling pending timers
     491              :     uint8_t clusterIndex;
     492           28 :     const EmberAfEndpointType * epType = definedEndpoint->endpointType;
     493           62 :     for (clusterIndex = 0; clusterIndex < epType->clusterCount; clusterIndex++)
     494              :     {
     495           34 :         const EmberAfCluster * cluster  = &(epType->cluster[clusterIndex]);
     496           34 :         EmberAfGenericClusterFunction f = emberAfFindClusterFunction(cluster, MATTER_CLUSTER_FLAG_SHUTDOWN_FUNCTION);
     497           34 :         if (f != nullptr)
     498              :         {
     499            0 :             ((EmberAfShutdownFunction) f)(definedEndpoint->endpoint);
     500              :         }
     501              :     }
     502              : 
     503           28 :     CommandHandlerInterfaceRegistry::Instance().UnregisterAllCommandHandlersForEndpoint(definedEndpoint->endpoint);
     504           28 :     AttributeAccessInterfaceRegistry::Instance().UnregisterAllForEndpoint(definedEndpoint->endpoint);
     505           28 : }
     506              : 
     507              : // Calls the init functions.
     508           25 : void emAfCallInits()
     509              : {
     510              :     uint16_t index;
     511           50 :     for (index = 0; index < emberAfEndpointCount(); index++)
     512              :     {
     513           25 :         if (emberAfEndpointIndexIsEnabled(index))
     514              :         {
     515           25 :             initializeEndpoint(&(emAfEndpoints[index]));
     516              :         }
     517              :     }
     518           25 : }
     519              : 
     520              : // Returns the pointer to metadata, or null if it is not found
     521         6914 : const EmberAfAttributeMetadata * emberAfLocateAttributeMetadata(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId)
     522              : {
     523         6914 :     const EmberAfAttributeMetadata * metadata = nullptr;
     524              :     EmberAfAttributeSearchRecord record;
     525         6914 :     record.endpoint    = endpoint;
     526         6914 :     record.clusterId   = clusterId;
     527         6914 :     record.attributeId = attributeId;
     528         6914 :     emAfReadOrWriteAttribute(&record, &metadata,
     529              :                              nullptr, // buffer
     530              :                              0,       // buffer size
     531              :                              false);  // write?
     532         6914 :     return metadata;
     533              : }
     534              : 
     535              : // This function does mem copy, but smartly, which means that if the type is a
     536              : // string, it will copy as much as it can.
     537              : // If src == NULL, then this method will set memory to zeroes
     538              : // See documentation for emAfReadOrWriteAttribute for the semantics of
     539              : // readLength when reading and writing.
     540            0 : static Status typeSensitiveMemCopy(ClusterId clusterId, uint8_t * dest, uint8_t * src, const EmberAfAttributeMetadata * am,
     541              :                                    bool write, uint16_t readLength)
     542              : {
     543            0 :     EmberAfAttributeType attributeType = am->attributeType;
     544              :     // readLength == 0 for a read indicates that we should just trust that the
     545              :     // caller has enough space for an attribute...
     546            0 :     bool ignoreReadLength = write || (readLength == 0);
     547            0 :     uint16_t bufferSize   = ignoreReadLength ? am->size : readLength;
     548              : 
     549            0 :     if (emberAfIsStringAttributeType(attributeType))
     550              :     {
     551            0 :         if (bufferSize < 1)
     552              :         {
     553            0 :             return Status::ResourceExhausted;
     554              :         }
     555            0 :         emberAfCopyString(dest, src, bufferSize - 1);
     556              :     }
     557            0 :     else if (emberAfIsLongStringAttributeType(attributeType))
     558              :     {
     559            0 :         if (bufferSize < 2)
     560              :         {
     561            0 :             return Status::ResourceExhausted;
     562              :         }
     563            0 :         emberAfCopyLongString(dest, src, bufferSize - 2);
     564              :     }
     565            0 :     else if (emberAfIsThisDataTypeAListType(attributeType))
     566              :     {
     567            0 :         if (bufferSize < 2)
     568              :         {
     569            0 :             return Status::ResourceExhausted;
     570              :         }
     571              : 
     572              :         // Just copy the length.
     573            0 :         memmove(dest, src, 2);
     574              :     }
     575              :     else
     576              :     {
     577            0 :         if (!ignoreReadLength && readLength < am->size)
     578              :         {
     579            0 :             return Status::ResourceExhausted;
     580              :         }
     581            0 :         if (src == nullptr)
     582              :         {
     583            0 :             memset(dest, 0, am->size);
     584              :         }
     585              :         else
     586              :         {
     587            0 :             memmove(dest, src, am->size);
     588              :         }
     589              :     }
     590            0 :     return Status::Success;
     591              : }
     592              : 
     593              : /**
     594              :  * @brief Matches a cluster based on cluster id and direction.
     595              :  *
     596              :  *   This function assumes that the passed cluster's endpoint already
     597              :  *   matches the endpoint of the EmberAfAttributeSearchRecord.
     598              :  *
     599              :  * Clusters match if:
     600              :  *   1. Cluster ids match AND
     601              :  *   2. Cluster is a server cluster (because there are no client attributes).
     602              :  */
     603         6914 : bool emAfMatchCluster(const EmberAfCluster * cluster, const EmberAfAttributeSearchRecord * attRecord)
     604              : {
     605         6914 :     return (cluster->clusterId == attRecord->clusterId && (cluster->mask & MATTER_CLUSTER_FLAG_SERVER));
     606              : }
     607              : 
     608              : /**
     609              :  * @brief Matches an attribute based on attribute id.
     610              :  *   This function assumes that the passed cluster already matches the
     611              :  *   clusterId and direction of the passed EmberAfAttributeSearchRecord.
     612              :  *
     613              :  * Attributes match if attr ids match.
     614              :  */
     615        10021 : bool emAfMatchAttribute(const EmberAfCluster * cluster, const EmberAfAttributeMetadata * am,
     616              :                         const EmberAfAttributeSearchRecord * attRecord)
     617              : {
     618        10021 :     return (am->attributeId == attRecord->attributeId);
     619              : }
     620              : 
     621              : // When reading non-string attributes, this function returns an error when destination
     622              : // buffer isn't large enough to accommodate the attribute type.  For strings, the
     623              : // function will copy at most readLength bytes.  This means the resulting string
     624              : // may be truncated.  The length byte(s) in the resulting string will reflect
     625              : // any truncation.  If readLength is zero, we are working with backwards-
     626              : // compatibility wrapper functions and we just cross our fingers and hope for
     627              : // the best.
     628              : //
     629              : // When writing attributes, readLength is ignored.  For non-string attributes,
     630              : // this function assumes the source buffer is the same size as the attribute
     631              : // type.  For strings, the function will copy as many bytes as will fit in the
     632              : // attribute.  This means the resulting string may be truncated.  The length
     633              : // byte(s) in the resulting string will reflect any truncated.
     634         6914 : Status emAfReadOrWriteAttribute(const EmberAfAttributeSearchRecord * attRecord, const EmberAfAttributeMetadata ** metadata,
     635              :                                 uint8_t * buffer, uint16_t readLength, bool write)
     636              : {
     637         6914 :     assertChipStackLockedByCurrentThread();
     638              : 
     639         6914 :     uint16_t attributeOffsetIndex = 0;
     640              : 
     641        13853 :     for (uint16_t ep = 0; ep < emberAfEndpointCount(); ep++)
     642              :     {
     643              :         // Is this a dynamic endpoint?
     644        13853 :         bool isDynamicEndpoint = (ep >= emberAfFixedEndpointCount());
     645              : 
     646        13853 :         if (emAfEndpoints[ep].endpoint == attRecord->endpoint)
     647              :         {
     648         6914 :             const EmberAfEndpointType * endpointType = emAfEndpoints[ep].endpointType;
     649              :             uint8_t clusterIndex;
     650         6914 :             if (!emberAfEndpointIndexIsEnabled(ep))
     651              :             {
     652            0 :                 continue;
     653              :             }
     654         6914 :             for (clusterIndex = 0; clusterIndex < endpointType->clusterCount; clusterIndex++)
     655              :             {
     656         6914 :                 const EmberAfCluster * cluster = &(endpointType->cluster[clusterIndex]);
     657         6914 :                 if (emAfMatchCluster(cluster, attRecord))
     658              :                 { // Got the cluster
     659              :                     uint16_t attrIndex;
     660        10021 :                     for (attrIndex = 0; attrIndex < cluster->attributeCount; attrIndex++)
     661              :                     {
     662        10021 :                         const EmberAfAttributeMetadata * am = &(cluster->attributes[attrIndex]);
     663        10021 :                         if (emAfMatchAttribute(cluster, am, attRecord))
     664              :                         { // Got the attribute
     665              :                             // If passed metadata location is not null, populate
     666         6914 :                             if (metadata != nullptr)
     667              :                             {
     668         6914 :                                 *metadata = am;
     669              :                             }
     670              : 
     671              :                             {
     672         6914 :                                 uint8_t * attributeLocation = attributeData + attributeOffsetIndex;
     673              :                                 uint8_t *src, *dst;
     674         6914 :                                 if (write)
     675              :                                 {
     676            0 :                                     src = buffer;
     677            0 :                                     dst = attributeLocation;
     678            0 :                                     if (!emberAfAttributeWriteAccessCallback(attRecord->endpoint, attRecord->clusterId,
     679            0 :                                                                              am->attributeId))
     680              :                                     {
     681            0 :                                         return Status::UnsupportedAccess;
     682              :                                     }
     683              :                                 }
     684              :                                 else
     685              :                                 {
     686         6914 :                                     if (buffer == nullptr)
     687              :                                     {
     688         6914 :                                         return Status::Success;
     689              :                                     }
     690              : 
     691            0 :                                     src = attributeLocation;
     692            0 :                                     dst = buffer;
     693            0 :                                     if (!emberAfAttributeReadAccessCallback(attRecord->endpoint, attRecord->clusterId,
     694            0 :                                                                             am->attributeId))
     695              :                                     {
     696            0 :                                         return Status::UnsupportedAccess;
     697              :                                     }
     698              :                                 }
     699              : 
     700              :                                 // Is the attribute externally stored?
     701            0 :                                 if (am->mask & MATTER_ATTRIBUTE_FLAG_EXTERNAL_STORAGE)
     702              :                                 {
     703            0 :                                     if (write)
     704              :                                     {
     705            0 :                                         return emberAfExternalAttributeWriteCallback(attRecord->endpoint, attRecord->clusterId, am,
     706            0 :                                                                                      buffer);
     707              :                                     }
     708              : 
     709            0 :                                     if (readLength < emberAfAttributeSize(am))
     710              :                                     {
     711              :                                         // Prevent a potential buffer overflow
     712            0 :                                         return Status::ResourceExhausted;
     713              :                                     }
     714              : 
     715            0 :                                     return emberAfExternalAttributeReadCallback(attRecord->endpoint, attRecord->clusterId, am,
     716            0 :                                                                                 buffer, emberAfAttributeSize(am));
     717              :                                 }
     718              : 
     719              :                                 // Internal storage is only supported for fixed endpoints
     720            0 :                                 if (!isDynamicEndpoint)
     721              :                                 {
     722            0 :                                     return typeSensitiveMemCopy(attRecord->clusterId, dst, src, am, write, readLength);
     723              :                                 }
     724              : 
     725            0 :                                 return Status::Failure;
     726              :                             }
     727              :                         }
     728              :                         else
     729              :                         { // Not the attribute we are looking for
     730              :                             // Increase the index if attribute is not externally stored
     731         3107 :                             if (!(am->mask & MATTER_ATTRIBUTE_FLAG_EXTERNAL_STORAGE))
     732              :                             {
     733            0 :                                 attributeOffsetIndex = static_cast<uint16_t>(attributeOffsetIndex + emberAfAttributeSize(am));
     734              :                             }
     735              :                         }
     736              :                     }
     737              : 
     738              :                     // Attribute is not in the cluster.
     739            0 :                     return Status::UnsupportedAttribute;
     740              :                 }
     741              : 
     742              :                 // Not the cluster we are looking for
     743            0 :                 attributeOffsetIndex = static_cast<uint16_t>(attributeOffsetIndex + cluster->clusterSize);
     744              :             }
     745              : 
     746              :             // Cluster is not in the endpoint.
     747            0 :             return Status::UnsupportedCluster;
     748              :         }
     749              : 
     750              :         // Not the endpoint we are looking for
     751              :         // Dynamic endpoints are external and don't factor into storage size
     752         6939 :         if (!isDynamicEndpoint)
     753              :         {
     754         6914 :             attributeOffsetIndex = static_cast<uint16_t>(attributeOffsetIndex + emAfEndpoints[ep].endpointType->endpointSize);
     755              :         }
     756              :     }
     757            0 :     return Status::UnsupportedEndpoint; // Sorry, endpoint was not found.
     758              : }
     759              : 
     760         4310 : const EmberAfEndpointType * emberAfFindEndpointType(EndpointId endpointId)
     761              : {
     762         4310 :     uint16_t ep = emberAfIndexFromEndpoint(endpointId);
     763         4310 :     if (ep == kEmberInvalidEndpointIndex)
     764              :     {
     765            5 :         return nullptr;
     766              :     }
     767         4305 :     return emAfEndpoints[ep].endpointType;
     768              : }
     769              : 
     770         9504 : const EmberAfCluster * emberAfFindClusterInType(const EmberAfEndpointType * endpointType, ClusterId clusterId,
     771              :                                                 EmberAfClusterMask mask, uint8_t * index)
     772              : {
     773              :     uint8_t i;
     774         9504 :     uint8_t scopedIndex = 0;
     775              : 
     776         9535 :     for (i = 0; i < endpointType->clusterCount; i++)
     777              :     {
     778         9525 :         const EmberAfCluster * cluster = &(endpointType->cluster[i]);
     779              : 
     780         9525 :         if (mask == 0 || ((cluster->mask & mask) != 0))
     781              :         {
     782         9525 :             if (cluster->clusterId == clusterId)
     783              :             {
     784         9494 :                 if (index)
     785              :                 {
     786         9459 :                     *index = scopedIndex;
     787              :                 }
     788              : 
     789         9494 :                 return cluster;
     790              :             }
     791              : 
     792           31 :             scopedIndex++;
     793              :         }
     794              :     }
     795              : 
     796           10 :     return nullptr;
     797              : }
     798              : 
     799         9469 : uint8_t emberAfClusterIndex(EndpointId endpoint, ClusterId clusterId, EmberAfClusterMask mask)
     800              : {
     801        19053 :     for (uint16_t ep = 0; ep < emberAfEndpointCount(); ep++)
     802              :     {
     803              :         // Check the endpoint id first, because that way we avoid examining the
     804              :         // endpoint type for endpoints that are not actually defined.
     805        19043 :         if (emAfEndpoints[ep].endpoint == endpoint)
     806              :         {
     807         9469 :             const EmberAfEndpointType * endpointType = emAfEndpoints[ep].endpointType;
     808         9469 :             uint8_t index                            = 0xFF;
     809         9469 :             if (emberAfFindClusterInType(endpointType, clusterId, mask, &index) != nullptr)
     810              :             {
     811         9459 :                 return index;
     812              :             }
     813              :         }
     814              :     }
     815           10 :     return 0xFF;
     816              : }
     817              : 
     818              : // Returns whether the given endpoint has the server of the given cluster on it.
     819            0 : bool emberAfContainsServer(EndpointId endpoint, ClusterId clusterId)
     820              : {
     821            0 :     return (emberAfFindServerCluster(endpoint, clusterId) != nullptr);
     822              : }
     823              : 
     824              : // Returns whether the given endpoint has the client of the given cluster on it.
     825            0 : bool emberAfContainsClient(EndpointId endpoint, ClusterId clusterId)
     826              : {
     827            0 :     uint16_t ep = emberAfIndexFromEndpoint(endpoint);
     828            0 :     if (ep == kEmberInvalidEndpointIndex)
     829              :     {
     830            0 :         return false;
     831              :     }
     832              : 
     833            0 :     return (emberAfFindClusterInType(emAfEndpoints[ep].endpointType, clusterId, MATTER_CLUSTER_FLAG_CLIENT) != nullptr);
     834              : }
     835              : 
     836              : // This will find the first server that has the clusterId given from the index of endpoint.
     837            0 : bool emberAfContainsServerFromIndex(uint16_t index, ClusterId clusterId)
     838              : {
     839            0 :     if (index == kEmberInvalidEndpointIndex)
     840              :     {
     841            0 :         return false;
     842              :     }
     843              : 
     844            0 :     return emberAfFindClusterInType(emAfEndpoints[index].endpointType, clusterId, MATTER_CLUSTER_FLAG_SERVER);
     845              : }
     846              : 
     847              : namespace chip {
     848              : namespace app {
     849              : 
     850            0 : EnabledEndpointsWithServerCluster::EnabledEndpointsWithServerCluster(ClusterId clusterId) :
     851            0 :     mEndpointCount(emberAfEndpointCount()), mClusterId(clusterId)
     852              : {
     853            0 :     EnsureMatchingEndpoint();
     854            0 : }
     855              : 
     856            0 : EndpointId EnabledEndpointsWithServerCluster::operator*() const
     857              : {
     858            0 :     return emberAfEndpointFromIndex(mEndpointIndex);
     859              : }
     860              : 
     861            0 : EnabledEndpointsWithServerCluster & EnabledEndpointsWithServerCluster::operator++()
     862              : {
     863            0 :     ++mEndpointIndex;
     864            0 :     EnsureMatchingEndpoint();
     865            0 :     return *this;
     866              : }
     867              : 
     868            0 : void EnabledEndpointsWithServerCluster::EnsureMatchingEndpoint()
     869              : {
     870            0 :     for (; mEndpointIndex < mEndpointCount; ++mEndpointIndex)
     871              :     {
     872            0 :         if (!emberAfEndpointIndexIsEnabled(mEndpointIndex))
     873              :         {
     874            0 :             continue;
     875              :         }
     876              : 
     877            0 :         if (emberAfContainsServerFromIndex(mEndpointIndex, mClusterId))
     878              :         {
     879            0 :             break;
     880              :         }
     881              :     }
     882            0 : }
     883              : 
     884              : } // namespace app
     885              : } // namespace chip
     886              : 
     887              : // Finds the cluster that matches endpoint, clusterId, direction.
     888           36 : const EmberAfCluster * emberAfFindServerCluster(EndpointId endpoint, ClusterId clusterId)
     889              : {
     890           36 :     uint16_t ep = emberAfIndexFromEndpoint(endpoint);
     891           36 :     if (ep == kEmberInvalidEndpointIndex)
     892              :     {
     893            1 :         return nullptr;
     894              :     }
     895              : 
     896           35 :     return emberAfFindClusterInType(emAfEndpoints[ep].endpointType, clusterId, MATTER_CLUSTER_FLAG_SERVER);
     897              : }
     898              : 
     899              : // Returns cluster within the endpoint; Does not ignore disabled endpoints
     900            0 : const EmberAfCluster * emberAfFindClusterIncludingDisabledEndpoints(EndpointId endpoint, ClusterId clusterId,
     901              :                                                                     EmberAfClusterMask mask)
     902              : {
     903            0 :     uint16_t ep = emberAfIndexFromEndpointIncludingDisabledEndpoints(endpoint);
     904            0 :     if (ep < MAX_ENDPOINT_COUNT)
     905              :     {
     906            0 :         return emberAfFindClusterInType(emAfEndpoints[ep].endpointType, clusterId, mask);
     907              :     }
     908            0 :     return nullptr;
     909              : }
     910              : 
     911            0 : uint16_t emberAfGetClusterServerEndpointIndex(EndpointId endpoint, ClusterId cluster, uint16_t fixedClusterServerEndpointCount)
     912              : {
     913            0 :     VerifyOrDie(fixedClusterServerEndpointCount <= FIXED_ENDPOINT_COUNT);
     914            0 :     uint16_t epIndex = findIndexFromEndpoint(endpoint, true /*ignoreDisabledEndpoints*/);
     915              : 
     916              :     // Endpoint must be configured and enabled
     917            0 :     if (epIndex == kEmberInvalidEndpointIndex)
     918              :     {
     919            0 :         return kEmberInvalidEndpointIndex;
     920              :     }
     921              : 
     922            0 :     if (emberAfFindClusterInType(emAfEndpoints[epIndex].endpointType, cluster, MATTER_CLUSTER_FLAG_SERVER) == nullptr)
     923              :     {
     924              :         // The provided endpoint does not contain the given cluster server.
     925            0 :         return kEmberInvalidEndpointIndex;
     926              :     }
     927              : 
     928            0 :     if (epIndex < FIXED_ENDPOINT_COUNT)
     929              :     {
     930              :         // This endpoint is a fixed one.
     931              :         // Return the index of this endpoint in the list of fixed endpoints that support the given cluster.
     932            0 :         uint16_t adjustedEndpointIndex = 0;
     933            0 :         for (uint16_t i = 0; i < epIndex; i++)
     934              :         {
     935              :             // Increase adjustedEndpointIndex for every endpoint containing the cluster server
     936              :             // before our endpoint of interest
     937            0 :             if (emAfEndpoints[i].endpoint != kInvalidEndpointId &&
     938            0 :                 (emberAfFindClusterInType(emAfEndpoints[i].endpointType, cluster, MATTER_CLUSTER_FLAG_SERVER) != nullptr))
     939              :             {
     940            0 :                 adjustedEndpointIndex++;
     941              :             }
     942              :         }
     943              : 
     944              :         // If this asserts, the provided fixedClusterServerEndpointCount doesn't match the app data model.
     945            0 :         VerifyOrDie(adjustedEndpointIndex < fixedClusterServerEndpointCount);
     946            0 :         epIndex = adjustedEndpointIndex;
     947              :     }
     948              :     else
     949              :     {
     950              :         // This is a dynamic endpoint.
     951              :         // Its index is just its index in the dynamic endpoint list, offset by fixedClusterServerEndpointCount.
     952            0 :         epIndex = static_cast<uint16_t>(fixedClusterServerEndpointCount + (epIndex - FIXED_ENDPOINT_COUNT));
     953              :     }
     954              : 
     955            0 :     return epIndex;
     956              : }
     957              : 
     958            0 : bool emberAfEndpointIsEnabled(EndpointId endpoint)
     959              : {
     960            0 :     uint16_t index = findIndexFromEndpoint(endpoint, false /* ignoreDisabledEndpoints */);
     961              : 
     962            0 :     if (kEmberInvalidEndpointIndex == index)
     963              :     {
     964            0 :         return false;
     965              :     }
     966              : 
     967            0 :     return emberAfEndpointIndexIsEnabled(index);
     968              : }
     969              : 
     970           57 : bool emberAfEndpointEnableDisable(EndpointId endpoint, bool enable)
     971              : {
     972           57 :     uint16_t index = findIndexFromEndpoint(endpoint, false /* ignoreDisabledEndpoints */);
     973              :     bool currentlyEnabled;
     974              : 
     975           57 :     if (kEmberInvalidEndpointIndex == index)
     976              :     {
     977            0 :         return false;
     978              :     }
     979              : 
     980           57 :     currentlyEnabled = emAfEndpoints[index].bitmask.Has(EmberAfEndpointOptions::isEnabled);
     981              : 
     982           57 :     if (enable)
     983              :     {
     984           29 :         emAfEndpoints[index].bitmask.Set(EmberAfEndpointOptions::isEnabled);
     985              :     }
     986              : 
     987           57 :     if (currentlyEnabled != enable)
     988              :     {
     989           57 :         if (enable)
     990              :         {
     991           29 :             initializeEndpoint(&(emAfEndpoints[index]));
     992           29 :             emberAfEndpointChanged(endpoint, emberAfGlobalInteractionModelAttributesChangedListener());
     993              :         }
     994              :         else
     995              :         {
     996           28 :             shutdownEndpoint(&(emAfEndpoints[index]));
     997           28 :             emAfEndpoints[index].bitmask.Clear(EmberAfEndpointOptions::isEnabled);
     998              :         }
     999              : 
    1000           57 :         EndpointId parentEndpointId = emberAfParentEndpointFromIndex(index);
    1001           57 :         while (parentEndpointId != kInvalidEndpointId)
    1002              :         {
    1003            0 :             emberAfAttributeChanged(parentEndpointId, Clusters::Descriptor::Id, Clusters::Descriptor::Attributes::PartsList::Id,
    1004              :                                     emberAfGlobalInteractionModelAttributesChangedListener());
    1005            0 :             uint16_t parentIndex = emberAfIndexFromEndpoint(parentEndpointId);
    1006            0 :             if (parentIndex == kEmberInvalidEndpointIndex)
    1007              :             {
    1008              :                 // Something has gone wrong.
    1009            0 :                 break;
    1010              :             }
    1011            0 :             parentEndpointId = emberAfParentEndpointFromIndex(parentIndex);
    1012              :         }
    1013              : 
    1014           57 :         emberAfAttributeChanged(/* endpoint = */ 0, Clusters::Descriptor::Id, Clusters::Descriptor::Attributes::PartsList::Id,
    1015              :                                 emberAfGlobalInteractionModelAttributesChangedListener());
    1016              :     }
    1017              : 
    1018           57 :     emberMetadataStructureGeneration++;
    1019           57 :     return true;
    1020              : }
    1021              : 
    1022        12136 : unsigned emberAfMetadataStructureGeneration()
    1023              : {
    1024        12136 :     return emberMetadataStructureGeneration;
    1025              : }
    1026              : 
    1027              : // Returns the index of a given endpoint.  Does not consider disabled endpoints.
    1028        13862 : uint16_t emberAfIndexFromEndpoint(EndpointId endpoint)
    1029              : {
    1030        13862 :     return findIndexFromEndpoint(endpoint, true /* ignoreDisabledEndpoints */);
    1031              : }
    1032              : 
    1033         2917 : EndpointId emberAfEndpointFromIndex(uint16_t index)
    1034              : {
    1035         2917 :     return emAfEndpoints[index].endpoint;
    1036              : }
    1037              : 
    1038         2974 : EndpointId emberAfParentEndpointFromIndex(uint16_t index)
    1039              : {
    1040         2974 :     return emAfEndpoints[index].parentEndpointId;
    1041              : }
    1042              : 
    1043              : // If server == true, returns the number of server clusters,
    1044              : // otherwise number of client clusters on this endpoint
    1045            0 : uint8_t emberAfClusterCount(EndpointId endpoint, bool server)
    1046              : {
    1047            0 :     uint16_t index = emberAfIndexFromEndpoint(endpoint);
    1048            0 :     if (index == kEmberInvalidEndpointIndex)
    1049              :     {
    1050            0 :         return 0;
    1051              :     }
    1052              : 
    1053            0 :     return emberAfClusterCountByIndex(index, server);
    1054              : }
    1055              : 
    1056           25 : uint8_t emberAfClusterCountByIndex(uint16_t endpointIndex, bool server)
    1057              : {
    1058           25 :     const EmberAfDefinedEndpoint * de = &(emAfEndpoints[endpointIndex]);
    1059           25 :     if (de->endpointType == nullptr)
    1060              :     {
    1061            0 :         return 0;
    1062              :     }
    1063              : 
    1064           25 :     return emberAfClusterCountForEndpointType(de->endpointType, server);
    1065              : }
    1066              : 
    1067         4358 : uint8_t emberAfClusterCountForEndpointType(const EmberAfEndpointType * type, bool server)
    1068              : {
    1069         4358 :     const EmberAfClusterMask cluster_mask = server ? MATTER_CLUSTER_FLAG_SERVER : MATTER_CLUSTER_FLAG_CLIENT;
    1070              : 
    1071         4358 :     return static_cast<uint8_t>(std::count_if(type->cluster, type->cluster + type->clusterCount,
    1072        13075 :                                               [=](const EmberAfCluster & cluster) { return (cluster.mask & cluster_mask) != 0; }));
    1073              : }
    1074              : 
    1075            0 : uint8_t emberAfGetClusterCountForEndpoint(EndpointId endpoint)
    1076              : {
    1077            0 :     uint16_t index = emberAfIndexFromEndpoint(endpoint);
    1078            0 :     if (index == kEmberInvalidEndpointIndex)
    1079              :     {
    1080            0 :         return 0;
    1081              :     }
    1082            0 :     return emAfEndpoints[index].endpointType->clusterCount;
    1083              : }
    1084              : 
    1085            0 : Span<const EmberAfDeviceType> emberAfDeviceTypeListFromEndpoint(EndpointId endpoint, CHIP_ERROR & err)
    1086              : {
    1087            0 :     return emberAfDeviceTypeListFromEndpointIndex(emberAfIndexFromEndpoint(endpoint), err);
    1088              : }
    1089              : 
    1090            0 : chip::Span<const EmberAfDeviceType> emberAfDeviceTypeListFromEndpointIndex(unsigned endpointIndex, CHIP_ERROR & err)
    1091              : {
    1092            0 :     if (endpointIndex == 0xFFFF)
    1093              :     {
    1094            0 :         err = CHIP_ERROR_INVALID_ARGUMENT;
    1095            0 :         return Span<const EmberAfDeviceType>();
    1096              :     }
    1097              : 
    1098            0 :     err = CHIP_NO_ERROR;
    1099            0 :     return emAfEndpoints[endpointIndex].deviceTypeList;
    1100              : }
    1101              : 
    1102            0 : CHIP_ERROR GetSemanticTagForEndpointAtIndex(EndpointId endpoint, size_t index,
    1103              :                                             Clusters::Descriptor::Structs::SemanticTagStruct::Type & tag)
    1104              : {
    1105            0 :     uint16_t endpointIndex = emberAfIndexFromEndpoint(endpoint);
    1106              : 
    1107            0 :     if (endpointIndex == 0xFFFF || index >= emAfEndpoints[endpointIndex].tagList.size())
    1108              :     {
    1109            0 :         return CHIP_ERROR_NOT_FOUND;
    1110              :     }
    1111            0 :     tag = emAfEndpoints[endpointIndex].tagList[index];
    1112            0 :     return CHIP_NO_ERROR;
    1113              : }
    1114              : #if CHIP_CONFIG_USE_ENDPOINT_UNIQUE_ID
    1115              : CHIP_ERROR emberAfGetEndpointUniqueIdForEndPoint(EndpointId endpoint, MutableCharSpan & epUniqueIdMutSpan)
    1116              : {
    1117              :     uint16_t endpointIndex = emberAfIndexFromEndpoint(endpoint);
    1118              : 
    1119              :     if (endpointIndex == 0xFFFF)
    1120              :     {
    1121              :         return CHIP_ERROR_NOT_FOUND;
    1122              :     }
    1123              : 
    1124              :     CharSpan epUniqueIdSpan(emAfEndpoints[endpointIndex].endpointUniqueId, emAfEndpoints[endpointIndex].endpointUniqueIdSize);
    1125              :     return CopyCharSpanToMutableCharSpan(epUniqueIdSpan, epUniqueIdMutSpan);
    1126              : }
    1127              : #endif
    1128            0 : CHIP_ERROR emberAfSetDeviceTypeList(EndpointId endpoint, Span<const EmberAfDeviceType> deviceTypeList)
    1129              : {
    1130            0 :     uint16_t endpointIndex = emberAfIndexFromEndpoint(endpoint);
    1131            0 :     if (endpointIndex == 0xFFFF)
    1132              :     {
    1133            0 :         return CHIP_ERROR_INVALID_ARGUMENT;
    1134              :     }
    1135              : 
    1136            0 :     emAfEndpoints[endpointIndex].deviceTypeList = deviceTypeList;
    1137            0 :     return CHIP_NO_ERROR;
    1138              : }
    1139              : 
    1140            0 : CHIP_ERROR SetTagList(EndpointId endpoint, Span<const Clusters::Descriptor::Structs::SemanticTagStruct::Type> tagList)
    1141              : {
    1142            0 :     uint16_t endpointIndex = emberAfIndexFromEndpoint(endpoint);
    1143            0 :     if (endpointIndex == 0xFFFF)
    1144              :     {
    1145            0 :         return CHIP_ERROR_INVALID_ARGUMENT;
    1146              :     }
    1147              : 
    1148            0 :     emAfEndpoints[endpointIndex].tagList = tagList;
    1149            0 :     return CHIP_NO_ERROR;
    1150              : }
    1151              : 
    1152              : // Returns the cluster of Nth server or client cluster,
    1153              : // depending on server toggle.
    1154            0 : const EmberAfCluster * emberAfGetNthCluster(EndpointId endpoint, uint8_t n, bool server)
    1155              : {
    1156            0 :     uint16_t index = emberAfIndexFromEndpoint(endpoint);
    1157            0 :     if (index == kEmberInvalidEndpointIndex)
    1158              :     {
    1159            0 :         return nullptr;
    1160              :     }
    1161              : 
    1162            0 :     const EmberAfEndpointType * endpointType = emAfEndpoints[index].endpointType;
    1163            0 :     const EmberAfClusterMask cluster_mask    = server ? MATTER_CLUSTER_FLAG_SERVER : MATTER_CLUSTER_FLAG_CLIENT;
    1164            0 :     const uint8_t clusterCount               = endpointType->clusterCount;
    1165              : 
    1166            0 :     uint8_t c = 0;
    1167            0 :     for (uint8_t i = 0; i < clusterCount; i++)
    1168              :     {
    1169            0 :         const EmberAfCluster * cluster = &(endpointType->cluster[i]);
    1170              : 
    1171            0 :         if ((cluster->mask & cluster_mask) == 0)
    1172              :         {
    1173            0 :             continue;
    1174              :         }
    1175              : 
    1176            0 :         if (c == n)
    1177              :         {
    1178            0 :             return cluster;
    1179              :         }
    1180              : 
    1181            0 :         c++;
    1182              :     }
    1183            0 :     return nullptr;
    1184              : }
    1185              : 
    1186              : // Returns the cluster id of Nth server or client cluster,
    1187              : // depending on server toggle.
    1188              : // Returns Optional<ClusterId>::Missing() if cluster does not exist.
    1189            0 : Optional<ClusterId> emberAfGetNthClusterId(EndpointId endpoint, uint8_t n, bool server)
    1190              : {
    1191            0 :     const EmberAfCluster * cluster = emberAfGetNthCluster(endpoint, n, server);
    1192            0 :     if (cluster == nullptr)
    1193              :     {
    1194            0 :         return Optional<ClusterId>::Missing();
    1195              :     }
    1196            0 :     return Optional<ClusterId>(cluster->clusterId);
    1197              : }
    1198              : 
    1199              : // Returns number of clusters put into the passed cluster list
    1200              : // for the given endpoint and client/server polarity
    1201            0 : uint8_t emberAfGetClustersFromEndpoint(EndpointId endpoint, ClusterId * clusterList, uint8_t listLen, bool server)
    1202              : {
    1203            0 :     uint8_t clusterCount = emberAfClusterCount(endpoint, server);
    1204              :     uint8_t i;
    1205              :     const EmberAfCluster * cluster;
    1206            0 :     if (clusterCount > listLen)
    1207              :     {
    1208            0 :         clusterCount = listLen;
    1209              :     }
    1210            0 :     for (i = 0; i < clusterCount; i++)
    1211              :     {
    1212            0 :         cluster        = emberAfGetNthCluster(endpoint, i, server);
    1213            0 :         clusterList[i] = (cluster == nullptr ? kEmberInvalidEndpointIndex : cluster->clusterId);
    1214              :     }
    1215            0 :     return clusterCount;
    1216              : }
    1217              : 
    1218           25 : void emberAfInitializeAttributes(EndpointId endpoint)
    1219              : {
    1220           25 :     emAfLoadAttributeDefaults(endpoint);
    1221           25 : }
    1222              : 
    1223           25 : void emAfLoadAttributeDefaults(EndpointId endpoint, Optional<ClusterId> clusterId)
    1224              : {
    1225              :     uint16_t ep;
    1226              :     uint8_t clusterI;
    1227              :     uint16_t attr;
    1228              :     uint8_t * ptr;
    1229           25 :     uint16_t epCount = emberAfEndpointCount();
    1230              :     uint8_t attrData[ATTRIBUTE_LARGEST];
    1231           25 :     auto * attrStorage = GetAttributePersistenceProvider();
    1232              :     // Don't check whether we actually have an attrStorage here, because it's OK
    1233              :     // to have one if none of our attributes have NVM storage.
    1234              : 
    1235           50 :     for (ep = 0; ep < epCount; ep++)
    1236              :     {
    1237              :         EmberAfDefinedEndpoint * de;
    1238           25 :         if (endpoint != kInvalidEndpointId)
    1239              :         {
    1240            0 :             ep = emberAfIndexFromEndpoint(endpoint);
    1241            0 :             if (ep == kEmberInvalidEndpointIndex)
    1242              :             {
    1243            0 :                 return;
    1244              :             }
    1245              :         }
    1246           25 :         de = &(emAfEndpoints[ep]);
    1247              : 
    1248         2900 :         for (clusterI = 0; clusterI < de->endpointType->clusterCount; clusterI++)
    1249              :         {
    1250         2875 :             const EmberAfCluster * cluster = &(de->endpointType->cluster[clusterI]);
    1251         2875 :             if (clusterId.HasValue())
    1252              :             {
    1253            0 :                 if (clusterId.Value() != cluster->clusterId)
    1254              :                 {
    1255            0 :                     continue;
    1256              :                 }
    1257              :             }
    1258              : 
    1259              :             // when the attributeCount is high, the loop takes too long to run and a
    1260              :             // watchdog kicks in causing a reset. As a workaround, we'll
    1261              :             // conditionally manually reset the watchdog. 300 sounds like a good
    1262              :             // magic number for now.
    1263         2875 :             if (cluster->attributeCount > 300)
    1264              :             {
    1265              :                 // halResetWatchdog();
    1266              :             }
    1267         2875 :             for (attr = 0; attr < cluster->attributeCount; attr++)
    1268              :             {
    1269            0 :                 const EmberAfAttributeMetadata * am = &(cluster->attributes[attr]);
    1270            0 :                 ptr                                 = nullptr; // Will get set to the value to write, as needed.
    1271              : 
    1272              :                 // First check for a persisted value.
    1273            0 :                 if (am->IsAutomaticallyPersisted())
    1274              :                 {
    1275            0 :                     VerifyOrDieWithMsg(attrStorage != nullptr, Zcl, "Attribute persistence needs a persistence provider");
    1276            0 :                     MutableByteSpan bytes(attrData);
    1277              :                     CHIP_ERROR err =
    1278            0 :                         attrStorage->ReadValue(ConcreteAttributePath(de->endpoint, cluster->clusterId, am->attributeId), bytes);
    1279            0 :                     if (err == CHIP_NO_ERROR)
    1280              :                     {
    1281            0 :                         err = ValidateDataContent(bytes, am);
    1282              :                     }
    1283              : 
    1284            0 :                     if (err == CHIP_NO_ERROR)
    1285              :                     {
    1286            0 :                         ptr = attrData;
    1287              :                     }
    1288              :                     else
    1289              :                     {
    1290            0 :                         ChipLogDetail(
    1291              :                             DataManagement,
    1292              :                             "Failed to read stored attribute (%u, " ChipLogFormatMEI ", " ChipLogFormatMEI ": %" CHIP_ERROR_FORMAT,
    1293              :                             de->endpoint, ChipLogValueMEI(cluster->clusterId), ChipLogValueMEI(am->attributeId), err.Format());
    1294              :                         // Just fall back to default value.
    1295              :                     }
    1296              :                 }
    1297              : 
    1298            0 :                 if (!am->IsExternal())
    1299              :                 {
    1300              :                     EmberAfAttributeSearchRecord record;
    1301            0 :                     record.endpoint    = de->endpoint;
    1302            0 :                     record.clusterId   = cluster->clusterId;
    1303            0 :                     record.attributeId = am->attributeId;
    1304              : 
    1305            0 :                     if (ptr == nullptr)
    1306              :                     {
    1307            0 :                         size_t defaultValueSizeForBigEndianNudger = 0;
    1308              :                         // Bypasses compiler warning about unused variable for little endian platforms.
    1309              :                         (void) defaultValueSizeForBigEndianNudger;
    1310            0 :                         if ((am->mask & MATTER_ATTRIBUTE_FLAG_MIN_MAX) != 0U)
    1311              :                         {
    1312              :                             // This is intentionally 2 and not 4 bytes since defaultValue in min/max
    1313              :                             // attributes is still uint16_t.
    1314            0 :                             if (emberAfAttributeSize(am) <= 2)
    1315              :                             {
    1316              :                                 static_assert(sizeof(am->defaultValue.ptrToMinMaxValue->defaultValue.defaultValue) == 2,
    1317              :                                               "if statement relies on size of max/min defaultValue being 2");
    1318            0 :                                 ptr = (uint8_t *) &(am->defaultValue.ptrToMinMaxValue->defaultValue.defaultValue);
    1319            0 :                                 defaultValueSizeForBigEndianNudger =
    1320              :                                     sizeof(am->defaultValue.ptrToMinMaxValue->defaultValue.defaultValue);
    1321              :                             }
    1322              :                             else
    1323              :                             {
    1324            0 :                                 ptr = (uint8_t *) am->defaultValue.ptrToMinMaxValue->defaultValue.ptrToDefaultValue;
    1325              :                             }
    1326              :                         }
    1327              :                         else
    1328              :                         {
    1329            0 :                             if ((emberAfAttributeSize(am) <= 4) && !emberAfIsStringAttributeType(am->attributeType))
    1330              :                             {
    1331            0 :                                 ptr                                = (uint8_t *) &(am->defaultValue.defaultValue);
    1332            0 :                                 defaultValueSizeForBigEndianNudger = sizeof(am->defaultValue.defaultValue);
    1333              :                             }
    1334              :                             else
    1335              :                             {
    1336            0 :                                 ptr = (uint8_t *) am->defaultValue.ptrToDefaultValue;
    1337              :                             }
    1338              :                         }
    1339              :                         // At this point, ptr either points to a default value, or is NULL, in which case
    1340              :                         // it should be treated as if it is pointing to an array of all zeroes.
    1341              : 
    1342              : #if (CHIP_CONFIG_BIG_ENDIAN_TARGET)
    1343              :                         // The default values for attributes that are less than or equal to
    1344              :                         // defaultValueSizeForBigEndianNudger in bytes are stored in an
    1345              :                         // uint32_t.  On big-endian platforms, a pointer to the default value
    1346              :                         // of size less than defaultValueSizeForBigEndianNudger will point to the wrong
    1347              :                         // byte.  So, for those cases, nudge the pointer forward so it points
    1348              :                         // to the correct byte.
    1349              :                         if (emberAfAttributeSize(am) < defaultValueSizeForBigEndianNudger && ptr != NULL)
    1350              :                         {
    1351              :                             ptr += (defaultValueSizeForBigEndianNudger - emberAfAttributeSize(am));
    1352              :                         }
    1353              : #endif // BIGENDIAN
    1354              :                     }
    1355              : 
    1356            0 :                     emAfReadOrWriteAttribute(&record,
    1357              :                                              nullptr, // metadata - unused
    1358              :                                              ptr,
    1359              :                                              0,     // buffer size - unused
    1360              :                                              true); // write?
    1361              :                 }
    1362              :             }
    1363              :         }
    1364           25 :         if (endpoint != kInvalidEndpointId)
    1365              :         {
    1366            0 :             break;
    1367              :         }
    1368              :     }
    1369              : }
    1370              : 
    1371              : // 'data' argument may be null, since we changed the ptrToDefaultValue
    1372              : // to be null instead of pointing to all zeroes.
    1373              : // This function has to be able to deal with that.
    1374            0 : void emAfSaveAttributeToStorageIfNeeded(uint8_t * data, EndpointId endpoint, ClusterId clusterId,
    1375              :                                         const EmberAfAttributeMetadata * metadata)
    1376              : {
    1377              :     // Get out of here if this attribute isn't marked non-volatile.
    1378            0 :     if (!metadata->IsAutomaticallyPersisted())
    1379              :     {
    1380            0 :         return;
    1381              :     }
    1382              : 
    1383              :     // TODO: Maybe we should have a separate constant for the size of the
    1384              :     // largest non-volatile attribute?
    1385            0 :     uint8_t allZeroData[ATTRIBUTE_LARGEST] = { 0 };
    1386            0 :     if (data == nullptr)
    1387              :     {
    1388            0 :         data = allZeroData;
    1389              :     }
    1390              : 
    1391              :     size_t dataSize;
    1392            0 :     EmberAfAttributeType type = metadata->attributeType;
    1393            0 :     if (emberAfIsStringAttributeType(type))
    1394              :     {
    1395            0 :         dataSize = emberAfStringLength(data) + 1;
    1396              :     }
    1397            0 :     else if (emberAfIsLongStringAttributeType(type))
    1398              :     {
    1399            0 :         dataSize = emberAfLongStringLength(data) + 2;
    1400              :     }
    1401              :     else
    1402              :     {
    1403            0 :         dataSize = metadata->size;
    1404              :     }
    1405              : 
    1406            0 :     auto * attrStorage = GetAttributePersistenceProvider();
    1407            0 :     if (attrStorage)
    1408              :     {
    1409            0 :         attrStorage->WriteValue(ConcreteAttributePath(endpoint, clusterId, metadata->attributeId), ByteSpan(data, dataSize));
    1410              :     }
    1411              :     else
    1412              :     {
    1413            0 :         ChipLogProgress(DataManagement, "Can't store attribute value: no persistence provider");
    1414              :     }
    1415              : }
    1416              : 
    1417              : // This function returns the actual function point from the array,
    1418              : // iterating over the function bits.
    1419         2944 : EmberAfGenericClusterFunction emberAfFindClusterFunction(const EmberAfCluster * cluster, EmberAfClusterMask functionMask)
    1420              : {
    1421         2944 :     EmberAfClusterMask mask = 0x01;
    1422         2944 :     uint8_t functionIndex   = 0;
    1423              : 
    1424         2944 :     if ((cluster->mask & functionMask) == 0)
    1425              :     {
    1426         2944 :         return nullptr;
    1427              :     }
    1428              : 
    1429            0 :     while (mask < functionMask)
    1430              :     {
    1431            0 :         if ((cluster->mask & mask) != 0)
    1432              :         {
    1433            0 :             functionIndex++;
    1434              :         }
    1435            0 :         mask = static_cast<EmberAfClusterMask>(mask << 1);
    1436              :     }
    1437            0 :     return cluster->functions[functionIndex];
    1438              : }
    1439              : 
    1440              : namespace chip {
    1441              : namespace app {
    1442              : 
    1443            0 : CHIP_ERROR SetParentEndpointForEndpoint(EndpointId childEndpoint, EndpointId parentEndpoint)
    1444              : {
    1445            0 :     uint16_t childIndex  = emberAfIndexFromEndpoint(childEndpoint);
    1446            0 :     uint16_t parentIndex = emberAfIndexFromEndpoint(parentEndpoint);
    1447              : 
    1448            0 :     if (childIndex == kEmberInvalidEndpointIndex || parentIndex == kEmberInvalidEndpointIndex)
    1449              :     {
    1450            0 :         return CHIP_ERROR_INVALID_ARGUMENT;
    1451              :     }
    1452            0 :     emAfEndpoints[childIndex].parentEndpointId = parentEndpoint;
    1453            0 :     return CHIP_NO_ERROR;
    1454              : }
    1455              : 
    1456            0 : CHIP_ERROR SetFlatCompositionForEndpoint(EndpointId endpoint)
    1457              : {
    1458            0 :     uint16_t index = emberAfIndexFromEndpoint(endpoint);
    1459            0 :     if (index == kEmberInvalidEndpointIndex)
    1460              :     {
    1461            0 :         return CHIP_ERROR_INVALID_ARGUMENT;
    1462              :     }
    1463            0 :     emAfEndpoints[index].bitmask.Set(EmberAfEndpointOptions::isFlatComposition);
    1464            0 :     return CHIP_NO_ERROR;
    1465              : }
    1466              : 
    1467            0 : CHIP_ERROR SetTreeCompositionForEndpoint(EndpointId endpoint)
    1468              : {
    1469            0 :     uint16_t index = emberAfIndexFromEndpoint(endpoint);
    1470            0 :     if (index == kEmberInvalidEndpointIndex)
    1471              :     {
    1472            0 :         return CHIP_ERROR_INVALID_ARGUMENT;
    1473              :     }
    1474            0 :     emAfEndpoints[index].bitmask.Clear(EmberAfEndpointOptions::isFlatComposition);
    1475            0 :     return CHIP_NO_ERROR;
    1476              : }
    1477              : 
    1478            0 : bool IsFlatCompositionForEndpoint(EndpointId endpoint)
    1479              : {
    1480            0 :     uint16_t index = emberAfIndexFromEndpoint(endpoint);
    1481            0 :     if (index == kEmberInvalidEndpointIndex)
    1482              :     {
    1483            0 :         return false;
    1484              :     }
    1485            0 :     return emAfEndpoints[index].bitmask.Has(EmberAfEndpointOptions::isFlatComposition);
    1486              : }
    1487              : 
    1488            0 : bool IsTreeCompositionForEndpoint(EndpointId endpoint)
    1489              : {
    1490            0 :     uint16_t index = emberAfIndexFromEndpoint(endpoint);
    1491            0 :     if (index == kEmberInvalidEndpointIndex)
    1492              :     {
    1493            0 :         return false;
    1494              :     }
    1495            0 :     return !emAfEndpoints[index].bitmask.Has(EmberAfEndpointOptions::isFlatComposition);
    1496              : }
    1497              : 
    1498         2917 : EndpointComposition GetCompositionForEndpointIndex(uint16_t endpointIndex)
    1499              : {
    1500         2917 :     VerifyOrReturnValue(endpointIndex < MATTER_ARRAY_SIZE(emAfEndpoints), EndpointComposition::kInvalid);
    1501         2917 :     if (emAfEndpoints[endpointIndex].bitmask.Has(EmberAfEndpointOptions::isFlatComposition))
    1502              :     {
    1503         1438 :         return EndpointComposition::kFullFamily;
    1504              :     }
    1505         1479 :     return EndpointComposition::kTree;
    1506              : }
    1507              : 
    1508              : } // namespace app
    1509              : } // namespace chip
    1510              : 
    1511            0 : uint16_t emberAfGetServerAttributeCount(EndpointId endpoint, ClusterId cluster)
    1512              : {
    1513            0 :     const EmberAfCluster * clusterObj = emberAfFindServerCluster(endpoint, cluster);
    1514            0 :     VerifyOrReturnError(clusterObj != nullptr, 0);
    1515            0 :     return clusterObj->attributeCount;
    1516              : }
    1517              : 
    1518            0 : uint16_t emberAfGetServerAttributeIndexByAttributeId(EndpointId endpoint, ClusterId cluster, AttributeId attributeId)
    1519              : {
    1520            0 :     const EmberAfCluster * clusterObj = emberAfFindServerCluster(endpoint, cluster);
    1521            0 :     VerifyOrReturnError(clusterObj != nullptr, UINT16_MAX);
    1522              : 
    1523            0 :     for (uint16_t i = 0; i < clusterObj->attributeCount; i++)
    1524              :     {
    1525            0 :         if (clusterObj->attributes[i].attributeId == attributeId)
    1526              :         {
    1527            0 :             return i;
    1528              :         }
    1529              :     }
    1530            0 :     return UINT16_MAX;
    1531              : }
    1532              : 
    1533            0 : Optional<AttributeId> emberAfGetServerAttributeIdByIndex(EndpointId endpoint, ClusterId cluster, uint16_t attributeIndex)
    1534              : {
    1535            0 :     const EmberAfCluster * clusterObj = emberAfFindServerCluster(endpoint, cluster);
    1536            0 :     if (clusterObj == nullptr || clusterObj->attributeCount <= attributeIndex)
    1537              :     {
    1538            0 :         return Optional<AttributeId>::Missing();
    1539              :     }
    1540            0 :     return Optional<AttributeId>(clusterObj->attributes[attributeIndex].attributeId);
    1541              : }
    1542              : 
    1543         9516 : DataVersion * emberAfDataVersionStorage(const ConcreteClusterPath & aConcreteClusterPath)
    1544              : {
    1545         9516 :     uint16_t index = emberAfIndexFromEndpoint(aConcreteClusterPath.mEndpointId);
    1546         9516 :     if (index == kEmberInvalidEndpointIndex)
    1547              :     {
    1548              :         // Unknown endpoint.
    1549           47 :         return nullptr;
    1550              :     }
    1551         9469 :     const EmberAfDefinedEndpoint & ep = emAfEndpoints[index];
    1552         9469 :     if (!ep.dataVersions)
    1553              :     {
    1554              :         // No storage provided.
    1555            0 :         return nullptr;
    1556              :     }
    1557              : 
    1558              :     // This does a second walk over endpoints to find the right one, but
    1559              :     // probably worth it to avoid duplicating code.
    1560              :     auto clusterIndex =
    1561         9469 :         emberAfClusterIndex(aConcreteClusterPath.mEndpointId, aConcreteClusterPath.mClusterId, MATTER_CLUSTER_FLAG_SERVER);
    1562         9469 :     if (clusterIndex == 0xFF)
    1563              :     {
    1564              :         // No such cluster on this endpoint.
    1565           10 :         return nullptr;
    1566              :     }
    1567              : 
    1568         9459 :     return ep.dataVersions + clusterIndex;
    1569              : }
    1570              : 
    1571              : namespace {
    1572              : class GlobalInteractionModelEngineChangedpathListener : public AttributesChangedListener
    1573              : {
    1574              : public:
    1575            6 :     ~GlobalInteractionModelEngineChangedpathListener() = default;
    1576              : 
    1577           86 :     void MarkDirty(const AttributePathParams & path) override
    1578              :     {
    1579           86 :         InteractionModelEngine::GetInstance()->GetReportingEngine().SetDirty(path);
    1580           86 :     }
    1581              : };
    1582              : 
    1583              : } // namespace
    1584              : 
    1585           86 : AttributesChangedListener * emberAfGlobalInteractionModelAttributesChangedListener()
    1586              : {
    1587           86 :     static GlobalInteractionModelEngineChangedpathListener listener;
    1588           86 :     return &listener;
    1589              : }
    1590              : 
    1591         5203 : void emberAfAttributeChanged(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId,
    1592              :                              AttributesChangedListener * listener)
    1593              : {
    1594              :     // Increase cluster data path
    1595         5203 :     DataVersion * version = emberAfDataVersionStorage(ConcreteClusterPath(endpoint, clusterId));
    1596         5203 :     if (version == nullptr)
    1597              :     {
    1598           57 :         ChipLogError(DataManagement, "Endpoint %x, Cluster " ChipLogFormatMEI " not found in IncreaseClusterDataVersion!", endpoint,
    1599              :                      ChipLogValueMEI(clusterId));
    1600              :     }
    1601              :     else
    1602              :     {
    1603         5146 :         (*(version))++;
    1604         5146 :         ChipLogDetail(DataManagement, "Endpoint %x, Cluster " ChipLogFormatMEI " update version to %" PRIx32, endpoint,
    1605              :                       ChipLogValueMEI(clusterId), *(version));
    1606              :     }
    1607              : 
    1608         5203 :     listener->MarkDirty(AttributePathParams(endpoint, clusterId, attributeId));
    1609         5203 : }
    1610              : 
    1611           29 : void emberAfEndpointChanged(EndpointId endpoint, AttributesChangedListener * listener)
    1612              : {
    1613           29 :     listener->MarkDirty(AttributePathParams(endpoint));
    1614           29 : }
        

Generated by: LCOV version 2.0-1