forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodegenDataModelProvider.cpp
857 lines (704 loc) · 31.5 KB
/
CodegenDataModelProvider.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
/*
* Copyright (c) 2024 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <app/codegen-data-model-provider/CodegenDataModelProvider.h>
#include <access/AccessControl.h>
#include <app-common/zap-generated/attribute-type.h>
#include <app/CommandHandlerInterface.h>
#include <app/CommandHandlerInterfaceRegistry.h>
#include <app/ConcreteClusterPath.h>
#include <app/ConcreteCommandPath.h>
#include <app/EventPathParams.h>
#include <app/RequiredPrivilege.h>
#include <app/data-model-provider/MetadataTypes.h>
#include <app/util/IMClusterCommandHandler.h>
#include <app/util/af-types.h>
#include <app/util/attribute-storage.h>
#include <app/util/endpoint-config-api.h>
#include <lib/core/CHIPError.h>
#include <lib/core/DataModelTypes.h>
// separated out for code-reuse
#include <app/ember_coupling/EventPathValidity.mixin.h>
#include <optional>
#include <variant>
namespace chip {
namespace app {
namespace {
/// Handles going through callback-based enumeration of generated/accepted commands
/// for CommandHandlerInterface based items.
///
/// Offers the ability to focus on some operation for finding a given
/// command id:
/// - FindFirst will return the first found element
/// - FindExact finds the element with the given id
/// - FindNext finds the element following the given id
class EnumeratorCommandFinder
{
public:
using HandlerCallbackFunction = CHIP_ERROR (CommandHandlerInterface::*)(const ConcreteClusterPath &,
CommandHandlerInterface::CommandIdCallback, void *);
enum class Operation
{
kFindFirst, // Find the first value in the list
kFindExact, // Find the given value
kFindNext // Find the value AFTER this value
};
EnumeratorCommandFinder(HandlerCallbackFunction callback) :
mCallback(callback), mOperation(Operation::kFindFirst), mTarget(kInvalidCommandId)
{}
/// Find the given command ID that matches the given operation/path.
///
/// If operation is kFindFirst, then path commandID is ignored. Otherwise it is used as a key to
/// kFindExact or kFindNext.
///
/// Returns:
/// - std::nullopt if no command found using the command handler interface
/// - kInvalidCommandId if the find failed (but command handler interface does provide a list)
/// - valid id if command handler interface usage succeeds
std::optional<CommandId> FindCommandId(Operation operation, const ConcreteCommandPath & path);
/// Uses FindCommandId to find the given command and loads the command entry data
std::optional<DataModel::CommandEntry> FindCommandEntry(Operation operation, const ConcreteCommandPath & path);
private:
HandlerCallbackFunction mCallback;
Operation mOperation;
CommandId mTarget;
std::optional<CommandId> mFound = std::nullopt;
Loop HandlerCallback(CommandId id)
{
switch (mOperation)
{
case Operation::kFindFirst:
mFound = id;
return Loop::Break;
case Operation::kFindExact:
if (mTarget == id)
{
mFound = id; // found it
return Loop::Break;
}
break;
case Operation::kFindNext:
if (mTarget == id)
{
// Once we found the ID, get the first
mOperation = Operation::kFindFirst;
}
break;
}
return Loop::Continue; // keep searching
}
static Loop HandlerCallbackFn(CommandId id, void * context)
{
auto self = static_cast<EnumeratorCommandFinder *>(context);
return self->HandlerCallback(id);
}
};
std::optional<CommandId> EnumeratorCommandFinder::FindCommandId(Operation operation, const ConcreteCommandPath & path)
{
mOperation = operation;
mTarget = path.mCommandId;
CommandHandlerInterface * interface =
CommandHandlerInterfaceRegistry::Instance().GetCommandHandler(path.mEndpointId, path.mClusterId);
if (interface == nullptr)
{
return std::nullopt; // no data: no interface
}
CHIP_ERROR err = (interface->*mCallback)(path, HandlerCallbackFn, this);
if (err == CHIP_ERROR_NOT_IMPLEMENTED)
{
return std::nullopt; // no data provided by the interface
}
if (err != CHIP_NO_ERROR)
{
// Report the error here since we lose actual error. This generally should NOT be possible as CommandHandlerInterface
// usually returns unimplemented or should just work for our use case (our callback never fails)
ChipLogError(DataManagement, "Enumerate error: %" CHIP_ERROR_FORMAT, err.Format());
return kInvalidCommandId;
}
return mFound.value_or(kInvalidCommandId);
}
/// Load the cluster information into the specified destination
std::variant<CHIP_ERROR, DataModel::ClusterInfo> LoadClusterInfo(const ConcreteClusterPath & path, const EmberAfCluster & cluster)
{
DataVersion * versionPtr = emberAfDataVersionStorage(path);
if (versionPtr == nullptr)
{
ChipLogError(AppServer, "Failed to get data version for %d/" ChipLogFormatMEI, static_cast<int>(path.mEndpointId),
ChipLogValueMEI(cluster.clusterId));
return CHIP_ERROR_NOT_FOUND;
}
DataModel::ClusterInfo info(*versionPtr);
// TODO: set entry flags:
// info->flags.Set(ClusterQualityFlags::kDiagnosticsData)
return info;
}
/// Converts a EmberAfCluster into a ClusterEntry
std::variant<CHIP_ERROR, DataModel::ClusterEntry> ClusterEntryFrom(EndpointId endpointId, const EmberAfCluster & cluster)
{
ConcreteClusterPath clusterPath(endpointId, cluster.clusterId);
auto info = LoadClusterInfo(clusterPath, cluster);
if (CHIP_ERROR * err = std::get_if<CHIP_ERROR>(&info))
{
return *err;
}
if (DataModel::ClusterInfo * infoValue = std::get_if<DataModel::ClusterInfo>(&info))
{
return DataModel::ClusterEntry{
.path = clusterPath,
.info = *infoValue,
};
}
return CHIP_ERROR_INCORRECT_STATE;
}
/// Finds the first server cluster entry for the given endpoint data starting at [start_index]
///
/// Returns an invalid entry if no more server clusters are found
DataModel::ClusterEntry FirstServerClusterEntry(EndpointId endpointId, const EmberAfEndpointType * endpoint, unsigned start_index,
unsigned & found_index)
{
for (unsigned cluster_idx = start_index; cluster_idx < endpoint->clusterCount; cluster_idx++)
{
const EmberAfCluster & cluster = endpoint->cluster[cluster_idx];
if (!cluster.IsServer())
{
continue;
}
found_index = cluster_idx;
auto entry = ClusterEntryFrom(endpointId, cluster);
if (DataModel::ClusterEntry * entryValue = std::get_if<DataModel::ClusterEntry>(&entry))
{
return *entryValue;
}
#if CHIP_ERROR_LOGGING
if (CHIP_ERROR * errValue = std::get_if<CHIP_ERROR>(&entry))
{
ChipLogError(AppServer, "Failed to load cluster entry: %" CHIP_ERROR_FORMAT, errValue->Format());
}
else
{
// Should NOT be possible: entryFrom has only 2 variants
ChipLogError(AppServer, "Failed to load cluster entry, UNKNOWN entry return type");
}
#endif
}
return DataModel::ClusterEntry::kInvalid;
}
/// Load the attribute information into the specified destination
///
/// `info` is assumed to be default-constructed/clear (i.e. this sets flags, but does not reset them).
void LoadAttributeInfo(const ConcreteAttributePath & path, const EmberAfAttributeMetadata & attribute,
DataModel::AttributeInfo * info)
{
info->readPrivilege = RequiredPrivilege::ForReadAttribute(path);
if (!attribute.IsReadOnly())
{
info->writePrivilege = RequiredPrivilege::ForWriteAttribute(path);
}
info->flags.Set(DataModel::AttributeQualityFlags::kListAttribute, (attribute.attributeType == ZCL_ARRAY_ATTRIBUTE_TYPE));
info->flags.Set(DataModel::AttributeQualityFlags::kTimed, attribute.MustUseTimedWrite());
// NOTE: we do NOT provide additional info for:
// - IsExternal/IsSingleton/IsAutomaticallyPersisted is not used by IM handling
// - IsSingleton spec defines it for CLUSTERS where as we have it for ATTRIBUTES
// - Several specification flags are not available (reportable, quieter reporting,
// fixed, source attribution)
// TODO: Set additional flags:
// info->flags.Set(DataModel::AttributeQualityFlags::kFabricScoped)
// info->flags.Set(DataModel::AttributeQualityFlags::kFabricSensitive)
// info->flags.Set(DataModel::AttributeQualityFlags::kChangesOmitted)
}
DataModel::AttributeEntry AttributeEntryFrom(const ConcreteClusterPath & clusterPath, const EmberAfAttributeMetadata & attribute)
{
DataModel::AttributeEntry entry;
entry.path = ConcreteAttributePath(clusterPath.mEndpointId, clusterPath.mClusterId, attribute.attributeId);
LoadAttributeInfo(entry.path, attribute, &entry.info);
return entry;
}
DataModel::CommandEntry CommandEntryFrom(const ConcreteClusterPath & clusterPath, CommandId clusterCommandId)
{
DataModel::CommandEntry entry;
entry.path = ConcreteCommandPath(clusterPath.mEndpointId, clusterPath.mClusterId, clusterCommandId);
entry.info.invokePrivilege = RequiredPrivilege::ForInvokeCommand(entry.path);
entry.info.flags.Set(DataModel::CommandQualityFlags::kTimed, CommandNeedsTimedInvoke(clusterPath.mClusterId, clusterCommandId));
entry.info.flags.Set(DataModel::CommandQualityFlags::kFabricScoped,
CommandIsFabricScoped(clusterPath.mClusterId, clusterCommandId));
return entry;
}
std::optional<DataModel::CommandEntry> EnumeratorCommandFinder::FindCommandEntry(Operation operation,
const ConcreteCommandPath & path)
{
std::optional<CommandId> id = FindCommandId(operation, path);
if (!id.has_value())
{
return std::nullopt;
}
return (*id == kInvalidCommandId) ? DataModel::CommandEntry::kInvalid : CommandEntryFrom(path, *id);
}
// TODO: DeviceTypeEntry content is IDENTICAL to EmberAfDeviceType, so centralizing
// to a common type is probably better. Need to figure out dependencies since
// this would make ember return datamodel-provider types.
DataModel::DeviceTypeEntry DeviceTypeEntryFromEmber(const EmberAfDeviceType & other)
{
DataModel::DeviceTypeEntry entry;
entry.deviceTypeId = other.deviceId;
entry.deviceTypeVersion = other.deviceVersion;
return entry;
}
// Explicitly compare for identical entries. note that types are different,
// so you must do `a == b` and the `b == a` will not work.
bool operator==(const DataModel::DeviceTypeEntry & a, const EmberAfDeviceType & b)
{
return (a.deviceTypeId == b.deviceId) && (a.deviceTypeVersion == b.deviceVersion);
}
/// Find the `index` where one of the following holds:
/// - types[index - 1] == previous OR
/// - index == types.size() // i.e. not found or there is no next
///
/// hintWherePreviousMayBe represents a search hint where previous may exist.
unsigned FindNextDeviceTypeIndex(Span<const EmberAfDeviceType> types, const DataModel::DeviceTypeEntry previous,
unsigned hintWherePreviousMayBe)
{
if (hintWherePreviousMayBe < types.size())
{
// this is a valid hint ... see if we are lucky
if (previous == types[hintWherePreviousMayBe])
{
return hintWherePreviousMayBe + 1; // return the next index
}
}
// hint was not useful. We have to do a full search
for (unsigned idx = 0; idx < types.size(); idx++)
{
if (previous == types[idx])
{
return idx + 1;
}
}
// cast should be safe as we know we do not have that many types
return static_cast<unsigned>(types.size());
}
const ConcreteCommandPath kInvalidCommandPath(kInvalidEndpointId, kInvalidClusterId, kInvalidCommandId);
} // namespace
std::optional<CommandId> CodegenDataModelProvider::EmberCommandListIterator::First(const CommandId * list)
{
VerifyOrReturnValue(list != nullptr, std::nullopt);
mCurrentList = mCurrentHint = list;
VerifyOrReturnValue(*mCurrentList != kInvalidCommandId, std::nullopt);
return *mCurrentList;
}
std::optional<CommandId> CodegenDataModelProvider::EmberCommandListIterator::Next(const CommandId * list, CommandId previousId)
{
VerifyOrReturnValue(list != nullptr, std::nullopt);
VerifyOrReturnValue(previousId != kInvalidCommandId, std::nullopt);
if (mCurrentList != list)
{
// invalidate the hint if switching lists...
mCurrentHint = nullptr;
mCurrentList = list;
}
if ((mCurrentHint == nullptr) || (*mCurrentHint != previousId))
{
// we did not find a usable hint. Search from the to set the hint
mCurrentHint = mCurrentList;
while ((*mCurrentHint != kInvalidCommandId) && (*mCurrentHint != previousId))
{
mCurrentHint++;
}
}
VerifyOrReturnValue(*mCurrentHint == previousId, std::nullopt);
// hint is valid and can be used immediately
mCurrentHint++; // this is the next value
return (*mCurrentHint == kInvalidCommandId) ? std::nullopt : std::make_optional(*mCurrentHint);
}
bool CodegenDataModelProvider::EmberCommandListIterator::Exists(const CommandId * list, CommandId toCheck)
{
VerifyOrReturnValue(list != nullptr, false);
VerifyOrReturnValue(toCheck != kInvalidCommandId, false);
if (mCurrentList != list)
{
// invalidate the hint if switching lists...
mCurrentHint = nullptr;
mCurrentList = list;
}
// maybe already positioned correctly
if ((mCurrentHint != nullptr) && (*mCurrentHint == toCheck))
{
return true;
}
// move and try to find it
mCurrentHint = mCurrentList;
while ((*mCurrentHint != kInvalidCommandId) && (*mCurrentHint != toCheck))
{
mCurrentHint++;
}
return (*mCurrentHint == toCheck);
}
std::optional<DataModel::ActionReturnStatus> CodegenDataModelProvider::Invoke(const DataModel::InvokeRequest & request,
TLV::TLVReader & input_arguments,
CommandHandler * handler)
{
CommandHandlerInterface * handler_interface =
CommandHandlerInterfaceRegistry::Instance().GetCommandHandler(request.path.mEndpointId, request.path.mClusterId);
if (handler_interface)
{
CommandHandlerInterface::HandlerContext context(*handler, request.path, input_arguments);
handler_interface->InvokeCommand(context);
// If the command was handled, don't proceed any further and return successfully.
if (context.mCommandHandled)
{
return std::nullopt;
}
}
// Ember always sets the return in the handler
DispatchSingleClusterCommand(request.path, input_arguments, handler);
return std::nullopt;
}
EndpointId CodegenDataModelProvider::FirstEndpoint()
{
// find the first enabled index
const uint16_t lastEndpointIndex = emberAfEndpointCount();
for (uint16_t endpoint_idx = 0; endpoint_idx < lastEndpointIndex; endpoint_idx++)
{
if (emberAfEndpointIndexIsEnabled(endpoint_idx))
{
mEndpointIterationHint = endpoint_idx;
return emberAfEndpointFromIndex(endpoint_idx);
}
}
// No enabled endpoint found. Give up
return kInvalidEndpointId;
}
std::optional<unsigned> CodegenDataModelProvider::TryFindEndpointIndex(EndpointId id) const
{
const uint16_t lastEndpointIndex = emberAfEndpointCount();
if ((mEndpointIterationHint < lastEndpointIndex) && emberAfEndpointIndexIsEnabled(mEndpointIterationHint) &&
(id == emberAfEndpointFromIndex(mEndpointIterationHint)))
{
return std::make_optional(mEndpointIterationHint);
}
// Linear search, this may be slow
uint16_t idx = emberAfIndexFromEndpoint(id);
if (idx == kEmberInvalidEndpointIndex)
{
return std::nullopt;
}
return std::make_optional<unsigned>(idx);
}
EndpointId CodegenDataModelProvider::NextEndpoint(EndpointId before)
{
const uint16_t lastEndpointIndex = emberAfEndpointCount();
std::optional<unsigned> before_idx = TryFindEndpointIndex(before);
if (!before_idx.has_value())
{
return kInvalidEndpointId;
}
// find the first enabled index
for (uint16_t endpoint_idx = static_cast<uint16_t>(*before_idx + 1); endpoint_idx < lastEndpointIndex; endpoint_idx++)
{
if (emberAfEndpointIndexIsEnabled(endpoint_idx))
{
mEndpointIterationHint = endpoint_idx;
return emberAfEndpointFromIndex(endpoint_idx);
}
}
// No enabled enpoint after "before" was found, give up
return kInvalidEndpointId;
}
DataModel::ClusterEntry CodegenDataModelProvider::FirstCluster(EndpointId endpointId)
{
const EmberAfEndpointType * endpoint = emberAfFindEndpointType(endpointId);
VerifyOrReturnValue(endpoint != nullptr, DataModel::ClusterEntry::kInvalid);
VerifyOrReturnValue(endpoint->clusterCount > 0, DataModel::ClusterEntry::kInvalid);
VerifyOrReturnValue(endpoint->cluster != nullptr, DataModel::ClusterEntry::kInvalid);
return FirstServerClusterEntry(endpointId, endpoint, 0, mClusterIterationHint);
}
std::optional<unsigned> CodegenDataModelProvider::TryFindServerClusterIndex(const EmberAfEndpointType * endpoint,
ClusterId id) const
{
const unsigned clusterCount = endpoint->clusterCount;
if (mClusterIterationHint < clusterCount)
{
const EmberAfCluster & cluster = endpoint->cluster[mClusterIterationHint];
if (cluster.IsServer() && (cluster.clusterId == id))
{
return std::make_optional(mClusterIterationHint);
}
}
// linear search, this may be slow
// does NOT use emberAfClusterIndex to not iterate over endpoints as we have
// already found the correct endpoint
for (unsigned cluster_idx = 0; cluster_idx < clusterCount; cluster_idx++)
{
const EmberAfCluster & cluster = endpoint->cluster[cluster_idx];
if (cluster.IsServer() && (cluster.clusterId == id))
{
return std::make_optional(cluster_idx);
}
}
return std::nullopt;
}
DataModel::ClusterEntry CodegenDataModelProvider::NextCluster(const ConcreteClusterPath & before)
{
// TODO: This search still seems slow (ember will loop). Should use index hints as long
// as ember API supports it
const EmberAfEndpointType * endpoint = emberAfFindEndpointType(before.mEndpointId);
VerifyOrReturnValue(endpoint != nullptr, DataModel::ClusterEntry::kInvalid);
VerifyOrReturnValue(endpoint->clusterCount > 0, DataModel::ClusterEntry::kInvalid);
VerifyOrReturnValue(endpoint->cluster != nullptr, DataModel::ClusterEntry::kInvalid);
std::optional<unsigned> cluster_idx = TryFindServerClusterIndex(endpoint, before.mClusterId);
if (!cluster_idx.has_value())
{
return DataModel::ClusterEntry::kInvalid;
}
return FirstServerClusterEntry(before.mEndpointId, endpoint, *cluster_idx + 1, mClusterIterationHint);
}
std::optional<DataModel::ClusterInfo> CodegenDataModelProvider::GetClusterInfo(const ConcreteClusterPath & path)
{
const EmberAfCluster * cluster = FindServerCluster(path);
VerifyOrReturnValue(cluster != nullptr, std::nullopt);
auto info = LoadClusterInfo(path, *cluster);
if (CHIP_ERROR * err = std::get_if<CHIP_ERROR>(&info))
{
#if CHIP_ERROR_LOGGING
ChipLogError(AppServer, "Failed to load cluster info: %" CHIP_ERROR_FORMAT, err->Format());
#else
(void) err->Format();
#endif
return std::nullopt;
}
return std::make_optional(std::get<DataModel::ClusterInfo>(info));
}
DataModel::AttributeEntry CodegenDataModelProvider::FirstAttribute(const ConcreteClusterPath & path)
{
const EmberAfCluster * cluster = FindServerCluster(path);
VerifyOrReturnValue(cluster != nullptr, DataModel::AttributeEntry::kInvalid);
VerifyOrReturnValue(cluster->attributeCount > 0, DataModel::AttributeEntry::kInvalid);
VerifyOrReturnValue(cluster->attributes != nullptr, DataModel::AttributeEntry::kInvalid);
mAttributeIterationHint = 0;
return AttributeEntryFrom(path, cluster->attributes[0]);
}
std::optional<unsigned> CodegenDataModelProvider::TryFindAttributeIndex(const EmberAfCluster * cluster, AttributeId id) const
{
const unsigned attributeCount = cluster->attributeCount;
// attempt to find this based on the embedded hint
if ((mAttributeIterationHint < attributeCount) && (cluster->attributes[mAttributeIterationHint].attributeId == id))
{
return std::make_optional(mAttributeIterationHint);
}
// linear search is required. This may be slow
for (unsigned attribute_idx = 0; attribute_idx < attributeCount; attribute_idx++)
{
if (cluster->attributes[attribute_idx].attributeId == id)
{
return std::make_optional(attribute_idx);
}
}
return std::nullopt;
}
const EmberAfCluster * CodegenDataModelProvider::FindServerCluster(const ConcreteClusterPath & path)
{
// cache things
if (mPreviouslyFoundCluster.has_value() && (mPreviouslyFoundCluster->path == path))
{
return mPreviouslyFoundCluster->cluster;
}
const EmberAfCluster * cluster = emberAfFindServerCluster(path.mEndpointId, path.mClusterId);
if (cluster != nullptr)
{
mPreviouslyFoundCluster = std::make_optional<ClusterReference>(path, cluster);
}
return cluster;
}
DataModel::AttributeEntry CodegenDataModelProvider::NextAttribute(const ConcreteAttributePath & before)
{
const EmberAfCluster * cluster = FindServerCluster(before);
VerifyOrReturnValue(cluster != nullptr, DataModel::AttributeEntry::kInvalid);
VerifyOrReturnValue(cluster->attributeCount > 0, DataModel::AttributeEntry::kInvalid);
VerifyOrReturnValue(cluster->attributes != nullptr, DataModel::AttributeEntry::kInvalid);
// find the given attribute in the list and then return the next one
std::optional<unsigned> attribute_idx = TryFindAttributeIndex(cluster, before.mAttributeId);
if (!attribute_idx.has_value())
{
return DataModel::AttributeEntry::kInvalid;
}
unsigned next_idx = *attribute_idx + 1;
if (next_idx < cluster->attributeCount)
{
mAttributeIterationHint = next_idx;
return AttributeEntryFrom(before, cluster->attributes[next_idx]);
}
// iteration complete
return DataModel::AttributeEntry::kInvalid;
}
std::optional<DataModel::AttributeInfo> CodegenDataModelProvider::GetAttributeInfo(const ConcreteAttributePath & path)
{
const EmberAfCluster * cluster = FindServerCluster(path);
VerifyOrReturnValue(cluster != nullptr, std::nullopt);
VerifyOrReturnValue(cluster->attributeCount > 0, std::nullopt);
VerifyOrReturnValue(cluster->attributes != nullptr, std::nullopt);
std::optional<unsigned> attribute_idx = TryFindAttributeIndex(cluster, path.mAttributeId);
if (!attribute_idx.has_value())
{
return std::nullopt;
}
DataModel::AttributeInfo info;
LoadAttributeInfo(path, cluster->attributes[*attribute_idx], &info);
return std::make_optional(info);
}
DataModel::CommandEntry CodegenDataModelProvider::FirstAcceptedCommand(const ConcreteClusterPath & path)
{
auto handlerInterfaceValue = EnumeratorCommandFinder(&CommandHandlerInterface::EnumerateAcceptedCommands)
.FindCommandEntry(EnumeratorCommandFinder::Operation::kFindFirst,
ConcreteCommandPath(path.mEndpointId, path.mClusterId, kInvalidCommandId));
if (handlerInterfaceValue.has_value())
{
return *handlerInterfaceValue;
}
const EmberAfCluster * cluster = FindServerCluster(path);
VerifyOrReturnValue(cluster != nullptr, DataModel::CommandEntry::kInvalid);
std::optional<CommandId> commandId = mAcceptedCommandsIterator.First(cluster->acceptedCommandList);
VerifyOrReturnValue(commandId.has_value(), DataModel::CommandEntry::kInvalid);
return CommandEntryFrom(path, *commandId);
}
DataModel::CommandEntry CodegenDataModelProvider::NextAcceptedCommand(const ConcreteCommandPath & before)
{
// TODO: `Next` redirecting to a callback is slow O(n^2).
// see https://github.com/project-chip/connectedhomeip/issues/35790
auto handlerInterfaceValue = EnumeratorCommandFinder(&CommandHandlerInterface::EnumerateAcceptedCommands)
.FindCommandEntry(EnumeratorCommandFinder::Operation::kFindNext, before);
if (handlerInterfaceValue.has_value())
{
return *handlerInterfaceValue;
}
const EmberAfCluster * cluster = FindServerCluster(before);
VerifyOrReturnValue(cluster != nullptr, DataModel::CommandEntry::kInvalid);
std::optional<CommandId> commandId = mAcceptedCommandsIterator.Next(cluster->acceptedCommandList, before.mCommandId);
VerifyOrReturnValue(commandId.has_value(), DataModel::CommandEntry::kInvalid);
return CommandEntryFrom(before, *commandId);
}
std::optional<DataModel::CommandInfo> CodegenDataModelProvider::GetAcceptedCommandInfo(const ConcreteCommandPath & path)
{
auto handlerInterfaceValue = EnumeratorCommandFinder(&CommandHandlerInterface::EnumerateAcceptedCommands)
.FindCommandEntry(EnumeratorCommandFinder::Operation::kFindExact, path);
if (handlerInterfaceValue.has_value())
{
return handlerInterfaceValue->IsValid() ? std::make_optional(handlerInterfaceValue->info) : std::nullopt;
}
const EmberAfCluster * cluster = FindServerCluster(path);
VerifyOrReturnValue(cluster != nullptr, std::nullopt);
VerifyOrReturnValue(mAcceptedCommandsIterator.Exists(cluster->acceptedCommandList, path.mCommandId), std::nullopt);
return CommandEntryFrom(path, path.mCommandId).info;
}
ConcreteCommandPath CodegenDataModelProvider::FirstGeneratedCommand(const ConcreteClusterPath & path)
{
std::optional<CommandId> commandId =
EnumeratorCommandFinder(&CommandHandlerInterface::EnumerateGeneratedCommands)
.FindCommandId(EnumeratorCommandFinder::Operation::kFindFirst,
ConcreteCommandPath(path.mEndpointId, path.mClusterId, kInvalidCommandId));
if (commandId.has_value())
{
return *commandId == kInvalidCommandId ? kInvalidCommandPath
: ConcreteCommandPath(path.mEndpointId, path.mClusterId, *commandId);
}
const EmberAfCluster * cluster = FindServerCluster(path);
VerifyOrReturnValue(cluster != nullptr, kInvalidCommandPath);
commandId = mGeneratedCommandsIterator.First(cluster->generatedCommandList);
VerifyOrReturnValue(commandId.has_value(), kInvalidCommandPath);
return ConcreteCommandPath(path.mEndpointId, path.mClusterId, *commandId);
}
ConcreteCommandPath CodegenDataModelProvider::NextGeneratedCommand(const ConcreteCommandPath & before)
{
// TODO: `Next` redirecting to a callback is slow O(n^2).
// see https://github.com/project-chip/connectedhomeip/issues/35790
auto nextId = EnumeratorCommandFinder(&CommandHandlerInterface::EnumerateGeneratedCommands)
.FindCommandId(EnumeratorCommandFinder::Operation::kFindNext, before);
if (nextId.has_value())
{
return (*nextId == kInvalidCommandId) ? kInvalidCommandPath
: ConcreteCommandPath(before.mEndpointId, before.mClusterId, *nextId);
}
const EmberAfCluster * cluster = FindServerCluster(before);
VerifyOrReturnValue(cluster != nullptr, kInvalidCommandPath);
std::optional<CommandId> commandId = mGeneratedCommandsIterator.Next(cluster->generatedCommandList, before.mCommandId);
VerifyOrReturnValue(commandId.has_value(), kInvalidCommandPath);
return ConcreteCommandPath(before.mEndpointId, before.mClusterId, *commandId);
}
std::optional<DataModel::DeviceTypeEntry> CodegenDataModelProvider::FirstDeviceType(EndpointId endpoint)
{
// Use the `Index` version even though `emberAfDeviceTypeListFromEndpoint` would work because
// index finding is cached in TryFindEndpointIndex and this avoids an extra `emberAfIndexFromEndpoint`
// during `Next` loops. This avoids O(n^2) on number of indexes when iterating over all device types.
//
// Not actually needed for `First`, however this makes First and Next consistent.
std::optional<unsigned> endpoint_index = TryFindEndpointIndex(endpoint);
if (!endpoint_index.has_value())
{
return std::nullopt;
}
CHIP_ERROR err = CHIP_NO_ERROR;
Span<const EmberAfDeviceType> deviceTypes = emberAfDeviceTypeListFromEndpointIndex(*endpoint_index, err);
if (deviceTypes.empty())
{
return std::nullopt;
}
// we start at the beginning
mDeviceTypeIterationHint = 0;
return DeviceTypeEntryFromEmber(deviceTypes[0]);
}
std::optional<DataModel::DeviceTypeEntry> CodegenDataModelProvider::NextDeviceType(EndpointId endpoint,
const DataModel::DeviceTypeEntry & previous)
{
// Use the `Index` version even though `emberAfDeviceTypeListFromEndpoint` would work because
// index finding is cached in TryFindEndpointIndex and this avoids an extra `emberAfIndexFromEndpoint`
// during `Next` loops. This avoids O(n^2) on number of indexes when iterating over all device types.
std::optional<unsigned> endpoint_index = TryFindEndpointIndex(endpoint);
if (!endpoint_index.has_value())
{
return std::nullopt;
}
CHIP_ERROR err = CHIP_NO_ERROR;
Span<const EmberAfDeviceType> deviceTypes = emberAfDeviceTypeListFromEndpointIndex(*endpoint_index, err);
unsigned idx = FindNextDeviceTypeIndex(deviceTypes, previous, mDeviceTypeIterationHint);
if (idx >= deviceTypes.size())
{
return std::nullopt;
}
mDeviceTypeIterationHint = idx;
return DeviceTypeEntryFromEmber(deviceTypes[idx]);
}
bool CodegenDataModelProvider::EventPathIncludesAccessibleConcretePath(const EventPathParams & path,
const Access::SubjectDescriptor & descriptor)
{
if (!path.HasWildcardEndpointId())
{
// No need to check whether the endpoint is enabled, because
// emberAfFindEndpointType returns null for disabled endpoints.
return HasValidEventPathForEndpoint(path.mEndpointId, path, descriptor);
}
for (uint16_t endpointIndex = 0; endpointIndex < emberAfEndpointCount(); ++endpointIndex)
{
if (!emberAfEndpointIndexIsEnabled(endpointIndex))
{
continue;
}
if (HasValidEventPathForEndpoint(emberAfEndpointFromIndex(endpointIndex), path, descriptor))
{
return true;
}
}
return false;
}
} // namespace app
} // namespace chip