forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMTRBaseDevice.mm
3200 lines (2803 loc) · 135 KB
/
MTRBaseDevice.mm
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
* Copyright (c) 2020-2023 Project CHIP Authors
*
* 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.
*/
#import <Matter/MTRClusterConstants.h>
#import <Matter/MTRDefines.h>
#import "MTRAttributeTLVValueDecoder_Internal.h"
#import "MTRBaseDevice_Internal.h"
#import "MTRBaseSubscriptionCallback.h"
#import "MTRCallbackBridgeBase.h"
#import "MTRCluster.h"
#import "MTRClusterStateCacheContainer_Internal.h"
#import "MTRCluster_Internal.h"
#import "MTRDevice_Internal.h"
#import "MTRError_Internal.h"
#import "MTREventTLVValueDecoder_Internal.h"
#import "MTRFramework.h"
#import "MTRLogging_Internal.h"
#import "MTRMetricKeys.h"
#import "MTRSetupPayload_Internal.h"
#import "NSDataSpanConversion.h"
#import "NSStringSpanConversion.h"
#import "zap-generated/MTRCommandPayloads_Internal.h"
#include "app/ConcreteAttributePath.h"
#include "app/ConcreteCommandPath.h"
#include "app/ConcreteEventPath.h"
#include "app/StatusResponse.h"
#include "lib/core/CHIPError.h"
#include "lib/core/DataModelTypes.h"
#include <app/AttributePathParams.h>
#include <app/BufferedReadCallback.h>
#include <app/ClusterStateCache.h>
#include <app/InteractionModelEngine.h>
#include <app/ReadClient.h>
#include <app/data-model/List.h>
#include <controller/CommissioningWindowOpener.h>
#include <controller/ReadInteraction.h>
#include <controller/WriteInteraction.h>
#include <crypto/CHIPCryptoPAL.h>
#include <setup_payload/SetupPayload.h>
#include <system/SystemClock.h>
#include <memory>
using namespace chip;
using namespace chip::app;
using namespace chip::Protocols::InteractionModel;
using chip::Optional;
using chip::SessionHandle;
using chip::Messaging::ExchangeManager;
using namespace chip::Tracing::DarwinFramework;
NSString * const MTRAttributePathKey = @"attributePath";
NSString * const MTRCommandPathKey = @"commandPath";
NSString * const MTREventPathKey = @"eventPath";
NSString * const MTRDataKey = @"data";
NSString * const MTRErrorKey = @"error";
NSString * const MTRTypeKey = @"type";
NSString * const MTRValueKey = @"value";
NSString * const MTRContextTagKey = @"contextTag";
NSString * const MTRSignedIntegerValueType = @"SignedInteger";
NSString * const MTRUnsignedIntegerValueType = @"UnsignedInteger";
NSString * const MTRBooleanValueType = @"Boolean";
NSString * const MTRUTF8StringValueType = @"UTF8String";
NSString * const MTROctetStringValueType = @"OctetString";
NSString * const MTRFloatValueType = @"Float";
NSString * const MTRDoubleValueType = @"Double";
NSString * const MTRNullValueType = @"Null";
NSString * const MTRStructureValueType = @"Structure";
NSString * const MTRArrayValueType = @"Array";
NSString * const MTREventNumberKey = @"eventNumber";
NSString * const MTREventPriorityKey = @"eventPriority";
NSString * const MTREventTimeTypeKey = @"eventTimeType";
NSString * const MTREventSystemUpTimeKey = @"eventSystemUpTime";
NSString * const MTREventTimestampDateKey = @"eventTimestampDate";
NSString * const MTREventIsHistoricalKey = @"eventIsHistorical";
class MTRDataValueDictionaryCallbackBridge;
class MTRDataValueDictionaryDecodableType;
template <typename DecodableValueType>
class BufferedReadClientCallback;
@interface MTRReadClientContainer : NSObject
@property (nonatomic, readwrite) app::ReadClient * readClientPtr;
@property (nonatomic, readwrite) BufferedReadClientCallback<MTRDataValueDictionaryDecodableType> * callback;
@property (nonatomic, readwrite) app::AttributePathParams * pathParams;
@property (nonatomic, readwrite) app::EventPathParams * eventPathParams;
@property (nonatomic, readwrite) uint64_t deviceID;
- (void)cleanup;
- (void)onDone;
@end
static NSMutableDictionary<NSNumber *, NSMutableArray<MTRReadClientContainer *> *> * readClientContainers;
static NSLock * readClientContainersLock;
static void InitializeReadClientContainers()
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
readClientContainers = [NSMutableDictionary dictionary];
readClientContainersLock = [[NSLock alloc] init];
});
}
static void AddReadClientContainer(uint64_t deviceId, MTRReadClientContainer * container)
{
InitializeReadClientContainers();
NSNumber * key = [NSNumber numberWithUnsignedLongLong:deviceId];
[readClientContainersLock lock];
if (!readClientContainers[key]) {
readClientContainers[key] = [NSMutableArray array];
}
[readClientContainers[key] addObject:container];
[readClientContainersLock unlock];
}
static void ReinstateReadClientList(NSMutableArray<MTRReadClientContainer *> * readClientList, NSNumber * key,
dispatch_queue_t queue, dispatch_block_t _Nullable completion)
{
[readClientContainersLock lock];
auto existingList = readClientContainers[key];
if (existingList) {
[existingList addObjectsFromArray:readClientList];
} else {
readClientContainers[key] = readClientList;
}
[readClientContainersLock unlock];
if (completion) {
dispatch_async(queue, completion);
}
}
static void PurgeReadClientContainers(
MTRDeviceController * controller, uint64_t deviceId, dispatch_queue_t queue, void (^_Nullable completion)(void))
{
InitializeReadClientContainers();
NSMutableArray<MTRReadClientContainer *> * listToDelete;
NSNumber * key = [NSNumber numberWithUnsignedLongLong:deviceId];
[readClientContainersLock lock];
listToDelete = readClientContainers[key];
[readClientContainers removeObjectForKey:key];
[readClientContainersLock unlock];
// Destroy read clients in the work queue
[controller
asyncDispatchToMatterQueue:^() {
for (MTRReadClientContainer * container in listToDelete) {
[container cleanup];
}
[listToDelete removeAllObjects];
if (completion) {
dispatch_async(queue, completion);
}
}
errorHandler:^(NSError * error) {
// Can't delete things. Just put them back, and hope we
// can delete them later.
ReinstateReadClientList(listToDelete, key, queue, completion);
}];
}
static void PurgeCompletedReadClientContainers(uint64_t deviceId)
{
InitializeReadClientContainers();
NSNumber * key = [NSNumber numberWithUnsignedLongLong:deviceId];
[readClientContainersLock lock];
NSMutableArray<MTRReadClientContainer *> * array = readClientContainers[key];
NSUInteger i = 0;
while (i < [array count]) {
if (array[i].readClientPtr == nullptr) {
[array removeObjectAtIndex:i];
continue;
}
i++;
}
[readClientContainersLock unlock];
}
static bool CheckMemberOfType(NSDictionary<NSString *, id> * responseValue, NSString * memberName, Class expectedClass,
NSString * errorMessage, NSError * __autoreleasing * error);
static void LogStringAndReturnError(NSString * errorStr, CHIP_ERROR errorCode, NSError * __autoreleasing * error);
static void LogStringAndReturnError(NSString * errorStr, MTRErrorCode errorCode, NSError * __autoreleasing * error);
@implementation MTRReadClientContainer
- (void)cleanup
{
if (_readClientPtr) {
Platform::Delete(_readClientPtr);
_readClientPtr = nullptr;
}
if (_pathParams) {
static_assert(std::is_trivially_destructible<AttributePathParams>::value, "AttributePathParams destructors won't get run");
Platform::MemoryFree(_pathParams);
_pathParams = nullptr;
}
if (_eventPathParams) {
static_assert(std::is_trivially_destructible<EventPathParams>::value, "EventPathParams destructors won't get run");
Platform::MemoryFree(_eventPathParams);
_eventPathParams = nullptr;
}
if (_callback) {
Platform::Delete(_callback);
_callback = nullptr;
}
}
- (void)onDone
{
[self cleanup];
PurgeCompletedReadClientContainers(_deviceID);
}
@end
@implementation MTRBaseDevice
- (instancetype)initWithPASEDevice:(chip::DeviceProxy *)device controller:(MTRDeviceController *)controller
{
if (self = [super init]) {
_isPASEDevice = YES;
_nodeID = device->GetDeviceId();
_deviceController = controller;
}
return self;
}
- (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller
{
if (self = [super init]) {
_isPASEDevice = NO;
_nodeID = nodeID.unsignedLongLongValue;
_deviceController = controller;
}
return self;
}
+ (MTRBaseDevice *)deviceWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller
{
// Indirect through the controller to give it a chance to create an
// MTRBaseDeviceOverXPC instead of just an MTRBaseDevice.
return [controller baseDeviceForNodeID:nodeID];
}
- (MTRTransportType)sessionTransportType
{
return [self.deviceController sessionTransportTypeForDevice:self];
}
- (void)invalidateCASESession
{
if (self.isPASEDevice) {
return;
}
[self.deviceController invalidateCASESessionForNode:self.nodeID];
}
namespace {
class SubscriptionCallback final : public MTRBaseSubscriptionCallback {
public:
SubscriptionCallback(DataReportCallback attributeReportCallback, DataReportCallback eventReportCallback,
ErrorCallback errorCallback, MTRDeviceResubscriptionScheduledHandler _Nullable resubscriptionScheduledHandler,
MTRSubscriptionEstablishedHandler _Nullable subscriptionEstablishedHandler, OnDoneHandler _Nullable onDoneHandler)
: MTRBaseSubscriptionCallback(attributeReportCallback, eventReportCallback, errorCallback, resubscriptionScheduledHandler,
subscriptionEstablishedHandler, onDoneHandler)
{
}
void OnEventData(const EventHeader & aEventHeader, TLV::TLVReader * apData, const StatusIB * apStatus) override;
void OnAttributeData(const ConcreteDataAttributePath & aPath, TLV::TLVReader * apData, const StatusIB & aStatus) override;
};
} // anonymous namespace
- (void)subscribeWithQueue:(dispatch_queue_t)queue
params:(MTRSubscribeParams *)params
clusterStateCacheContainer:(MTRClusterStateCacheContainer * _Nullable)clusterStateCacheContainer
attributeReportHandler:(MTRDeviceReportHandler _Nullable)attributeReportHandler
eventReportHandler:(MTRDeviceReportHandler _Nullable)eventReportHandler
errorHandler:(void (^)(NSError * error))errorHandler
subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished
resubscriptionScheduled:(MTRDeviceResubscriptionScheduledHandler _Nullable)resubscriptionScheduled
{
if (self.isPASEDevice) {
// We don't support subscriptions over PASE.
dispatch_async(queue, ^{
errorHandler([MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]);
});
return;
}
// Copy params before going async.
params = [params copy];
[self.deviceController getSessionForNode:self.nodeID
completion:^(ExchangeManager * _Nullable exchangeManager, const Optional<SessionHandle> & session,
NSError * _Nullable error, NSNumber * _Nullable retryDelay) {
if (error != nil) {
dispatch_async(queue, ^{
errorHandler(error);
});
return;
}
// Wildcard endpoint, cluster, attribute, event.
auto attributePath = std::make_unique<AttributePathParams>();
auto eventPath = std::make_unique<EventPathParams>();
eventPath->mIsUrgentEvent = params.reportEventsUrgently;
ReadPrepareParams readParams(session.Value());
[params toReadPrepareParams:readParams];
readParams.mpAttributePathParamsList = attributePath.get();
readParams.mAttributePathParamsListSize = 1;
readParams.mpEventPathParamsList = eventPath.get();
readParams.mEventPathParamsListSize = 1;
std::unique_ptr<ClusterStateCache> clusterStateCache;
ReadClient::Callback * callbackForReadClient = nullptr;
OnDoneHandler onDoneHandler = nil;
if (clusterStateCacheContainer) {
__weak MTRClusterStateCacheContainer * weakPtr = clusterStateCacheContainer;
onDoneHandler = ^{
// This, like all manipulation of cppClusterStateCache, needs to run on the Matter
// queue.
MTRClusterStateCacheContainer * container = weakPtr;
if (container) {
container.cppClusterStateCache = nullptr;
container.baseDevice = nil;
}
};
}
auto callback = std::make_unique<SubscriptionCallback>(
^(NSArray * value) {
dispatch_async(queue, ^{
if (attributeReportHandler != nil) {
attributeReportHandler(value);
}
});
},
^(NSArray * value) {
dispatch_async(queue, ^{
if (eventReportHandler != nil) {
eventReportHandler(value);
}
});
},
^(NSError * error) {
dispatch_async(queue, ^{
errorHandler(error);
});
},
^(NSError * error, NSNumber * resubscriptionDelay) {
dispatch_async(queue, ^{
if (resubscriptionScheduled != nil) {
resubscriptionScheduled(error, resubscriptionDelay);
}
});
},
^(void) {
dispatch_async(queue, ^{
if (subscriptionEstablished != nil) {
subscriptionEstablished();
}
});
},
onDoneHandler);
if (clusterStateCacheContainer) {
clusterStateCache = std::make_unique<ClusterStateCache>(*callback.get());
callbackForReadClient = &clusterStateCache->GetBufferedCallback();
} else {
callbackForReadClient = &callback->GetBufferedCallback();
}
auto readClient = std::make_unique<ReadClient>(InteractionModelEngine::GetInstance(),
exchangeManager, *callbackForReadClient, ReadClient::InteractionType::Subscribe);
CHIP_ERROR err;
if (!params.resubscribeAutomatically) {
err = readClient->SendRequest(readParams);
} else {
// SendAutoResubscribeRequest cleans up the params, even on failure.
attributePath.release();
eventPath.release();
err = readClient->SendAutoResubscribeRequest(std::move(readParams));
}
if (err != CHIP_NO_ERROR) {
dispatch_async(queue, ^{
errorHandler([MTRError errorForCHIPErrorCode:err]);
});
return;
}
if (clusterStateCacheContainer) {
clusterStateCacheContainer.cppClusterStateCache = clusterStateCache.get();
// ClusterStateCache will be deleted when OnDone is called.
callback->AdoptClusterStateCache(std::move(clusterStateCache));
clusterStateCacheContainer.baseDevice = self;
}
// Callback and ReadClient will be deleted when OnDone is called.
callback->AdoptReadClient(std::move(readClient));
callback.release();
}];
}
static NSDictionary<NSString *, id> * _MakeDataValueDictionary(NSString * type, id _Nullable value, NSNumber * _Nullable dataVersion)
{
if (value && dataVersion) {
return @ { MTRTypeKey : type, MTRValueKey : value, MTRDataVersionKey : dataVersion };
} else if (value) {
return @ { MTRTypeKey : type, MTRValueKey : value };
} else if (dataVersion) {
return @ { MTRTypeKey : type, MTRDataVersionKey : dataVersion };
} else {
return @ { MTRTypeKey : type };
}
}
// Convert TLV data into data-value dictionary as described in MTRDeviceResponseHandler
NSDictionary<NSString *, id> * _Nullable MTRDecodeDataValueDictionaryFromCHIPTLV(chip::TLV::TLVReader * data, NSNumber * dataVersion)
{
chip::TLV::TLVType dataTLVType = data->GetType();
switch (dataTLVType) {
case chip::TLV::kTLVType_SignedInteger: {
int64_t val;
CHIP_ERROR err = data->Get(val);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Error(%s): TLV signed integer decoding failed", chip::ErrorStr(err));
return nil;
}
return _MakeDataValueDictionary(MTRSignedIntegerValueType, @(val), dataVersion);
}
case chip::TLV::kTLVType_UnsignedInteger: {
uint64_t val;
CHIP_ERROR err = data->Get(val);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Error(%s): TLV unsigned integer decoding failed", chip::ErrorStr(err));
return nil;
}
return _MakeDataValueDictionary(MTRUnsignedIntegerValueType, @(val), dataVersion);
}
case chip::TLV::kTLVType_Boolean: {
bool val;
CHIP_ERROR err = data->Get(val);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Error(%s): TLV boolean decoding failed", chip::ErrorStr(err));
return nil;
}
return _MakeDataValueDictionary(MTRBooleanValueType, @(val), dataVersion);
}
case chip::TLV::kTLVType_FloatingPointNumber: {
// Try float first
float floatValue;
CHIP_ERROR err = data->Get(floatValue);
if (err == CHIP_NO_ERROR) {
return _MakeDataValueDictionary(MTRFloatValueType, @(floatValue), dataVersion);
}
double val;
err = data->Get(val);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Error(%s): TLV floating point decoding failed", chip::ErrorStr(err));
return nil;
}
return _MakeDataValueDictionary(MTRDoubleValueType, @(val), dataVersion);
}
case chip::TLV::kTLVType_UTF8String: {
CharSpan stringValue;
CHIP_ERROR err = data->Get(stringValue);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Error(%s): TLV UTF8String decoding failed", chip::ErrorStr(err));
return nil;
}
NSString * stringObj = AsString(stringValue);
if (stringObj == nil) {
MTR_LOG_ERROR("Error(%s): TLV UTF8String value is not actually UTF-8", err.AsString());
return nil;
}
return _MakeDataValueDictionary(MTRUTF8StringValueType, stringObj, dataVersion);
}
case chip::TLV::kTLVType_ByteString: {
ByteSpan bytesValue;
CHIP_ERROR err = data->Get(bytesValue);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Error(%s): TLV ByteString decoding failed", chip::ErrorStr(err));
return nil;
}
return _MakeDataValueDictionary(MTROctetStringValueType, AsData(bytesValue), dataVersion);
}
case chip::TLV::kTLVType_Null: {
return _MakeDataValueDictionary(MTRNullValueType, nil, dataVersion);
}
case chip::TLV::kTLVType_Structure:
case chip::TLV::kTLVType_Array: {
NSString * typeName;
switch (dataTLVType) {
case chip::TLV::kTLVType_Structure:
typeName = MTRStructureValueType;
break;
case chip::TLV::kTLVType_Array:
typeName = MTRArrayValueType;
break;
default:
typeName = @"Unsupported";
break;
}
chip::TLV::TLVType tlvType;
CHIP_ERROR err = data->EnterContainer(tlvType);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Error(%s): TLV container entering failed", chip::ErrorStr(err));
return nil;
}
NSMutableArray * array = [[NSMutableArray alloc] init];
while ((err = data->Next()) == CHIP_NO_ERROR) {
chip::TLV::Tag tag = data->GetTag();
id value = MTRDecodeDataValueDictionaryFromCHIPTLV(data);
if (value == nullptr) {
MTR_LOG_ERROR("Error when decoding TLV container of type %s", typeName.UTF8String);
return nil;
}
NSMutableDictionary * arrayElement = [NSMutableDictionary dictionary];
[arrayElement setObject:value forKey:MTRDataKey];
if (dataTLVType == chip::TLV::kTLVType_Structure) {
uint64_t tagNum;
if (IsContextTag(tag)) {
tagNum = TagNumFromTag(tag);
} else if (IsProfileTag(tag)) {
uint64_t profile = ProfileIdFromTag(tag);
tagNum = (profile << kProfileIdShift) | TagNumFromTag(tag);
} else {
MTR_LOG_ERROR("Skipping unknown tag type when decoding TLV structure.");
continue;
}
[arrayElement setObject:[NSNumber numberWithUnsignedLongLong:tagNum] forKey:MTRContextTagKey];
}
[array addObject:arrayElement];
}
if (err != CHIP_END_OF_TLV) {
MTR_LOG_ERROR("Error(%s): TLV container decoding failed", chip::ErrorStr(err));
return nil;
}
err = data->ExitContainer(tlvType);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Error(%s): TLV container exiting failed", chip::ErrorStr(err));
return nil;
}
return _MakeDataValueDictionary(typeName, array, dataVersion);
}
default:
MTR_LOG_ERROR("Error: Unsupported TLV type for conversion: %u", static_cast<unsigned>(data->GetType()));
return nil;
}
}
static CHIP_ERROR MTREncodeTLVFromDataValueDictionary(id object, chip::TLV::TLVWriter & writer, chip::TLV::Tag tag)
{
if (![object isKindOfClass:[NSDictionary class]]) {
MTR_LOG_ERROR("Error: Unsupported object to encode: %@", [object class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
NSString * typeName = ((NSDictionary *) object)[MTRTypeKey];
id value = ((NSDictionary *) object)[MTRValueKey];
if (![typeName isKindOfClass:[NSString class]]) {
MTR_LOG_ERROR("Error: Object to encode is corrupt");
return CHIP_ERROR_INVALID_ARGUMENT;
}
if ([typeName isEqualToString:MTRSignedIntegerValueType]) {
if (![value isKindOfClass:[NSNumber class]]) {
MTR_LOG_ERROR("Error: Object to encode has corrupt signed integer type: %@", [value class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
return writer.Put(tag, [value longLongValue]);
}
if ([typeName isEqualToString:MTRUnsignedIntegerValueType]) {
if (![value isKindOfClass:[NSNumber class]]) {
MTR_LOG_ERROR("Error: Object to encode has corrupt unsigned integer type: %@", [value class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
return writer.Put(tag, [value unsignedLongLongValue]);
}
if ([typeName isEqualToString:MTRBooleanValueType]) {
if (![value isKindOfClass:[NSNumber class]]) {
MTR_LOG_ERROR("Error: Object to encode has corrupt boolean type: %@", [value class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
return writer.Put(tag, static_cast<bool>([value boolValue]));
}
if ([typeName isEqualToString:MTRFloatValueType]) {
if (![value isKindOfClass:[NSNumber class]]) {
MTR_LOG_ERROR("Error: Object to encode has corrupt float type: %@", [value class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
return writer.Put(tag, [value floatValue]);
}
if ([typeName isEqualToString:MTRDoubleValueType]) {
if (![value isKindOfClass:[NSNumber class]]) {
MTR_LOG_ERROR("Error: Object to encode has corrupt double type: %@", [value class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
return writer.Put(tag, [value doubleValue]);
}
if ([typeName isEqualToString:MTRNullValueType]) {
return writer.PutNull(tag);
}
if ([typeName isEqualToString:MTRUTF8StringValueType]) {
if (![value isKindOfClass:[NSString class]]) {
MTR_LOG_ERROR("Error: Object to encode has corrupt UTF8 string type: %@", [value class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
return writer.PutString(tag, [value UTF8String]);
}
if ([typeName isEqualToString:MTROctetStringValueType]) {
if (![value isKindOfClass:[NSData class]]) {
MTR_LOG_ERROR("Error: Object to encode has corrupt octet string type: %@", [value class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
return writer.Put(tag, chip::ByteSpan(static_cast<const uint8_t *>([value bytes]), [value length]));
}
if ([typeName isEqualToString:MTRStructureValueType]) {
if (![value isKindOfClass:[NSArray class]]) {
MTR_LOG_ERROR("Error: Object to encode has corrupt structure type: %@", [value class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
TLV::TLVType outer;
ReturnErrorOnFailure(writer.StartContainer(tag, chip::TLV::kTLVType_Structure, outer));
for (id element in value) {
if (![element isKindOfClass:[NSDictionary class]]) {
MTR_LOG_ERROR("Error: Structure element to encode has corrupt type: %@", [element class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
id elementTag = element[MTRContextTagKey];
id elementValue = element[MTRDataKey];
if (!elementTag || !elementValue) {
MTR_LOG_ERROR("Error: Structure element to encode has corrupt value: %@", element);
return CHIP_ERROR_INVALID_ARGUMENT;
}
if (![elementTag isKindOfClass:NSNumber.class]) {
MTR_LOG_ERROR("Error: Structure element to encode has corrupt tag type: %@", [elementTag class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
// Our tag might actually be a profile tag.
uint64_t tagValue = [elementTag unsignedLongLongValue];
TLV::Tag tag;
if (tagValue > UINT8_MAX) {
tag = TLV::ProfileTag(tagValue >> kProfileIdShift,
(tagValue & ((1ull << kProfileIdShift) - 1)));
} else {
tag = TLV::ContextTag(static_cast<uint8_t>(tagValue));
}
ReturnErrorOnFailure(
MTREncodeTLVFromDataValueDictionary(elementValue, writer, tag));
}
ReturnErrorOnFailure(writer.EndContainer(outer));
return CHIP_NO_ERROR;
}
if ([typeName isEqualToString:MTRArrayValueType]) {
if (![value isKindOfClass:[NSArray class]]) {
MTR_LOG_ERROR("Error: Object to encode has corrupt array type: %@", [value class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
TLV::TLVType outer;
ReturnErrorOnFailure(writer.StartContainer(tag, chip::TLV::kTLVType_Array, outer));
for (id element in value) {
if (![element isKindOfClass:[NSDictionary class]]) {
MTR_LOG_ERROR("Error: Array element to encode has corrupt type: %@", [element class]);
return CHIP_ERROR_INVALID_ARGUMENT;
}
id elementValue = element[MTRDataKey];
if (!elementValue) {
MTR_LOG_ERROR("Error: Array element to encode has corrupt value: %@", element);
return CHIP_ERROR_INVALID_ARGUMENT;
}
ReturnErrorOnFailure(MTREncodeTLVFromDataValueDictionary(elementValue, writer, chip::TLV::AnonymousTag()));
}
ReturnErrorOnFailure(writer.EndContainer(outer));
return CHIP_NO_ERROR;
}
MTR_LOG_ERROR("Error: Unsupported type to encode: %@", typeName);
return CHIP_ERROR_INVALID_ARGUMENT;
}
NSData * _Nullable MTREncodeTLVFromDataValueDictionary(NSDictionary<NSString *, id> * value, NSError * __autoreleasing * error)
{
// A single data item cannot be bigger than a packet, so just use 1200 bytes
// as the max size of our buffer. This assumes that lists will not be
// passed as-is to this method but will get chunked, with each list item
// passed to this method separately.
uint8_t buffer[1200];
TLV::TLVWriter writer;
writer.Init(buffer);
CHIP_ERROR err = MTREncodeTLVFromDataValueDictionary(value, writer, TLV::AnonymousTag());
if (err != CHIP_NO_ERROR) {
if (error) {
*error = [MTRError errorForCHIPErrorCode:err];
}
return nil;
}
return AsData(ByteSpan(buffer, writer.GetLengthWritten()));
}
// Callback type to pass data value as an NSObject
typedef void (*MTRDataValueDictionaryCallback)(void * context, id value);
// Rename to be generic for decode and encode
class MTRDataValueDictionaryDecodableType {
public:
MTRDataValueDictionaryDecodableType()
: decodedObj(nil)
{
}
MTRDataValueDictionaryDecodableType(id obj)
: decodedObj(obj)
{
}
CHIP_ERROR Decode(chip::TLV::TLVReader & data)
{
decodedObj = MTRDecodeDataValueDictionaryFromCHIPTLV(&data);
if (decodedObj == nil) {
MTR_LOG_ERROR("Error: Failed to get value from TLV data for attribute reading response");
}
return (decodedObj) ? CHIP_NO_ERROR : CHIP_ERROR_DECODE_FAILED;
}
CHIP_ERROR Encode(chip::TLV::TLVWriter & writer, chip::TLV::Tag tag) const
{
return MTREncodeTLVFromDataValueDictionary(decodedObj, writer, tag);
}
static constexpr bool kIsFabricScoped = false;
static bool MustUseTimedInvoke() { return false; }
NSDictionary<NSString *, id> * _Nullable GetDecodedObject() const { return decodedObj; }
private:
NSDictionary<NSString *, id> * _Nullable decodedObj;
};
// Callback bridge for MTRDataValueDictionaryCallback
class MTRDataValueDictionaryCallbackBridge : public MTRCallbackBridge<MTRDataValueDictionaryCallback> {
public:
MTRDataValueDictionaryCallbackBridge(dispatch_queue_t queue, MTRDeviceResponseHandler handler, MTRActionBlock action)
: MTRCallbackBridge<MTRDataValueDictionaryCallback>(queue, handler, action, OnSuccessFn) {};
static void OnSuccessFn(void * context, id value) { DispatchSuccess(context, value); }
};
template <typename DecodableValueType>
class BufferedReadClientCallback final : public app::ReadClient::Callback {
public:
using OnSuccessAttributeCallbackType
= std::function<void(const ConcreteDataAttributePath & aPath, const DecodableValueType & aData)>;
using OnSuccessEventCallbackType = std::function<void(const EventHeader & aEventHeader, const DecodableValueType & aData)>;
using OnErrorCallbackType = std::function<void(
const app::ConcreteAttributePath * attributePath, const app::ConcreteEventPath * eventPath, CHIP_ERROR aError)>;
using OnDoneCallbackType = std::function<void(BufferedReadClientCallback * callback)>;
using OnSubscriptionEstablishedCallbackType = std::function<void()>;
using OnDeviceResubscriptionScheduledCallbackType = std::function<void(NSError * error, NSNumber * resubscriptionDelay)>;
BufferedReadClientCallback(app::AttributePathParams * aAttributePathParamsList, size_t aAttributePathParamsSize,
app::EventPathParams * aEventPathParamsList, size_t aEventPathParamsSize,
OnSuccessAttributeCallbackType aOnAttributeSuccess, OnSuccessEventCallbackType aOnEventSuccess,
OnErrorCallbackType aOnError, OnDoneCallbackType aOnDone,
OnSubscriptionEstablishedCallbackType aOnSubscriptionEstablished = nullptr,
OnDeviceResubscriptionScheduledCallbackType aOnDeviceResubscriptionScheduled = nullptr)
: mAttributePathParamsList(aAttributePathParamsList)
, mAttributePathParamsSize(aAttributePathParamsSize)
, mEventPathParamsList(aEventPathParamsList)
, mEventPathParamsSize(aEventPathParamsSize)
, mOnAttributeSuccess(aOnAttributeSuccess)
, mOnEventSuccess(aOnEventSuccess)
, mOnError(aOnError)
, mOnDone(aOnDone)
, mOnSubscriptionEstablished(aOnSubscriptionEstablished)
, mOnDeviceResubscriptionScheduled(aOnDeviceResubscriptionScheduled)
, mBufferedReadAdapter(*this)
{
}
~BufferedReadClientCallback()
{
// Ensure we release the ReadClient before we tear down anything else,
// so it can call our OnDeallocatePaths properly.
mReadClient = nullptr;
}
app::BufferedReadCallback & GetBufferedCallback() { return mBufferedReadAdapter; }
void AdoptReadClient(Platform::UniquePtr<app::ReadClient> aReadClient) { mReadClient = std::move(aReadClient); }
private:
void OnAttributeData(
const app::ConcreteDataAttributePath & aPath, TLV::TLVReader * apData, const app::StatusIB & aStatus) override
{
CHIP_ERROR err = CHIP_NO_ERROR;
DecodableValueType value;
VerifyOrExit(mOnAttributeSuccess != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(mAttributePathParamsList != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
//
// We shouldn't be getting list item operations in the provided path since that should be handled by the buffered read
// callback. If we do, that's a bug.
//
VerifyOrDie(!aPath.IsListItemOperation());
VerifyOrExit(
std::find_if(mAttributePathParamsList, mAttributePathParamsList + mAttributePathParamsSize,
[aPath](app::AttributePathParams & pathParam) -> bool { return pathParam.IsAttributePathSupersetOf(aPath); })
!= mAttributePathParamsList + mAttributePathParamsSize,
err = CHIP_ERROR_SCHEMA_MISMATCH);
VerifyOrExit(aStatus.IsSuccess(), err = aStatus.ToChipError());
VerifyOrExit(apData != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
SuccessOrExit(err = app::DataModel::Decode(*apData, value));
mOnAttributeSuccess(aPath, value);
exit:
if (err != CHIP_NO_ERROR) {
mOnError(&aPath, nullptr, err);
}
}
void OnEventData(const EventHeader & aEventHeader, TLV::TLVReader * apData, const StatusIB * apStatus) override
{
CHIP_ERROR err = CHIP_NO_ERROR;
DecodableValueType value;
VerifyOrExit(mOnEventSuccess != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(mEventPathParamsList != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(std::find_if(mEventPathParamsList, mEventPathParamsList + mEventPathParamsSize,
[aEventHeader](app::EventPathParams & pathParam) -> bool {
return pathParam.IsEventPathSupersetOf(aEventHeader.mPath);
})
!= mEventPathParamsList + mEventPathParamsSize,
err = CHIP_ERROR_SCHEMA_MISMATCH);
VerifyOrExit(apStatus == nullptr, err = apStatus->ToChipError());
VerifyOrExit(apData != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
SuccessOrExit(err = app::DataModel::Decode(*apData, value));
mOnEventSuccess(aEventHeader, value);
exit:
if (err != CHIP_NO_ERROR) {
mOnError(nullptr, &aEventHeader.mPath, err);
}
}
void OnError(CHIP_ERROR aError) override { mOnError(nullptr, nullptr, aError); }
void OnDone(ReadClient *) override { mOnDone(this); }
void OnSubscriptionEstablished(SubscriptionId aSubscriptionId) override
{
if (mOnSubscriptionEstablished) {
mOnSubscriptionEstablished();
}
}
CHIP_ERROR OnResubscriptionNeeded(ReadClient * apReadClient, CHIP_ERROR aTerminationCause) override
{
CHIP_ERROR err = ReadClient::Callback::OnResubscriptionNeeded(apReadClient, aTerminationCause);
ReturnErrorOnFailure(err);
if (mOnDeviceResubscriptionScheduled != nullptr) {
auto callback = mOnDeviceResubscriptionScheduled;
auto error = [MTRError errorForCHIPErrorCode:aTerminationCause];
auto delayMs = @(apReadClient->ComputeTimeTillNextSubscription());
callback(error, delayMs);
}
return CHIP_NO_ERROR;
}
void OnDeallocatePaths(chip::app::ReadPrepareParams && aReadPrepareParams) override {}
OnSuccessAttributeCallbackType mOnAttributeSuccess;
OnSuccessEventCallbackType mOnEventSuccess;
OnErrorCallbackType mOnError;
OnDoneCallbackType mOnDone;
OnSubscriptionEstablishedCallbackType mOnSubscriptionEstablished;
OnDeviceResubscriptionScheduledCallbackType mOnDeviceResubscriptionScheduled;
app::BufferedReadCallback mBufferedReadAdapter;
Platform::UniquePtr<app::ReadClient> mReadClient;
app::AttributePathParams * mAttributePathParamsList;
app::EventPathParams * mEventPathParamsList;
size_t mAttributePathParamsSize;
size_t mEventPathParamsSize;
};
- (void)readAttributesWithEndpointID:(NSNumber * _Nullable)endpointID
clusterID:(NSNumber * _Nullable)clusterID
attributeID:(NSNumber * _Nullable)attributeID
params:(MTRReadParams * _Nullable)params
queue:(dispatch_queue_t)queue
completion:(MTRDeviceResponseHandler)completion
{
NSArray<MTRAttributeRequestPath *> * attributePaths = [NSArray
arrayWithObject:[MTRAttributeRequestPath requestPathWithEndpointID:endpointID clusterID:clusterID attributeID:attributeID]];
[self readAttributePaths:attributePaths eventPaths:nil params:params queue:queue completion:completion];
}
- (void)_readKnownAttributeWithEndpointID:(NSNumber *)endpointID
clusterID:(NSNumber *)clusterID
attributeID:(NSNumber *)attributeID
params:(MTRReadParams * _Nullable)params
queue:(dispatch_queue_t)queue
completion:(void (^)(id _Nullable value, NSError * _Nullable error))completion
{
auto * attributePath = [MTRAttributePath attributePathWithEndpointID:endpointID clusterID:clusterID attributeID:attributeID];
auto innerCompletion = ^(NSArray<NSDictionary<NSString *, id> *> * _Nullable values, NSError * _Nullable error) {
if (error != nil) {
completion(nil, error);
return;
}
// Preserving the old behavior: we don't fail on multiple reports, but
// just report the first one.
if (values.count == 0) {
completion(nil, [NSError errorWithDomain:MTRErrorDomain code:MTRErrorCodeSchemaMismatch userInfo:nil]);
return;
}
NSDictionary<NSString *, id> * value = values[0];
NSError * initError;
auto * report = [[MTRAttributeReport alloc] initWithResponseValue:value error:&initError];
if (initError != nil) {
completion(nil, initError);
return;
}
if (![report.path isEqual:attributePath]) {
// For some reason the server returned data for the wrong
// attribute, even though it happened to decode to our type.
completion(nil, [NSError errorWithDomain:MTRErrorDomain code:MTRErrorCodeSchemaMismatch userInfo:nil]);
return;
}
completion(report.value, report.error);
};
[self readAttributesWithEndpointID:endpointID
clusterID:clusterID
attributeID:attributeID
params:params
queue:queue
completion:innerCompletion];
}
- (void)readAttributePaths:(NSArray<MTRAttributeRequestPath *> * _Nullable)attributePaths
eventPaths:(NSArray<MTREventRequestPath *> * _Nullable)eventPaths
params:(MTRReadParams * _Nullable)params
queue:(dispatch_queue_t)queue
completion:(MTRDeviceResponseHandler)completion
{
[self readAttributePaths:attributePaths eventPaths:eventPaths params:params includeDataVersion:NO queue:queue completion:completion];
}
- (void)readAttributePaths:(NSArray<MTRAttributeRequestPath *> * _Nullable)attributePaths
eventPaths:(NSArray<MTREventRequestPath *> * _Nullable)eventPaths
params:(MTRReadParams * _Nullable)params
includeDataVersion:(BOOL)includeDataVersion