forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMTRDevice_Concrete.mm
4998 lines (4266 loc) · 227 KB
/
MTRDevice_Concrete.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) 2022-2025 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/Matter.h>
#import <os/lock.h>
#import "MTRAsyncWorkQueue.h"
#import "MTRAttributeSpecifiedCheck.h"
#import "MTRBaseClusters.h"
#import "MTRBaseDevice_Internal.h"
#import "MTRBaseSubscriptionCallback.h"
#import "MTRCluster.h"
#import "MTRClusterConstants.h"
#import "MTRCommandTimedCheck.h"
#import "MTRConversion.h"
#import "MTRDefines_Internal.h"
#import "MTRDeviceConnectivityMonitor.h"
#import "MTRDeviceControllerOverXPC.h"
#import "MTRDeviceController_Internal.h"
#import "MTRDeviceDataValidation.h"
#import "MTRDevice_Concrete.h"
#import "MTRDevice_Internal.h"
#import "MTRError_Internal.h"
#import "MTREventTLVValueDecoder_Internal.h"
#import "MTRLogging_Internal.h"
#import "MTRMetricKeys.h"
#import "MTRMetricsCollector.h"
#import "MTRTimeUtils.h"
#import "MTRUnfairLock.h"
#import "MTRUtilities.h"
#import "zap-generated/MTRCommandPayloads_Internal.h"
#import "lib/core/CHIPError.h"
#import "lib/core/DataModelTypes.h"
#import <app/ConcreteAttributePath.h>
#import <lib/support/FibonacciUtils.h>
#import <app/AttributePathParams.h>
#import <app/BufferedReadCallback.h>
#import <app/ClusterStateCache.h>
#import <app/InteractionModelEngine.h>
#import <platform/LockTracker.h>
#import <platform/PlatformManager.h>
static NSString * const sLastInitialSubscribeLatencyKey = @"lastInitialSubscribeLatency";
static NSString * const sDeviceMayBeReachableReason = @"SPI client indicated the device may now be reachable";
// Not static, because these are public API.
NSString * const MTRPreviousDataKey = @"previousData";
NSString * const MTRDataVersionKey = @"dataVersion";
// allow readwrite access to superclass properties
@interface MTRDevice_Concrete ()
@property (nonatomic, readwrite) MTRAsyncWorkQueue<MTRDevice *> * asyncWorkQueue;
@property (nonatomic, readwrite) MTRDeviceState state;
@property (nonatomic, readwrite, nullable) NSDate * estimatedStartTime;
@property (nonatomic, readwrite, nullable, copy) NSNumber * estimatedSubscriptionLatency;
@property (nonatomic, readwrite, assign) BOOL suspended;
// nullable because technically _deviceController is nullable.
@property (nonatomic, readonly, nullable) MTRDeviceController_Concrete * _concreteController;
@end
typedef void (^MTRDeviceAttributeReportHandler)(NSArray * _Nonnull);
#define kSecondsToWaitBeforeMarkingUnreachableAfterSettingUpSubscription 10
// Disabling pending crashes
#define ENABLE_CONNECTIVITY_MONITORING 0
/* BEGIN DRAGONS: Note methods here cannot be renamed, and are used by private callers, do not rename, remove or modify behavior here */
@interface NSObject (MatterPrivateForInternalDragonsDoNotFeed)
- (void)_deviceInternalStateChanged:(MTRDevice *)device;
@end
/* END DRAGONS */
#pragma mark - SubscriptionCallback class declaration
using namespace chip;
using namespace chip::app;
using namespace chip::Protocols::InteractionModel;
using namespace chip::Tracing::DarwinFramework;
typedef void (^FirstReportHandler)(void);
namespace {
class SubscriptionCallback final : public MTRBaseSubscriptionCallback {
public:
SubscriptionCallback(DataReportCallback attributeReportCallback, DataReportCallback eventReportCallback,
ErrorCallback errorCallback, MTRDeviceResubscriptionScheduledHandler resubscriptionCallback,
SubscriptionEstablishedHandler subscriptionEstablishedHandler, OnDoneHandler onDoneHandler,
UnsolicitedMessageFromPublisherHandler unsolicitedMessageFromPublisherHandler, ReportBeginHandler reportBeginHandler,
ReportEndHandler reportEndHandler)
: MTRBaseSubscriptionCallback(attributeReportCallback, eventReportCallback, errorCallback, resubscriptionCallback,
subscriptionEstablishedHandler, onDoneHandler, unsolicitedMessageFromPublisherHandler, reportBeginHandler,
reportEndHandler)
{
}
// Used to reset Resubscription backoff on events that indicate likely availability of device to come back online
void ResetResubscriptionBackoff() { mResubscriptionNumRetries = 0; }
private:
void OnSubscriptionEstablished(chip::SubscriptionId aSubscriptionId) override;
void OnEventData(const EventHeader & aEventHeader, TLV::TLVReader * apData, const StatusIB * apStatus) override;
void OnAttributeData(const ConcreteDataAttributePath & aPath, TLV::TLVReader * apData, const StatusIB & aStatus) override;
CHIP_ERROR OnResubscriptionNeeded(chip::app::ReadClient * apReadClient, CHIP_ERROR aTerminationCause) override;
// Copied from ReadClient and customized for MTRDevice resubscription time reset
uint32_t ComputeTimeTillNextSubscription();
uint32_t mResubscriptionNumRetries = 0;
};
} // anonymous namespace
#pragma mark - MTRDeviceMatterCPPObjectsHolder
// Class to hold C++ objects that can only be manipulated on the Matter queue
@interface MTRDeviceMatterCPPObjectsHolder : NSObject
@property (nonatomic, readonly) ReadClient * readClient;
@property (nonatomic, readonly) SubscriptionCallback * subscriptionCallback; // valid when and only when readClient is valid
- (void)setReadClient:(ReadClient * _Nullable)readClient subscriptionCallback:(SubscriptionCallback * _Nullable)subscriptionCallback;
- (void)clearReadClientAndDeleteSubscriptionCallback;
@end
@implementation MTRDeviceMatterCPPObjectsHolder
@synthesize readClient = _readClient;
@synthesize subscriptionCallback = _subscriptionCallback;
- (ReadClient *)readClient
{
assertChipStackLockedByCurrentThread();
@synchronized(self) {
return _readClient;
}
}
- (SubscriptionCallback *)subscriptionCallback
{
assertChipStackLockedByCurrentThread();
@synchronized(self) {
return _subscriptionCallback;
}
}
- (void)setReadClient:(ReadClient * _Nullable)readClient subscriptionCallback:(SubscriptionCallback * _Nullable)subscriptionCallback
{
assertChipStackLockedByCurrentThread();
@synchronized(self) {
// Sanity check and log if readClient and subscriptionCallback aren't both valid or both null
if (((readClient == nullptr) && (subscriptionCallback != nullptr)) || ((readClient != nullptr) && (subscriptionCallback == nullptr))) {
MTR_LOG_ERROR("%@: setReadClient:subscriptionCallback: readClient and subscriptionCallback must both be valid or both be null %p %p", self, readClient, subscriptionCallback);
}
// Sanity check and log if overriding existing values
if ((readClient != nullptr) && (_readClient != nullptr)) {
MTR_LOG_ERROR("%@: setReadClient:subscriptionCallback: readClient set when current value not null %p %p", self, readClient, _readClient);
}
if (((subscriptionCallback != nullptr)) && (_subscriptionCallback != nullptr)) {
MTR_LOG_ERROR("%@: setReadClient:subscriptionCallback: subscriptionCallback set when current value not null %p %p", self, subscriptionCallback, _subscriptionCallback);
}
_readClient = readClient;
_subscriptionCallback = subscriptionCallback;
}
}
- (void)clearReadClientAndDeleteSubscriptionCallback
{
assertChipStackLockedByCurrentThread();
@synchronized(self) {
_readClient = nullptr;
if (_subscriptionCallback) {
delete _subscriptionCallback;
_subscriptionCallback = nullptr;
}
}
}
@end
#pragma mark - MTRDevice
// Utility methods for working with MTRInternalDeviceState, located near the
// enum so it's easier to notice that they need to stay in sync.
namespace {
bool HadSubscriptionEstablishedOnce(MTRInternalDeviceState state)
{
return state >= MTRInternalDeviceStateInitialSubscriptionEstablished;
}
bool NeedToStartSubscriptionSetup(MTRInternalDeviceState state)
{
return state <= MTRInternalDeviceStateUnsubscribed;
}
bool HaveSubscriptionEstablishedRightNow(MTRInternalDeviceState state)
{
return state == MTRInternalDeviceStateInitialSubscriptionEstablished || state == MTRInternalDeviceStateLaterSubscriptionEstablished;
}
NSString * InternalDeviceStateString(MTRInternalDeviceState state)
{
switch (state) {
case MTRInternalDeviceStateUnsubscribed:
return @"Unsubscribed";
case MTRInternalDeviceStateSubscribing:
return @"Subscribing";
case MTRInternalDeviceStateInitialSubscriptionEstablished:
return @"InitialSubscriptionEstablished";
case MTRInternalDeviceStateResubscribing:
return @"Resubscribing";
case MTRInternalDeviceStateLaterSubscriptionEstablished:
return @"LaterSubscriptionEstablished";
default:
return @"Unknown";
}
}
} // anonymous namespace
typedef NS_ENUM(NSUInteger, MTRDeviceExpectedValueFieldIndex) {
MTRDeviceExpectedValueFieldExpirationTimeIndex = 0,
MTRDeviceExpectedValueFieldValueIndex = 1,
MTRDeviceExpectedValueFieldIDIndex = 2
};
typedef NS_ENUM(NSUInteger, MTRDeviceReadRequestFieldIndex) {
MTRDeviceReadRequestFieldPathIndex = 0,
MTRDeviceReadRequestFieldParamsIndex = 1
};
typedef NS_ENUM(NSUInteger, MTRDeviceWriteRequestFieldIndex) {
MTRDeviceWriteRequestFieldPathIndex = 0,
MTRDeviceWriteRequestFieldValueIndex = 1,
MTRDeviceWriteRequestFieldTimeoutIndex = 2,
MTRDeviceWriteRequestFieldExpectedValueIDIndex = 3,
};
typedef NS_ENUM(NSUInteger, MTRDeviceWorkItemBatchingID) {
MTRDeviceWorkItemBatchingReadID = 1,
MTRDeviceWorkItemBatchingWriteID = 2,
};
typedef NS_ENUM(NSUInteger, MTRDeviceWorkItemDuplicateTypeID) {
MTRDeviceWorkItemDuplicateReadTypeID = 1,
};
// Minimal time to wait since our last resubscribe failure before we will allow
// a read attempt to prod our subscription.
//
// TODO: Figure out a better value for this, but for now don't allow this to
// happen more often than once every 10 minutes.
#define MTRDEVICE_MIN_RESUBSCRIBE_DUE_TO_READ_INTERVAL_SECONDS (10 * 60)
// Weight of new data in determining subscription latencies. To avoid random
// outliers causing too much noise in the value, treat an existing value (if
// any) as having 2/3 weight and the new value as having 1/3 weight. These
// weights are subject to change, if it's determined that different ones give
// better behavior.
#define MTRDEVICE_SUBSCRIPTION_LATENCY_NEW_VALUE_WEIGHT (1.0 / 3.0)
@interface MTRDevice_Concrete ()
// protects against concurrent time updates by guarding timeUpdateScheduled flag which manages time updates scheduling,
// and protects device calls to setUTCTime and setDSTOffset. This can't just be replaced with "lock", because the time
// update code calls public APIs like readAttributeWithEndpointID:.. (which attempt to take "lock") while holding
// whatever lock protects the time sync bits.
@property (nonatomic, readonly) os_unfair_lock timeSyncLock;
@property (nonatomic) NSMutableArray<NSDictionary<NSString *, id> *> * unreportedEvents;
// The highest event number we have observed, if there was one at all.
@property (nonatomic, readwrite, nullable) NSNumber * highestObservedEventNumber;
// receivingReport is true if we are receving a subscription report. In
// particular, this will be false if we're just getting an attribute value from
// a read-through.
@property (nonatomic) BOOL receivingReport;
// receivingPrimingReport is true if this subscription report is part of us
// establishing a new subscription to the device. When this is true, it is
// _not_ guaranteed that any particular set of attributes will be reported
// (e.g. everything could be filtered out by our DataVersion filters).
// Conversely, when this is false that tells us nothing about attributes _not_
// being reported: a device could randomly decide to rev all data versions and
// report all attributes at any point in time, for example due to performing
// subscription resumption.
@property (nonatomic) BOOL receivingPrimingReport;
// TODO: instead of all the BOOL properties that are some facet of the state, move to internal state machine that has (at least):
// Actively receiving report
// Actively receiving priming report
@property (nonatomic) MTRInternalDeviceState internalDeviceState;
@property (nonatomic) BOOL doingCASEAttemptForDeviceMayBeReachable;
#define MTRDEVICE_SUBSCRIPTION_ATTEMPT_MIN_WAIT_SECONDS (1)
#define MTRDEVICE_SUBSCRIPTION_ATTEMPT_MAX_WAIT_SECONDS (3600)
@property (nonatomic) uint32_t lastSubscriptionAttemptWait;
/**
* If reattemptingSubscription is true, that means that we have failed to get a
* CASE session for the publisher and are now waiting to try again. In this
* state we never have subscriptionActive true or a non-null currentReadClient.
*/
@property (nonatomic) BOOL reattemptingSubscription;
// Expected value cache is attributePath => NSArray of [NSDate of expiration time, NSDictionary of value, expected value ID]
// - See MTRDeviceExpectedValueFieldIndex for the definitions of indices into this array.
// See MTRDeviceResponseHandler definition for value dictionary details.
@property (nonatomic) NSMutableDictionary<MTRAttributePath *, NSArray *> * expectedValueCache;
// This is a monotonically increasing value used when adding entries to expectedValueCache
// Currently used/updated only in _getAttributesToReportWithNewExpectedValues:expirationTime:expectedValueID:
@property (nonatomic) uint64_t expectedValueNextID;
@property (nonatomic) BOOL expirationCheckScheduled;
@property (nonatomic) BOOL timeUpdateScheduled;
@property (nonatomic) NSDate * estimatedStartTimeFromGeneralDiagnosticsUpTime;
@property (nonatomic) NSDate * lastDeviceBecameActiveCallbackTime;
@property (nonatomic) BOOL throttlingDeviceBecameActiveCallbacks;
// Keep track of the last time we received subscription related communication from the device
@property (nonatomic, nullable) NSDate * lastSubscriptionActiveTime;
/**
* If currentReadClient is non-null, that means that we successfully
* called SendAutoResubscribeRequest on the ReadClient and have not yet gotten
* an OnDone for that ReadClient.
*/
@property (nonatomic, readonly) MTRDeviceMatterCPPObjectsHolder * matterCPPObjectsHolder;
@end
// Declaring selector so compiler won't complain about testing and calling it in _handleReportEnd
#ifdef DEBUG
@protocol MTRDeviceUnitTestDelegate <MTRDeviceDelegate>
- (void)unitTestReportBeginForDevice:(MTRDevice *)device;
- (void)unitTestReportEndForDevice:(MTRDevice *)device;
- (BOOL)unitTestShouldSetUpSubscriptionForDevice:(MTRDevice *)device;
- (BOOL)unitTestShouldSkipExpectedValuesForWrite:(MTRDevice *)device;
- (NSNumber *)unitTestMaxIntervalOverrideForSubscription:(MTRDevice *)device;
- (BOOL)unitTestForceAttributeReportsIfMatchingCache:(MTRDevice *)device;
- (BOOL)unitTestPretendThreadEnabled:(MTRDevice *)device;
- (void)unitTestSubscriptionPoolDequeue:(MTRDevice *)device;
- (void)unitTestSubscriptionPoolWorkComplete:(MTRDevice *)device;
- (void)unitTestClusterDataPersisted:(MTRDevice *)device;
- (BOOL)unitTestSuppressTimeBasedReachabilityChanges:(MTRDevice *)device;
- (void)unitTestSubscriptionCallbackDeleteForDevice:(MTRDevice *)device;
- (void)unitTestSubscriptionResetForDevice:(MTRDevice *)device;
@end
#endif
@implementation MTRDevice_Concrete {
#ifdef DEBUG
NSUInteger _unitTestAttributesReportedSinceLastCheck;
#endif
// _deviceCachePrimed is true if we have the data that comes from an initial
// subscription priming report (whether it came from storage or from our
// subscription).
BOOL _deviceCachePrimed;
// _persistedClusterData stores data that we have already persisted (when we have
// cluster data persistence enabled). Nil when we have no persistence enabled.
NSCache<MTRClusterPath *, MTRDeviceClusterData *> * _Nullable _persistedClusterData;
// _clusterDataToPersist stores data that needs to be persisted. If we
// don't have persistence enabled, this is our only data store. Nil if we
// currently have nothing that could need persisting.
NSMutableDictionary<MTRClusterPath *, MTRDeviceClusterData *> * _Nullable _clusterDataToPersist;
// _persistedClusters stores the set of "valid" keys into _persistedClusterData.
// These are keys that could have values in _persistedClusterData even if they don't
// right now (because they have been evicted).
NSMutableSet<MTRClusterPath *> * _persistedClusters;
// When we last failed to subscribe to the device (either via
// _setupSubscriptionWithReason or via the auto-resubscribe behavior
// of the ReadClient). Nil if we have had no such failures.
NSDate * _Nullable _lastSubscriptionFailureTime;
MTRDeviceConnectivityMonitor * _connectivityMonitor;
// This boolean keeps track of any device configuration changes received in an attribute report.
// If this is true when the report ends, we notify the delegate.
BOOL _deviceConfigurationChanged;
// The completion block is set when the subscription / resubscription work is enqueued, and called / cleared when any of the following happen:
// 1. Subscription establishes
// 2. OnResubscriptionNeeded is called
// 3. Subscription reset (including when getSessionForNode fails)
MTRAsyncWorkCompletionBlock _subscriptionPoolWorkCompletionBlock;
// Tracking of initial subscribe latency. When _initialSubscribeStart is
// nil, we are not tracking the latency.
NSDate * _Nullable _initialSubscribeStart;
// Storage behavior configuration and variables to keep track of the logic
// _clusterDataPersistenceFirstScheduledTime is used to track the start time of the delay between
// report and persistence.
// _mostRecentReportTimes is a list of the most recent report timestamps used for calculating
// the running average time between reports.
// _deviceReportingExcessivelyStartTime tracks when a device starts reporting excessively.
// _reportToPersistenceDelayCurrentMultiplier is the current multiplier that is calculated when a
// report comes in.
MTRDeviceStorageBehaviorConfiguration * _storageBehaviorConfiguration;
NSDate * _Nullable _clusterDataPersistenceFirstScheduledTime;
NSMutableArray<NSDate *> * _mostRecentReportTimes;
NSDate * _Nullable _deviceReportingExcessivelyStartTime;
double _reportToPersistenceDelayCurrentMultiplier;
// System time change observer reference
id _systemTimeChangeObserverToken;
// Protects mutable state used by our description getter. This is a separate lock from "lock"
// so that we don't need to worry about getting our description while holding "lock" (e.g due to
// logging self). This lock _must_ be held narrowly, with no other lock acquisitions allowed
// while it's held, to avoid deadlock.
os_unfair_lock _descriptionLock;
// State used by our description getter: access to these must be protected by descriptionLock.
NSNumber * _Nullable _vid; // nil if unknown
NSNumber * _Nullable _pid; // nil if unknown
// _allNetworkFeatures is a bitwise or of the feature maps of all network commissioning clusters
// present on the device, or nil if there aren't any.
NSNumber * _Nullable _allNetworkFeatures;
// Copy of _internalDeviceState that is safe to use in description.
MTRInternalDeviceState _internalDeviceStateForDescription;
// Copy of _lastSubscriptionAttemptWait that is safe to use in description.
uint32_t _lastSubscriptionAttemptWaitForDescription;
// Most recent entry in _mostRecentReportTimes, if any.
NSDate * _Nullable _mostRecentReportTimeForDescription;
// Copy of _lastSubscriptionFailureTime that is safe to use in description.
NSDate * _Nullable _lastSubscriptionFailureTimeForDescription;
}
// synthesize superclass property readwrite accessors
@synthesize queue = _queue;
@synthesize asyncWorkQueue = _asyncWorkQueue;
@synthesize state = _state;
@synthesize estimatedStartTime = _estimatedStartTime;
@synthesize estimatedSubscriptionLatency = _estimatedSubscriptionLatency;
//@synthesize lock = _lock;
//@synthesize persistedClusterData = _persistedClusterData;
- (instancetype)initWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController_Concrete *)controller
{
// `super` was NSObject, is now MTRDevice. MTRDevice hides its `init`
if (self = [super initForSubclassesWithNodeID:nodeID controller:controller]) {
_timeSyncLock = OS_UNFAIR_LOCK_INIT;
_descriptionLock = OS_UNFAIR_LOCK_INIT;
_queue
= dispatch_queue_create("org.csa-iot.matter.framework.device.workqueue", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
_expectedValueCache = [NSMutableDictionary dictionary];
_asyncWorkQueue = [[MTRAsyncWorkQueue alloc] initWithContext:self];
_state = MTRDeviceStateUnknown;
_internalDeviceState = MTRInternalDeviceStateUnsubscribed;
_internalDeviceStateForDescription = MTRInternalDeviceStateUnsubscribed;
_doingCASEAttemptForDeviceMayBeReachable = NO;
if (controller.controllerDataStore) {
_persistedClusterData = [[NSCache alloc] init];
} else {
_persistedClusterData = nil;
}
_clusterDataToPersist = nil;
_persistedClusters = [NSMutableSet set];
_highestObservedEventNumber = nil;
_matterCPPObjectsHolder = [[MTRDeviceMatterCPPObjectsHolder alloc] init];
_throttlingDeviceBecameActiveCallbacks = NO;
// If there is a data store, make sure we have an observer to monitor system clock changes, so
// NSDate-based write coalescing could be reset and not get into a bad state.
if (_persistedClusterData) {
mtr_weakify(self);
_systemTimeChangeObserverToken = [[NSNotificationCenter defaultCenter] addObserverForName:NSSystemClockDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull notification) {
mtr_strongify(self);
VerifyOrReturn(self, MTR_LOG_DEBUG("NSNotificationCenter addObserverForName called back with nil MTRDevice"));
std::lock_guard lock(self->_lock);
[self _resetStorageBehaviorState];
}];
}
self.suspended = controller.suspended;
MTR_LOG_DEBUG("%@ init with hex nodeID 0x%016llX", self, _nodeID.unsignedLongLongValue);
}
return self;
}
- (void)dealloc
{
MTR_LOG("MTRDevice dealloc: %p", self);
[[NSNotificationCenter defaultCenter] removeObserver:_systemTimeChangeObserverToken];
#ifdef DEBUG
// Save the first delegate for testing
__block id testDelegate = nil;
for (MTRDeviceDelegateInfo * delegateInfo in _delegates) {
testDelegate = delegateInfo.delegate;
break;
}
#endif
[_delegates removeAllObjects];
// Delete subscription callback object to tear down ReadClient
MTRDeviceMatterCPPObjectsHolder * matterCPPObjectsHolder = self.matterCPPObjectsHolder;
[self._concreteController asyncDispatchToMatterQueue:^{
[matterCPPObjectsHolder clearReadClientAndDeleteSubscriptionCallback];
#ifdef DEBUG
// tell test delegate about having completed the deletion
if ([testDelegate respondsToSelector:@selector(unitTestSubscriptionCallbackDeleteForDevice:)]) {
[testDelegate unitTestSubscriptionCallbackDeleteForDevice:nil];
}
#endif
} errorHandler:nil];
// Clear this device from subscription pool and persist cached data to storage as needed.
std::lock_guard lock(_lock);
[self _clearSubscriptionPoolWork];
[self _doPersistClusterData];
}
- (NSString *)description
{
id _Nullable vid;
id _Nullable pid;
NSNumber * _Nullable networkFeatures;
MTRInternalDeviceState internalDeviceState;
uint32_t lastSubscriptionAttemptWait;
NSDate * _Nullable mostRecentReportTime;
NSDate * _Nullable lastSubscriptionFailureTime;
{
std::lock_guard lock(_descriptionLock);
vid = _vid;
pid = _pid;
networkFeatures = _allNetworkFeatures;
internalDeviceState = _internalDeviceStateForDescription;
lastSubscriptionAttemptWait = _lastSubscriptionAttemptWaitForDescription;
mostRecentReportTime = _mostRecentReportTimeForDescription;
lastSubscriptionFailureTime = _lastSubscriptionFailureTimeForDescription;
}
if (vid == nil) {
vid = @"Unknown";
}
if (pid == nil) {
pid = @"Unknown";
}
NSString * wifi;
NSString * thread;
if (networkFeatures == nil) {
wifi = @"NO";
thread = @"NO";
} else {
wifi = MTR_YES_NO(networkFeatures.unsignedLongLongValue & MTRNetworkCommissioningFeatureWiFiNetworkInterface);
thread = MTR_YES_NO(networkFeatures.unsignedLongLongValue & MTRNetworkCommissioningFeatureThreadNetworkInterface);
}
NSString * reportAge;
if (mostRecentReportTime) {
reportAge = [NSString stringWithFormat:@" (%.0lfs ago)", -[mostRecentReportTime timeIntervalSinceNow]];
} else {
reportAge = @"";
}
NSString * subscriptionFailureAge;
if (lastSubscriptionFailureTime) {
subscriptionFailureAge = [NSString stringWithFormat:@" (%.0lfs ago)", -[lastSubscriptionFailureTime timeIntervalSinceNow]];
} else {
subscriptionFailureAge = @"";
}
return [NSString
stringWithFormat:@"<%@: %p, node: %016llX-%016llX (%llu), VID: %@, PID: %@, WiFi: %@, Thread: %@, state: %@, last subscription attempt wait: %lus, queued work: %lu, last report: %@%@, last subscription failure: %@%@, controller: %@>", NSStringFromClass(self.class), self, _deviceController.compressedFabricID.unsignedLongLongValue, _nodeID.unsignedLongLongValue, _nodeID.unsignedLongLongValue, vid, pid, wifi, thread, InternalDeviceStateString(internalDeviceState), static_cast<unsigned long>(lastSubscriptionAttemptWait), static_cast<unsigned long>(_asyncWorkQueue.itemCount), mostRecentReportTime, reportAge, lastSubscriptionFailureTime, subscriptionFailureAge, _deviceController.uniqueIdentifier];
}
- (NSDictionary *)_internalProperties
{
NSMutableDictionary * properties = [NSMutableDictionary dictionary];
{
std::lock_guard lock(_descriptionLock);
MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyKeyVendorID, _vid, properties);
MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyKeyProductID, _pid, properties);
MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyNetworkFeatures, _allNetworkFeatures, properties);
MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyMostRecentReportTime, _mostRecentReportTimeForDescription, properties);
}
{
std::lock_guard lock(_lock);
MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyDeviceInternalState, [NSNumber numberWithUnsignedInteger:_internalDeviceState], properties);
MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyLastSubscriptionAttemptWait, [NSNumber numberWithUnsignedInt:_lastSubscriptionAttemptWait], properties);
MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyLastSubscriptionFailureTime, _lastSubscriptionFailureTime, properties);
MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyDeviceState, @(_state), properties);
MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyDeviceCachePrimed, @(_deviceCachePrimed), properties);
MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyEstimatedStartTime, _estimatedStartTime, properties);
MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyEstimatedSubscriptionLatency, _estimatedSubscriptionLatency, properties);
}
return properties;
}
- (nullable NSNumber *)vendorID
{
std::lock_guard lock(_descriptionLock);
return [_vid copy];
}
- (nullable NSNumber *)productID
{
std::lock_guard lock(_descriptionLock);
return [_pid copy];
}
- (MTRNetworkCommissioningFeature)networkCommissioningFeatures
{
std::lock_guard lock(_descriptionLock);
return [_allNetworkFeatures unsignedIntValue];
}
- (void)_notifyDelegateOfPrivateInternalPropertiesChanges
{
os_unfair_lock_assert_owner(&self->_lock);
[self _callDelegatesWithBlock:^(id<MTRDeviceDelegate> delegate) {
if ([delegate respondsToSelector:@selector(device:internalStateUpdated:)]) {
[delegate performSelector:@selector(device:internalStateUpdated:) withObject:self withObject:[self _internalProperties]];
}
}];
}
#pragma mark - Time Synchronization
- (void)_setTimeOnDevice
{
NSDate * now = [NSDate date];
// If no date available, error
if (!now) {
MTR_LOG_ERROR("%@ Could not retrieve current date. Unable to setUTCTime on endpoints.", self);
return;
}
uint64_t matterEpochTimeMicroseconds = 0;
if (!DateToMatterEpochMicroseconds(now, matterEpochTimeMicroseconds)) {
MTR_LOG_ERROR("%@ Could not convert NSDate (%@) to Matter Epoch Time. Unable to setUTCTime on endpoints.", self, now);
return;
}
// Set Time on each Endpoint with a Time Synchronization Cluster Server
NSArray<NSNumber *> * endpointsToSync = [self _endpointsWithTimeSyncClusterServer];
for (NSNumber * endpoint in endpointsToSync) {
MTR_LOG_DEBUG("%@ Setting Time on Endpoint %@", self, endpoint);
[self _setUTCTime:matterEpochTimeMicroseconds withGranularity:MTRTimeSynchronizationGranularityMicrosecondsGranularity forEndpoint:endpoint];
// Check how many DST offsets this endpoint supports.
auto dstOffsetsMaxSizePath = [MTRAttributePath attributePathWithEndpointID:endpoint clusterID:@(MTRClusterIDTypeTimeSynchronizationID) attributeID:@(MTRAttributeIDTypeClusterTimeSynchronizationAttributeDSTOffsetListMaxSizeID)];
auto dstOffsetsMaxSize = [self readAttributeWithEndpointID:dstOffsetsMaxSizePath.endpoint clusterID:dstOffsetsMaxSizePath.cluster attributeID:dstOffsetsMaxSizePath.attribute params:nil];
if (dstOffsetsMaxSize == nil) {
// This endpoint does not support TZ, so won't support SetDSTOffset.
MTR_LOG("%@ Unable to SetDSTOffset on endpoint %@, since it does not support the TZ feature", self, endpoint);
continue;
}
auto attrReport = [[MTRAttributeReport alloc] initWithResponseValue:@{
MTRAttributePathKey : dstOffsetsMaxSizePath,
MTRDataKey : dstOffsetsMaxSize,
}
error:nil];
uint8_t maxOffsetCount;
if (attrReport == nil) {
MTR_LOG_ERROR("%@ DSTOffsetListMaxSize value on endpoint %@ is invalid. Defaulting to 1.", self, endpoint);
maxOffsetCount = 1;
} else {
NSNumber * maxOffsetCountAsNumber = attrReport.value;
maxOffsetCount = maxOffsetCountAsNumber.unsignedCharValue;
if (maxOffsetCount == 0) {
MTR_LOG_ERROR("%@ DSTOffsetListMaxSize value on endpoint %@ is 0, which is not allowed. Defaulting to 1.", self, endpoint);
maxOffsetCount = 1;
}
}
auto * dstOffsets = MTRComputeDSTOffsets(maxOffsetCount);
if (dstOffsets == nil) {
MTR_LOG_ERROR("%@ Could not retrieve DST offset information. Unable to setDSTOffset on endpoint %@.", self, endpoint);
continue;
}
[self _setDSTOffsets:dstOffsets forEndpoint:endpoint];
}
}
- (void)_scheduleNextUpdate:(UInt64)nextUpdateInSeconds
{
mtr_weakify(self);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (nextUpdateInSeconds * NSEC_PER_SEC)), self.queue, ^{
mtr_strongify(self);
MTR_LOG_DEBUG("%@ Timer expired, start Device Time Update", self);
if (self) {
[self _performScheduledTimeUpdate];
} else {
MTR_LOG_DEBUG("%@ MTRDevice no longer valid. No Timer Scheduled will be scheduled for a Device Time Update.", self);
return;
}
});
self.timeUpdateScheduled = YES;
MTR_LOG_DEBUG("%@ Timer Scheduled for next Device Time Update, in %llu seconds", self, nextUpdateInSeconds);
}
// Time Updates are a day apart (this can be changed in the future)
#define MTR_DEVICE_TIME_UPDATE_DEFAULT_WAIT_TIME_SEC (24 * 60 * 60)
// assume lock is held
- (void)_updateDeviceTimeAndScheduleNextUpdate
{
os_unfair_lock_assert_owner(&self->_timeSyncLock);
if (self.timeUpdateScheduled) {
MTR_LOG_DEBUG("%@ Device Time Update already scheduled", self);
return;
}
[self _setTimeOnDevice];
[self _scheduleNextUpdate:MTR_DEVICE_TIME_UPDATE_DEFAULT_WAIT_TIME_SEC];
}
- (void)_performScheduledTimeUpdate
{
std::lock_guard lock(_timeSyncLock);
// Device needs to still be reachable
if (self.state != MTRDeviceStateReachable) {
MTR_LOG_DEBUG("%@ Device is not reachable, canceling Device Time Updates.", self);
return;
}
// Device must not be invalidated
if (!self.timeUpdateScheduled) {
MTR_LOG_DEBUG("%@ Device Time Update is no longer scheduled, MTRDevice may have been invalidated.", self);
return;
}
self.timeUpdateScheduled = NO;
[self _updateDeviceTimeAndScheduleNextUpdate];
}
- (NSArray<NSNumber *> *)_endpointsWithTimeSyncClusterServer
{
NSArray<NSNumber *> * endpointsOnDevice;
{
std::lock_guard lock(_lock);
endpointsOnDevice = [self _endpointList];
}
NSMutableArray<NSNumber *> * endpointsWithTimeSyncCluster = [[NSMutableArray<NSNumber *> alloc] init];
for (NSNumber * endpoint in endpointsOnDevice) {
// Get list of server clusters on endpoint
auto clusterList = [self readAttributeWithEndpointID:endpoint clusterID:@(MTRClusterIDTypeDescriptorID) attributeID:@(MTRAttributeIDTypeClusterDescriptorAttributeServerListID) params:nil];
NSArray<NSNumber *> * clusterArray = [self arrayOfNumbersFromAttributeValue:clusterList];
if (clusterArray && [clusterArray containsObject:@(MTRClusterIDTypeTimeSynchronizationID)]) {
[endpointsWithTimeSyncCluster addObject:endpoint];
}
}
MTR_LOG_DEBUG("%@ Device has following endpoints with Time Sync Cluster Server: %@", self, endpointsWithTimeSyncCluster);
return endpointsWithTimeSyncCluster;
}
- (void)_setUTCTime:(UInt64)matterEpochTime withGranularity:(uint8_t)granularity forEndpoint:(NSNumber *)endpoint
{
MTR_LOG_DEBUG(" %@ _setUTCTime with matterEpochTime: %llu, endpoint %@", self, matterEpochTime, endpoint);
MTRTimeSynchronizationClusterSetUTCTimeParams * params = [[MTRTimeSynchronizationClusterSetUTCTimeParams
alloc] init];
params.utcTime = @(matterEpochTime);
params.granularity = @(granularity);
mtr_weakify(self);
auto setUTCTimeResponseHandler = ^(id _Nullable response, NSError * _Nullable error) {
mtr_strongify(self);
if (error) {
MTR_LOG_ERROR("%@ _setUTCTime failed on endpoint %@, with parameters %@, error: %@", self, endpoint, params, error);
}
};
[self _invokeKnownCommandWithEndpointID:endpoint
clusterID:@(MTRClusterIDTypeTimeSynchronizationID)
commandID:@(MTRCommandIDTypeClusterTimeSynchronizationCommandSetUTCTimeID)
commandPayload:params
expectedValues:nil
expectedValueInterval:nil
timedInvokeTimeout:nil
serverSideProcessingTimeout:params.serverSideProcessingTimeout
responseClass:nil
queue:self.queue
completion:setUTCTimeResponseHandler];
}
- (void)_setDSTOffsets:(NSArray<MTRTimeSynchronizationClusterDSTOffsetStruct *> *)dstOffsets forEndpoint:(NSNumber *)endpoint
{
MTR_LOG_DEBUG("%@ _setDSTOffsets with offsets: %@, endpoint %@",
self, dstOffsets, endpoint);
MTRTimeSynchronizationClusterSetDSTOffsetParams * params = [[MTRTimeSynchronizationClusterSetDSTOffsetParams
alloc] init];
params.dstOffset = dstOffsets;
mtr_weakify(self);
auto setDSTOffsetResponseHandler = ^(id _Nullable response, NSError * _Nullable error) {
mtr_strongify(self);
if (error) {
MTR_LOG_ERROR("%@ _setDSTOffsets failed on endpoint %@, with parameters %@, error: %@", self, endpoint, params, error);
}
};
[self _invokeKnownCommandWithEndpointID:endpoint
clusterID:@(MTRClusterIDTypeTimeSynchronizationID)
commandID:@(MTRCommandIDTypeClusterTimeSynchronizationCommandSetDSTOffsetID)
commandPayload:params
expectedValues:nil
expectedValueInterval:nil
timedInvokeTimeout:nil
serverSideProcessingTimeout:params.serverSideProcessingTimeout
responseClass:nil
queue:self.queue
completion:setDSTOffsetResponseHandler];
}
- (NSMutableArray<NSNumber *> *)arrayOfNumbersFromAttributeValue:(MTRDeviceDataValueDictionary)dataDictionary
{
if (![MTRArrayValueType isEqual:dataDictionary[MTRTypeKey]]) {
return nil;
}
id value = dataDictionary[MTRValueKey];
if (![value isKindOfClass:NSArray.class]) {
return nil;
}
NSArray * valueArray = value;
__auto_type outputArray = [NSMutableArray<NSNumber *> arrayWithCapacity:valueArray.count];
for (id item in valueArray) {
if (![item isKindOfClass:NSDictionary.class]) {
return nil;
}
NSDictionary * itemDictionary = item;
id data = itemDictionary[MTRDataKey];
if (![data isKindOfClass:NSDictionary.class]) {
return nil;
}
NSDictionary * dataDictionary = data;
id dataType = dataDictionary[MTRTypeKey];
id dataValue = dataDictionary[MTRValueKey];
if (![dataType isKindOfClass:NSString.class] || ![dataValue isKindOfClass:NSNumber.class]) {
return nil;
}
[outputArray addObject:dataValue];
}
return outputArray;
}
#pragma mark Subscription and delegate handling
// subscription intervals are in seconds
#define MTR_DEVICE_SUBSCRIPTION_MAX_INTERVAL_MIN (10 * 60) // 10 minutes (for now)
#define MTR_DEVICE_SUBSCRIPTION_MAX_INTERVAL_MAX (60 * 60) // 60 minutes
#define MTR_DEVICE_MIN_SECONDS_BETWEEN_DEVICE_BECAME_ACTIVE_CALLBACKS (1 * 60) // 1 minute (for now)
- (BOOL)_subscriptionsAllowed
{
os_unfair_lock_assert_owner(&self->_lock);
// We should not allow a subscription when we are suspended or for device controllers over XPC.
return self.suspended == NO && ![_deviceController isKindOfClass:MTRDeviceControllerOverXPC.class];
}
- (void)_delegateAdded:(id<MTRDeviceDelegate>)delegate
{
os_unfair_lock_assert_owner(&self->_lock);
[super _delegateAdded:delegate];
[self _ensureSubscriptionForExistingDelegates:@"delegate is set"];
}
- (void)_ensureSubscriptionForExistingDelegates:(NSString *)reason
{
os_unfair_lock_assert_owner(&self->_lock);
__block BOOL shouldSetUpSubscription = [self _subscriptionsAllowed];
// For unit testing only. If this ever changes to not being for unit testing purposes,
// we would need to move the code outside of where we acquire the lock above.
#ifdef DEBUG
[self _callFirstDelegateSynchronouslyWithBlock:^(id testDelegate) {
if ([testDelegate respondsToSelector:@selector(unitTestShouldSetUpSubscriptionForDevice:)]) {
shouldSetUpSubscription = [testDelegate unitTestShouldSetUpSubscriptionForDevice:self];
}
}];
#endif
if (shouldSetUpSubscription) {
MTR_LOG("%@ - starting subscription setup", self);
// Record the time of first addDelegate call that triggers initial subscribe, and do not reset this value on subsequent addDelegate calls
if (!_initialSubscribeStart) {
_initialSubscribeStart = [NSDate now];
}
mtr_weakify(self);
if ([self _deviceUsesThread]) {
MTR_LOG(" => %@ - device is a thread device, scheduling in pool", self);
NSString * description = [NSString stringWithFormat:@"MTRDevice setDelegate first subscription / controller resume (%p)", self];
[self _scheduleSubscriptionPoolWork:^{
mtr_strongify(self);
VerifyOrReturn(self, MTR_LOG_DEBUG("_ensureSubscriptionForExistingDelegates _scheduleSubscriptionPoolWork called back with nil MTRDevice"));
[self->_deviceController asyncDispatchToMatterQueue:^{
mtr_strongify(self);
VerifyOrReturn(self, MTR_LOG_DEBUG("_ensureSubscriptionForExistingDelegates asyncDispatchToMatterQueue called back with nil MTRDevice"));
std::lock_guard lock(self->_lock);
[self _setupSubscriptionWithReason:[NSString stringWithFormat:@"%@ and scheduled subscription is happening", reason]];
} errorHandler:^(NSError * _Nonnull error) {
mtr_strongify(self);
VerifyOrReturn(self, MTR_LOG_DEBUG("_ensureSubscriptionForExistingDelegates asyncDispatchToMatterQueue errored with nil MTRDevice"));
// If controller is not running, clear work item from the subscription queue
MTR_LOG_ERROR("%@ could not dispatch to matter queue for resubscription - error %@", self, error);
std::lock_guard lock(self->_lock);
[self _clearSubscriptionPoolWork];
}];
} inNanoseconds:0 description:description];
} else {
[_deviceController asyncDispatchToMatterQueue:^{
mtr_strongify(self);
VerifyOrReturn(self, MTR_LOG_DEBUG("_ensureSubscriptionForExistingDelegates asyncDispatchToMatterQueue called back with nil MTRDevice"));
std::lock_guard lock(self->_lock);
[self _setupSubscriptionWithReason:[NSString stringWithFormat:@"%@ and subscription is needed", reason]];
} errorHandler:nil];
}
}
}
- (void)invalidate
{
MTR_LOG("%@ invalidate", self);
[_asyncWorkQueue invalidate];
os_unfair_lock_lock(&self->_timeSyncLock);
_timeUpdateScheduled = NO;
os_unfair_lock_unlock(&self->_timeSyncLock);
os_unfair_lock_lock(&self->_lock);
// Flush unstored attributes if any
[self _persistClusterData];
_state = MTRDeviceStateUnknown;
// Make sure we don't try to resubscribe if we have a pending resubscribe
// attempt, since we now have no delegate.
_reattemptingSubscription = NO;
// Clear subscription pool work item if it's in progress, to avoid forever
// taking up a slot in the controller's work queue.
[self _clearSubscriptionPoolWork];
mtr_weakify(self);
[_deviceController asyncDispatchToMatterQueue:^{
mtr_strongify(self);
VerifyOrReturn(self, MTR_LOG_DEBUG("invalidate asyncDispatchToMatterQueue called back with nil MTRDevice"));
MTR_LOG("%@ invalidate disconnecting ReadClient and SubscriptionCallback", self);
// Destroy the read client and callback (has to happen on the Matter
// queue, to avoid deleting objects that are being referenced), to
// tear down the subscription. We will get no more callbacks from
// the subscription after this point.
std::lock_guard lock(self->_lock);
[self _resetSubscription];
}
errorHandler:nil];
[self _stopConnectivityMonitoring];