From ee7183385396382663b6bd8bff66ba85dbb74b11 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Tue, 29 Oct 2024 18:02:46 +0100 Subject: [PATCH 001/121] [chip-tool][interactive] Add quit as an alias for quit() (#36283) --- .../interactive/InteractiveCommands.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/examples/chip-tool/commands/interactive/InteractiveCommands.cpp b/examples/chip-tool/commands/interactive/InteractiveCommands.cpp index 92861f7711d566..7c843cc900b07a 100644 --- a/examples/chip-tool/commands/interactive/InteractiveCommands.cpp +++ b/examples/chip-tool/commands/interactive/InteractiveCommands.cpp @@ -25,13 +25,14 @@ #include #include -constexpr char kInteractiveModePrompt[] = ">>> "; -constexpr char kInteractiveModeHistoryFileName[] = "chip_tool_history"; -constexpr char kInteractiveModeStopCommand[] = "quit()"; -constexpr char kCategoryError[] = "Error"; -constexpr char kCategoryProgress[] = "Info"; -constexpr char kCategoryDetail[] = "Debug"; -constexpr char kCategoryAutomation[] = "Automation"; +constexpr char kInteractiveModePrompt[] = ">>> "; +constexpr char kInteractiveModeHistoryFileName[] = "chip_tool_history"; +constexpr char kInteractiveModeStopCommand[] = "quit()"; +constexpr char kInteractiveModeStopAlternateCommand[] = "quit"; +constexpr char kCategoryError[] = "Error"; +constexpr char kCategoryProgress[] = "Info"; +constexpr char kCategoryDetail[] = "Debug"; +constexpr char kCategoryAutomation[] = "Automation"; namespace { @@ -387,7 +388,7 @@ CHIP_ERROR InteractiveStartCommand::RunCommand() bool InteractiveCommand::ParseCommand(char * command, int * status) { - if (strcmp(command, kInteractiveModeStopCommand) == 0) + if (strcmp(command, kInteractiveModeStopCommand) == 0 || strcmp(command, kInteractiveModeStopAlternateCommand) == 0) { // If scheduling the cleanup fails, there is not much we can do. // But if something went wrong while the application is leaving it could be because things have From 0f5f31da7802a83a602d400233a904377f2b204b Mon Sep 17 00:00:00 2001 From: Jeff Tung <100387939+jtung-apple@users.noreply.github.com> Date: Tue, 29 Oct 2024 10:56:26 -0700 Subject: [PATCH 002/121] [Darwin] Internal state plumbing for the _XPC classes (#35962) * Updating this * Restyled by clang-format * Removing bad rebase * Update src/darwin/Framework/CHIP/MTRDevice_XPC.mm * Fixing format * Fixing format * Restyled by clang-format * Fixing * Restyled by clang-format * fixing bad merge * fixing bad merge * Apply suggestions from code review * Remove unnecessary MTRDevice_Concrete changes. --------- Co-authored-by: Justin Wood Co-authored-by: Restyled.io Co-authored-by: Boris Zbarsky --- .../Framework/CHIP/MTRDeviceController.mm | 2 +- .../Framework/CHIP/MTRDeviceController_XPC.mm | 69 +++++++++++- .../Framework/CHIP/MTRDevice_Concrete.mm | 34 ++++-- .../Framework/CHIP/MTRDevice_Internal.h | 6 +- src/darwin/Framework/CHIP/MTRDevice_XPC.mm | 103 +++++++++++------- .../CHIP/XPC Protocol/MTRXPCClientProtocol.h | 2 + .../CHIP/XPC Protocol/MTRXPCServerProtocol.h | 9 +- .../Matter.xcodeproj/project.pbxproj | 8 +- 8 files changed, 168 insertions(+), 65 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index 5695ef23c7a9e7..8b8295d94450c2 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -714,7 +714,7 @@ - (NSUInteger)_iterateDelegateInfoWithBlock:(void (^_Nullable)(MTRDeviceControll } } -- (void)_callDelegatesWithBlock:(void (^_Nullable)(id delegate))block logString:(const char *)logString; +- (void)_callDelegatesWithBlock:(void (^_Nullable)(id delegate))block logString:(const char *)logString { NSUInteger delegatesCalled = [self _iterateDelegateInfoWithBlock:^(MTRDeviceControllerDelegateInfo * delegateInfo) { id strongDelegate = delegateInfo.delegate; diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm index 7e88870aa7b570..d737e4d95d9856 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -43,6 +43,9 @@ @interface MTRDeviceController_XPC () NSString * const MTRDeviceControllerRegistrationControllerContextKey = @"MTRDeviceControllerRegistrationControllerContext"; NSString * const MTRDeviceControllerRegistrationNodeIDsKey = @"MTRDeviceControllerRegistrationNodeIDs"; NSString * const MTRDeviceControllerRegistrationNodeIDKey = @"MTRDeviceControllerRegistrationNodeID"; +NSString * const MTRDeviceControllerRegistrationControllerNodeIDKey = @"MTRDeviceControllerRegistrationControllerNodeID"; +NSString * const MTRDeviceControllerRegistrationControllerIsRunningKey = @"MTRDeviceControllerRegistrationControllerIsRunning"; +NSString * const MTRDeviceControllerRegistrationDeviceInternalStateKey = @"MTRDeviceControllerRegistrationDeviceInternalState"; // #define MTR_HAVE_MACH_SERVICE_NAME_CONSTRUCTOR @@ -90,6 +93,8 @@ - (void)removeDevice:(MTRDevice *)device } #pragma mark - XPC +@synthesize controllerNodeID = _controllerNodeID; + + (NSMutableSet *)_allowedClasses { static NSArray * sBaseAllowedClasses = @[ @@ -167,6 +172,13 @@ - (NSXPCInterface *)_interfaceForClientProtocol argumentIndex:1 ofReply:NO]; + allowedClasses = [MTRDeviceController_XPC _allowedClasses]; + + [interface setClasses:allowedClasses + forSelector:@selector(controller:controllerConfigurationUpdated:) + argumentIndex:1 + ofReply:NO]; + return interface; } @@ -346,9 +358,6 @@ - (MTRDevice *)_setupDeviceForNodeID:(NSNumber *)nodeID prefetchedClusterData:(N #pragma mark - XPC Action Overrides -MTR_DEVICECONTROLLER_SIMPLE_REMOTE_XPC_GETTER(isRunning, BOOL, NO, getIsRunningWithReply) -MTR_DEVICECONTROLLER_SIMPLE_REMOTE_XPC_GETTER(controllerNodeID, NSNumber *, nil, controllerNodeIDWithReply) - // Not Supported via XPC // - (oneway void)deviceController:(NSUUID *)controller setupCommissioningSessionWithPayload:(MTRSetupPayload *)payload newNodeID:(NSNumber *)newNodeID withReply:(void(^)(BOOL success, NSError * _Nullable error))reply; // - (oneway void)deviceController:(NSUUID *)controller setupCommissioningSessionWithDiscoveredDevice:(MTRCommissionableBrowserResult *)discoveredDevice payload:(MTRSetupPayload *)payload newNodeID:(NSNumber *)newNodeID withReply:(void(^)(BOOL success, NSError * _Nullable error))reply; @@ -424,6 +433,60 @@ - (oneway void)device:(NSNumber *)nodeID internalStateUpdated:(NSDictionary *)di #pragma mark - MTRDeviceController Protocol Client +- (oneway void)controller:(NSUUID *)controller controllerConfigurationUpdated:(NSDictionary *)configuration +{ + // Reuse the same format as config dictionary, and add values for internal states + // @{ + // MTRDeviceControllerRegistrationControllerContextKey: @{ + // MTRDeviceControllerRegistrationControllerNodeIDKey: controllerNodeID + // } + // MTRDeviceControllerRegistrationNodeIDsKey: @[ + // @{ + // MTRDeviceControllerRegistrationNodeIDKey: nodeID, + // MTRDeviceControllerRegistrationDeviceInternalStateKey: deviceInternalStateDictionary + // } + // ] + // } + + NSDictionary * controllerContext = MTR_SAFE_CAST(configuration[MTRDeviceControllerRegistrationControllerContextKey], NSDictionary); + NSNumber * controllerNodeID = MTR_SAFE_CAST(controllerContext[MTRDeviceControllerRegistrationControllerNodeIDKey], NSNumber); + if (controllerContext && controllerNodeID) { + _controllerNodeID = controllerContext[MTRDeviceControllerRegistrationControllerNodeIDKey]; + } + + NSArray * deviceInfoList = MTR_SAFE_CAST(configuration[MTRDeviceControllerRegistrationNodeIDsKey], NSArray); + + MTR_LOG("Received controllerConfigurationUpdated: controllerNode ID %@ deviceInfoList %@", self.controllerNodeID, deviceInfoList); + + for (NSDictionary * deviceInfo in deviceInfoList) { + if (!MTR_SAFE_CAST(deviceInfo, NSDictionary)) { + MTR_LOG_ERROR(" - Missing or malformed device Info"); + continue; + } + + NSNumber * nodeID = MTR_SAFE_CAST(deviceInfo[MTRDeviceControllerRegistrationNodeIDKey], NSNumber); + if (!nodeID) { + MTR_LOG_ERROR(" - Missing or malformed nodeID"); + continue; + } + + NSDictionary * deviceInternalState = MTR_SAFE_CAST(deviceInfo[MTRDeviceControllerRegistrationDeviceInternalStateKey], NSDictionary); + if (!deviceInternalState) { + MTR_LOG_ERROR(" - Missing or malformed deviceInternalState"); + continue; + } + + auto * device = static_cast([self deviceForNodeID:nodeID]); + [device device:nodeID internalStateUpdated:deviceInternalState]; + } +} + +- (BOOL)isRunning +{ + // For XPC controller, always return yes + return YES; +} + // Not Supported via XPC //- (oneway void)controller:(NSUUID *)controller statusUpdate:(MTRCommissioningStatus)status { // } diff --git a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm index 12b6250e0bcadb..a7b5d255f8772d 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm @@ -475,15 +475,26 @@ - (NSString *)description - (NSDictionary *)_internalProperties { NSMutableDictionary * properties = [NSMutableDictionary dictionary]; - std::lock_guard lock(_descriptionLock); + { + 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(kMTRDeviceInternalPropertyDeviceState, [NSNumber numberWithUnsignedInteger:_internalDeviceStateForDescription], properties); - MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyLastSubscriptionAttemptWait, [NSNumber numberWithUnsignedInt:_lastSubscriptionAttemptWaitForDescription], properties); - MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyMostRecentReportTime, _mostRecentReportTimeForDescription, properties); - MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyLastSubscriptionFailureTime, _lastSubscriptionFailureTimeForDescription, properties); + 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; } @@ -968,6 +979,7 @@ - (void)_callDelegateDeviceCachePrimed [delegate deviceCachePrimed:self]; } }]; + [self _notifyDelegateOfPrivateInternalPropertiesChanges]; } // assume lock is held @@ -998,6 +1010,7 @@ - (void)_changeState:(MTRDeviceState)state [self _callDelegatesWithBlock:^(id delegate) { [delegate device:self stateChanged:state]; }]; + [self _notifyDelegateOfPrivateInternalPropertiesChanges]; } else { MTR_LOG( "%@ Not reporting reachability state change, since no change in state %lu => %lu", self, static_cast(lastState), static_cast(state)); @@ -1438,6 +1451,7 @@ - (void)_handleUnsolicitedMessageFromPublisher [delegate deviceBecameActive:self]; } }]; + [self _notifyDelegateOfPrivateInternalPropertiesChanges]; // in case this is called during exponential back off of subscription // reestablishment, this starts the attempt right away @@ -2423,7 +2437,9 @@ - (void)_setupSubscriptionWithReason:(NSString *)reason mtr_strongify(self); VerifyOrReturn(self); - [self _markDeviceAsUnreachableIfNeverSubscribed]; + if (!HaveSubscriptionEstablishedRightNow(self->_internalDeviceState)) { + [self _markDeviceAsUnreachableIfNeverSubscribed]; + } }); } diff --git a/src/darwin/Framework/CHIP/MTRDevice_Internal.h b/src/darwin/Framework/CHIP/MTRDevice_Internal.h index 35cc25e26949da..f162e43e4d683d 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDevice_Internal.h @@ -187,9 +187,13 @@ static NSString * const kTestStorageUserDefaultEnabledKey = @"enableTestStorage" static NSString * const kMTRDeviceInternalPropertyKeyVendorID = @"MTRDeviceInternalStateKeyVendorID"; static NSString * const kMTRDeviceInternalPropertyKeyProductID = @"MTRDeviceInternalStateKeyProductID"; static NSString * const kMTRDeviceInternalPropertyNetworkFeatures = @"MTRDeviceInternalPropertyNetworkFeatures"; -static NSString * const kMTRDeviceInternalPropertyDeviceState = @"MTRDeviceInternalPropertyDeviceState"; +static NSString * const kMTRDeviceInternalPropertyDeviceInternalState = @"MTRDeviceInternalPropertyDeviceInternalState"; static NSString * const kMTRDeviceInternalPropertyLastSubscriptionAttemptWait = @"kMTRDeviceInternalPropertyLastSubscriptionAttemptWait"; static NSString * const kMTRDeviceInternalPropertyMostRecentReportTime = @"MTRDeviceInternalPropertyMostRecentReportTime"; static NSString * const kMTRDeviceInternalPropertyLastSubscriptionFailureTime = @"MTRDeviceInternalPropertyLastSubscriptionFailureTime"; +static NSString * const kMTRDeviceInternalPropertyDeviceState = @"MTRDeviceInternalPropertyDeviceState"; +static NSString * const kMTRDeviceInternalPropertyDeviceCachePrimed = @"MTRDeviceInternalPropertyDeviceCachePrimed"; +static NSString * const kMTRDeviceInternalPropertyEstimatedStartTime = @"MTRDeviceInternalPropertyEstimatedStartTime"; +static NSString * const kMTRDeviceInternalPropertyEstimatedSubscriptionLatency = @"MTRDeviceInternalPropertyEstimatedSubscriptionLatency"; NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm index 8a5f745a1dfc70..ec156cdcc5c0b3 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_XPC.mm @@ -56,6 +56,7 @@ #import "MTRSetupPayload.h" #import "MTRTimeUtils.h" #import "MTRUnfairLock.h" +#import "MTRUtilities.h" #import "NSDataSpanConversion.h" #import "NSStringSpanConversion.h" @@ -113,22 +114,21 @@ - (NSString *)description } // TODO: Add these to the description - // MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyDeviceState, _internalDeviceStateForDescription, properties); // MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyLastSubscriptionAttemptWait, _lastSubscriptionAttemptWaitForDescription, properties); // MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyMostRecentReportTime, _mostRecentReportTimeForDescription, properties); // MTR_OPTIONAL_ATTRIBUTE(kMTRDeviceInternalPropertyLastSubscriptionFailureTime, _lastSubscriptionFailureTimeForDescription, properties); - return [NSString - stringWithFormat:@"<%@: %p, node: %016llX-%016llX (%llu), VID: %@, PID: %@, WiFi: %@, Thread: %@, controller: %@>", - NSStringFromClass(self.class), self, - _deviceController.compressedFabricID.unsignedLongLongValue, - _nodeID.unsignedLongLongValue, - _nodeID.unsignedLongLongValue, - [self._internalState objectForKey:kMTRDeviceInternalPropertyKeyVendorID], - [self._internalState objectForKey:kMTRDeviceInternalPropertyKeyProductID], - wifi, - thread, - _deviceController.uniqueIdentifier]; + return [NSString stringWithFormat:@"<%@: %p, node: %016llX-%016llX (%llu), VID: %@, PID: %@, WiFi: %@, Thread: %@, controller: %@ state: %lu>", + NSStringFromClass(self.class), self, + _deviceController.compressedFabricID.unsignedLongLongValue, + _nodeID.unsignedLongLongValue, + _nodeID.unsignedLongLongValue, + [self vendorID], + [self productID], + wifi, + thread, + _deviceController.uniqueIdentifier, + (unsigned long) self.state]; } - (nullable NSNumber *)vendorID @@ -146,19 +146,12 @@ - (nullable NSNumber *)productID // required methods for MTRDeviceDelegates - (oneway void)device:(NSNumber *)nodeID stateChanged:(MTRDeviceState)state { - if (!MTR_SAFE_CAST(nodeID, NSNumber)) { - MTR_LOG_ERROR("%@ invalid device:stateChanged: nodeID: %@", self, nodeID); - return; - } - - MTR_LOG("%s", __PRETTY_FUNCTION__); - [self _lockAndCallDelegatesWithBlock:^(id delegate) { - [delegate device:self stateChanged:state]; - }]; + // Not needed, since internal will get this } - (oneway void)device:(NSNumber *)nodeID receivedAttributeReport:(NSArray *)attributeReport { + MTR_LOG("%@ %s", self, __PRETTY_FUNCTION__); if (!MTR_SAFE_CAST(nodeID, NSNumber)) { MTR_LOG_ERROR("%@ invalid device:receivedAttributeReport: nodeID: %@", self, nodeID); return; @@ -169,7 +162,6 @@ - (oneway void)device:(NSNumber *)nodeID receivedAttributeReport:(NSArray delegate) { [delegate device:self receivedAttributeReport:attributeReport]; }]; @@ -177,6 +169,7 @@ - (oneway void)device:(NSNumber *)nodeID receivedAttributeReport:(NSArray *)eventReport { + MTR_LOG("%@ %s", self, __PRETTY_FUNCTION__); if (!MTR_SAFE_CAST(nodeID, NSNumber)) { MTR_LOG_ERROR("%@ invalid device:receivedEventReport: nodeID: %@", self, nodeID); return; @@ -187,7 +180,6 @@ - (oneway void)device:(NSNumber *)nodeID receivedEventReport:(NSArray delegate) { [delegate device:self receivedEventReport:eventReport]; }]; @@ -196,12 +188,12 @@ - (oneway void)device:(NSNumber *)nodeID receivedEventReport:(NSArray delegate) { if ([delegate respondsToSelector:@selector(deviceBecameActive:)]) { [delegate deviceBecameActive:self]; @@ -211,20 +203,12 @@ - (oneway void)deviceBecameActive:(NSNumber *)nodeID - (oneway void)deviceCachePrimed:(NSNumber *)nodeID { - if (!MTR_SAFE_CAST(nodeID, NSNumber)) { - MTR_LOG_ERROR("%@ invalid deviceCachePrimed: nodeID: %@", self, nodeID); - return; - } - - [self _lockAndCallDelegatesWithBlock:^(id delegate) { - if ([delegate respondsToSelector:@selector(deviceCachePrimed:)]) { - [delegate deviceCachePrimed:self]; - } - }]; + // Not needed since this is a state update now } - (oneway void)deviceConfigurationChanged:(NSNumber *)nodeID { + MTR_LOG("%@ %s", self, __PRETTY_FUNCTION__); if (!MTR_SAFE_CAST(nodeID, NSNumber)) { MTR_LOG_ERROR("%@ invalid deviceConfigurationChanged: nodeID: %@", self, nodeID); return; @@ -264,6 +248,7 @@ - (BOOL)_internalState:(NSDictionary *)dictionary hasValidValuesForKeys:(const N - (oneway void)device:(NSNumber *)nodeID internalStateUpdated:(NSDictionary *)dictionary { + MTR_LOG("%@ %s", self, __PRETTY_FUNCTION__); if (!MTR_SAFE_CAST(nodeID, NSNumber)) { MTR_LOG_ERROR("%@ invalid device:internalStateUpdated: nodeID: %@", self, nodeID); return; @@ -274,22 +259,56 @@ - (oneway void)device:(NSNumber *)nodeID internalStateUpdated:(NSDictionary *)di return; } + NSNumber * oldStateNumber = MTR_SAFE_CAST(self._internalState[kMTRDeviceInternalPropertyDeviceState], NSNumber); + NSNumber * newStateNumber = MTR_SAFE_CAST(dictionary[kMTRDeviceInternalPropertyDeviceState], NSNumber); + VerifyOrReturn([self _internalState:dictionary hasValidValuesForKeys:requiredInternalStateKeys valueRequired:YES]); VerifyOrReturn([self _internalState:dictionary hasValidValuesForKeys:optionalInternalStateKeys valueRequired:NO]); [self _setInternalState:dictionary]; - MTR_LOG("%@ internal state updated", self); + + if (!MTREqualObjects(oldStateNumber, newStateNumber)) { + MTRDeviceState state = self.state; + [self _lockAndCallDelegatesWithBlock:^(id delegate) { + [delegate device:self stateChanged:state]; + }]; + } + + NSNumber * oldPrimedState = MTR_SAFE_CAST(self._internalState[kMTRDeviceInternalPropertyDeviceCachePrimed], NSNumber); + NSNumber * newPrimedState = MTR_SAFE_CAST(dictionary[kMTRDeviceInternalPropertyDeviceCachePrimed], NSNumber); + + if (!MTREqualObjects(oldPrimedState, newPrimedState)) { + [self _lockAndCallDelegatesWithBlock:^(id delegate) { + if ([delegate respondsToSelector:@selector(deviceCachePrimed:)]) { + [delegate deviceCachePrimed:self]; + } + }]; + } } -#pragma mark - Remote Commands +- (MTRDeviceState)state +{ + NSNumber * stateNumber = MTR_SAFE_CAST(self._internalState[kMTRDeviceInternalPropertyDeviceState], NSNumber); + return stateNumber ? static_cast(stateNumber.unsignedIntegerValue) : MTRDeviceStateUnknown; +} + +- (BOOL)deviceCachePrimed +{ + NSNumber * deviceCachePrimedNumber = MTR_SAFE_CAST(self._internalState[kMTRDeviceInternalPropertyDeviceCachePrimed], NSNumber); + return deviceCachePrimedNumber.boolValue; +} + +- (nullable NSDate *)estimatedStartTime +{ + return MTR_SAFE_CAST(self._internalState[kMTRDeviceInternalPropertyEstimatedStartTime], NSDate); +} -// TODO: Figure out how to validate the return values for the various -// MTR_DEVICE_*_XPC macros below. +- (nullable NSNumber *)estimatedSubscriptionLatency +{ + return MTR_SAFE_CAST(self._internalState[kMTRDeviceInternalPropertyEstimatedSubscriptionLatency], NSNumber); +} -MTR_DEVICE_SIMPLE_REMOTE_XPC_GETTER(state, MTRDeviceState, MTRDeviceStateUnknown, getStateWithReply) -MTR_DEVICE_SIMPLE_REMOTE_XPC_GETTER(deviceCachePrimed, BOOL, NO, getDeviceCachePrimedWithReply) -MTR_DEVICE_SIMPLE_REMOTE_XPC_GETTER(estimatedStartTime, NSDate * _Nullable, nil, getEstimatedStartTimeWithReply) -MTR_DEVICE_SIMPLE_REMOTE_XPC_GETTER(estimatedSubscriptionLatency, NSNumber * _Nullable, nil, getEstimatedSubscriptionLatencyWithReply) +#pragma mark - Remote Commands typedef NSDictionary * _Nullable ReadAttributeResponseType; MTR_DEVICE_COMPLEX_REMOTE_XPC_GETTER(readAttributeWithEndpointID diff --git a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h index cfa59db8a73303..bd9048e4595f81 100644 --- a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h +++ b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h @@ -37,6 +37,8 @@ MTR_NEWLY_AVAILABLE //- (oneway void)controller:(NSUUID *)controller commissioningSessionEstablishmentDone:(NSError * _Nullable)error; //- (oneway void)controller:(NSUUID *)controller commissioningComplete:(NSError * _Nullable)error nodeID:(NSNumber * _Nullable)nodeID metrics:(MTRMetrics * _Nullable)metrics; //- (oneway void)controller:(NSUUID *)controller readCommissioningInfo:(MTRProductIdentity *)info; +@optional +- (oneway void)controller:(NSUUID *)controller controllerConfigurationUpdated:(NSDictionary *)configuration; @end MTR_NEWLY_AVAILABLE diff --git a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h index 9ecec60ae52a41..1a468a133264bb 100644 --- a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h +++ b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h @@ -21,6 +21,9 @@ NS_ASSUME_NONNULL_BEGIN MTR_EXTERN NSString * const MTRDeviceControllerRegistrationNodeIDsKey MTR_NEWLY_AVAILABLE; MTR_EXTERN NSString * const MTRDeviceControllerRegistrationNodeIDKey MTR_NEWLY_AVAILABLE; MTR_EXTERN NSString * const MTRDeviceControllerRegistrationControllerContextKey MTR_NEWLY_AVAILABLE; +MTR_EXTERN NSString * const MTRDeviceControllerRegistrationControllerNodeIDKey MTR_NEWLY_AVAILABLE; +MTR_EXTERN NSString * const MTRDeviceControllerRegistrationControllerIsRunningKey MTR_NEWLY_AVAILABLE; +MTR_EXTERN NSString * const MTRDeviceControllerRegistrationDeviceInternalStateKey MTR_NEWLY_AVAILABLE; MTR_NEWLY_AVAILABLE @protocol MTRXPCServerProtocol_MTRDevice @@ -54,10 +57,6 @@ MTR_NEWLY_AVAILABLE @protocol MTRXPCServerProtocol_MTRDeviceController @optional -- (oneway void)deviceController:(NSUUID *)controller getIsRunningWithReply:(void (^)(BOOL response))reply; -- (oneway void)deviceController:(NSUUID *)controller getUniqueIdentifierWithReply:(void (^)(NSUUID *))reply; -- (oneway void)deviceController:(NSUUID *)controller controllerNodeIDWithReply:(void (^)(NSNumber * nodeID))reply; - // - (oneway void)deviceController:(NSUUID *)controller setupCommissioningSessionWithPayload:(MTRSetupPayload *)payload newNodeID:(NSNumber *)newNodeID withReply:(void (^)(BOOL success, NSError * _Nullable error))reply; // - (oneway void)deviceController:(NSUUID *)controller setupCommissioningSessionWithDiscoveredDevice:(MTRCommissionableBrowserResult *)discoveredDevice payload:(MTRSetupPayload *)payload newNodeID:(NSNumber *)newNodeID withReply:(void (^)(BOOL success, NSError * _Nullable error))reply; // - (oneway void)deviceController:(NSUUID *)controller commissionNodeWithID:(NSNumber *)nodeID commissioningParams:(MTRCommissioningParameters *)commissioningParams withReply:(void (^)(BOOL success, NSError * _Nullable error))reply; @@ -73,6 +72,7 @@ MTR_NEWLY_AVAILABLE - (oneway void)deviceController:(NSUUID *)controller registerNodeID:(NSNumber *)nodeID; - (oneway void)deviceController:(NSUUID *)controller unregisterNodeID:(NSNumber *)nodeID; +- (oneway void)deviceController:(NSUUID *)controller updateControllerConfiguration:(NSDictionary *)controllerState; @end @@ -80,7 +80,6 @@ MTR_NEWLY_AVAILABLE @protocol MTRXPCServerProtocol @optional - (oneway void)deviceController:(NSUUID *)controller checkInWithContext:(NSDictionary *)context; -- (oneway void)deviceController:(NSUUID *)controller updateControllerConfiguration:(NSDictionary *)controllerState; @end NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index 673f1cacaabc10..a21e90d726ec0b 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -1322,8 +1322,6 @@ isa = PBXGroup; children = ( D444F9A12C6E8058007761E5 /* XPC Protocol */, - 9B231B032C62EF650030EB37 /* MTRDeviceController_Concrete.mm */, - 9B0484F42C701154006C2D5F /* MTRDeviceController_Concrete.h */, 88E07D602B9A89A4005FD53E /* MTRMetricKeys.h */, 88FA798B2B7B257100CD4B6F /* MTRMetricsCollector.h */, 88FA798C2B7B257100CD4B6F /* MTRMetricsCollector.mm */, @@ -1404,11 +1402,13 @@ 75B3269B2BCDB9D600E17C4E /* MTRDeviceConnectivityMonitor.h */, 75B3269D2BCDB9EA00E17C4E /* MTRDeviceConnectivityMonitor.mm */, 991DC0822475F45400C13860 /* MTRDeviceController.h */, + 5136660F28067D540025EDAE /* MTRDeviceController_Internal.h */, + 991DC0872475F47D00C13860 /* MTRDeviceController.mm */, + 9B0484F42C701154006C2D5F /* MTRDeviceController_Concrete.h */, + 9B231B032C62EF650030EB37 /* MTRDeviceController_Concrete.mm */, 9BFE5D4E2C6D3075007D4319 /* MTRDeviceController_XPC.h */, 9B5CCB582C6E6FD3009DD99B /* MTRDeviceController_XPC_Internal.h */, 9BFE5D4F2C6D3075007D4319 /* MTRDeviceController_XPC.mm */, - 5136660F28067D540025EDAE /* MTRDeviceController_Internal.h */, - 991DC0872475F47D00C13860 /* MTRDeviceController.mm */, 5A7947E227C0101200434CF2 /* MTRDeviceController+XPC.h */, 5A7947E327C0129500434CF2 /* MTRDeviceController+XPC.mm */, 2CB7163E252F731E0026E2BB /* MTRDeviceControllerDelegate.h */, From 4ed1e884f22d41cd9769e4e51a784bfd055d12fa Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Tue, 29 Oct 2024 18:57:35 +0100 Subject: [PATCH 003/121] [darwin-framework-tool] Enable leak checking by default if built for mac with ASan disabled (#36282) --- examples/darwin-framework-tool/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/darwin-framework-tool/BUILD.gn b/examples/darwin-framework-tool/BUILD.gn index 1c492ba10a1241..f5333c9f42c4e1 100644 --- a/examples/darwin-framework-tool/BUILD.gn +++ b/examples/darwin-framework-tool/BUILD.gn @@ -45,7 +45,7 @@ declare_args() { generate_compilation_database = false # Enable automatic leak checks before the application exits - enable_leak_checking = false + enable_leak_checking = !is_asan && target_os == "mac" } sdk = "macosx" From 1285f6b5e186e75a2bce122f0b65848798618714 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Tue, 29 Oct 2024 11:12:55 -0700 Subject: [PATCH 004/121] Rename CommissionerControl to CommissionerControlDelegate (#36280) --- examples/fabric-bridge-app/linux/BUILD.gn | 2 +- ...trol.cpp => CommissionerControlDelegate.cpp} | 2 +- ...rControl.h => CommissionerControlDelegate.h} | 0 examples/fabric-bridge-app/linux/main.cpp | 17 ++++++++--------- 4 files changed, 10 insertions(+), 11 deletions(-) rename examples/fabric-bridge-app/linux/{CommissionerControl.cpp => CommissionerControlDelegate.cpp} (99%) rename examples/fabric-bridge-app/linux/include/{CommissionerControl.h => CommissionerControlDelegate.h} (100%) diff --git a/examples/fabric-bridge-app/linux/BUILD.gn b/examples/fabric-bridge-app/linux/BUILD.gn index d0e92a408ee00e..aec152497ae1a2 100644 --- a/examples/fabric-bridge-app/linux/BUILD.gn +++ b/examples/fabric-bridge-app/linux/BUILD.gn @@ -33,7 +33,7 @@ if (bridge_enable_pw_rpc) { executable("fabric-bridge-app") { sources = [ "${chip_root}/examples/fabric-bridge-app/fabric-bridge-common/include/CHIPProjectAppConfig.h", - "CommissionerControl.cpp", + "CommissionerControlDelegate.cpp", "main.cpp", ] diff --git a/examples/fabric-bridge-app/linux/CommissionerControl.cpp b/examples/fabric-bridge-app/linux/CommissionerControlDelegate.cpp similarity index 99% rename from examples/fabric-bridge-app/linux/CommissionerControl.cpp rename to examples/fabric-bridge-app/linux/CommissionerControlDelegate.cpp index 138e1129b82273..8a5c5af3db0566 100644 --- a/examples/fabric-bridge-app/linux/CommissionerControl.cpp +++ b/examples/fabric-bridge-app/linux/CommissionerControlDelegate.cpp @@ -16,7 +16,7 @@ * limitations under the License. */ -#include "CommissionerControl.h" +#include "CommissionerControlDelegate.h" #include "RpcClient.h" #include diff --git a/examples/fabric-bridge-app/linux/include/CommissionerControl.h b/examples/fabric-bridge-app/linux/include/CommissionerControlDelegate.h similarity index 100% rename from examples/fabric-bridge-app/linux/include/CommissionerControl.h rename to examples/fabric-bridge-app/linux/include/CommissionerControlDelegate.h diff --git a/examples/fabric-bridge-app/linux/main.cpp b/examples/fabric-bridge-app/linux/main.cpp index a101fd3d32a91a..574053424f7895 100644 --- a/examples/fabric-bridge-app/linux/main.cpp +++ b/examples/fabric-bridge-app/linux/main.cpp @@ -23,7 +23,7 @@ #include "BridgedDeviceBasicInformationImpl.h" #include "BridgedDeviceManager.h" #include "CommissionableInit.h" -#include "CommissionerControl.h" +#include "CommissionerControlDelegate.h" #include #include @@ -35,6 +35,12 @@ #include "RpcServer.h" #endif +using namespace chip; +using namespace chip::app; +using namespace chip::app::Clusters; +using namespace chip::app::Clusters::AdministratorCommissioning; +using namespace chip::app::Clusters::BridgedDeviceBasicInformation; + // This is declared here and not in a header because zap/embr assumes all clusters // are defined in a static endpoint in the .zap file. From there, the codegen will // automatically use PluginApplicationCallbacksHeader.jinja to declare and call @@ -43,12 +49,6 @@ // need to declare and call it ourselves where the application is initialized. void MatterEcosystemInformationPluginServerInitCallback(); -using namespace chip; -using namespace chip::app; -using namespace chip::app::Clusters; -using namespace chip::app::Clusters::AdministratorCommissioning; -using namespace chip::app::Clusters::BridgedDeviceBasicInformation; - namespace { #if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE @@ -58,8 +58,6 @@ constexpr uint16_t kRetryIntervalS = 3; uint16_t gFabricAdminServerPort = 33001; uint16_t gLocalServerPort = 33002; -BridgedDeviceBasicInformationImpl gBridgedDeviceBasicInformationAttributes; - constexpr uint16_t kOptionFabricAdminServerPortNumber = 0xFF01; constexpr uint16_t kOptionLocalServerPortNumber = 0xFF02; @@ -239,6 +237,7 @@ void BridgedDeviceInformationCommandHandler::InvokeCommand(HandlerContext & hand } BridgedAdministratorCommissioning gBridgedAdministratorCommissioning; +BridgedDeviceBasicInformationImpl gBridgedDeviceBasicInformationAttributes; AdministratorCommissioningCommandHandler gAdministratorCommissioningCommandHandler; BridgedDeviceInformationCommandHandler gBridgedDeviceInformationCommandHandler; From 8211b690b7d4a68c1e4ea7609d2b1fc213be425d Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Tue, 29 Oct 2024 15:27:59 -0400 Subject: [PATCH 005/121] Factor out common parts of list iterators into shared super-classes. (#36279) * Factor out common parts of list iterators into shared super-classes. Saves some codesize. Fixes https://github.com/project-chip/connectedhomeip/issues/36264 * Remove unused variables. --- src/app/data-model/DecodableList.h | 184 ++++++++++++------ .../java/OTAProviderDelegateBridge.cpp | 9 +- src/controller/tests/TestEventChunking.cpp | 1 - 3 files changed, 132 insertions(+), 62 deletions(-) diff --git a/src/app/data-model/DecodableList.h b/src/app/data-model/DecodableList.h index b05db43c1522bf..b65bf674960885 100644 --- a/src/app/data-model/DecodableList.h +++ b/src/app/data-model/DecodableList.h @@ -83,8 +83,103 @@ class DecodableListBase } protected: + class Iterator + { + public: + Iterator(const TLV::TLVReader & reader) + { + mStatus = CHIP_NO_ERROR; + mReader.Init(reader); + } + + bool Next() + { + if (mReader.GetContainerType() == TLV::kTLVType_NotSpecified) + { + return false; + } + + if (mStatus == CHIP_NO_ERROR) + { + mStatus = mReader.Next(); + } + + return (mStatus == CHIP_NO_ERROR); + } + + /* + * Returns the result of all previous operations on this iterator. + * + * Notably, if the end-of-list was encountered in a previous call to Next, + * the status returned shall be CHIP_NO_ERROR. + */ + CHIP_ERROR GetStatus() const + { + if (mStatus == CHIP_END_OF_TLV) + { + return CHIP_NO_ERROR; + } + + return mStatus; + } + + protected: + CHIP_ERROR mStatus; + TLV::TLVReader mReader; + }; + TLV::TLVReader mReader; - chip::Optional mFabricIndex; +}; + +template +class FabricIndexListMemberMixin +{ +}; + +template <> +class FabricIndexListMemberMixin +{ +public: + void SetFabricIndex(FabricIndex fabricIndex) { mFabricIndex.SetValue(fabricIndex); } + +protected: + Optional mFabricIndex; +}; + +template +class FabricIndexIteratorMemberMixin +{ +}; + +template <> +class FabricIndexIteratorMemberMixin +{ +public: + FabricIndexIteratorMemberMixin(const Optional & fabricindex) : mFabricIndex(fabricindex) {} + +protected: + const Optional mFabricIndex; +}; + +template +class DecodableMaybeFabricScopedList : public DecodableListBase, public FabricIndexListMemberMixin +{ +public: + static constexpr bool kIsFabricScoped = IsFabricScoped; + +protected: + class Iterator : public DecodableListBase::Iterator, public FabricIndexIteratorMemberMixin + { + public: + template = true> + Iterator(const TLV::TLVReader & reader, const Optional & fabricIndex) : + DecodableListBase::Iterator(reader), FabricIndexIteratorMemberMixin(fabricIndex) + {} + + template = true> + Iterator(const TLV::TLVReader & reader) : DecodableListBase::Iterator(reader) + {} + }; }; } // namespace detail @@ -109,21 +204,15 @@ class DecodableListBase * */ template -class DecodableList : public detail::DecodableListBase +class DecodableList : public detail::DecodableMaybeFabricScopedList::value> { public: DecodableList() {} - static constexpr bool kIsFabricScoped = DataModel::IsFabricScoped::value; - - template ::value, bool> = true> - void SetFabricIndex(FabricIndex fabricIndex) + class Iterator : public detail::DecodableMaybeFabricScopedList::value>::Iterator { - mFabricIndex.SetValue(fabricIndex); - } + using IteratorBase = typename detail::DecodableMaybeFabricScopedList::value>::Iterator; - class Iterator - { public: /* * Initialize the iterator with a reference to a reader. @@ -133,11 +222,13 @@ class DecodableList : public detail::DecodableListBase * have a `kTLVType_NotSpecified` container type if there is * no list. */ - Iterator(const TLV::TLVReader & reader, Optional fabricIndex) : mFabricIndex(fabricIndex) - { - mStatus = CHIP_NO_ERROR; - mReader.Init(reader); - } + template ::value, bool> = true> + Iterator(const TLV::TLVReader & reader, Optional fabricIndex) : IteratorBase(reader, fabricIndex) + {} + + template ::value, bool> = true> + Iterator(const TLV::TLVReader & reader) : IteratorBase(reader) + {} /* * Increments the iterator to point to the next list element @@ -157,17 +248,17 @@ class DecodableList : public detail::DecodableListBase template ::value, bool> = true> bool Next() { - return DoNext(); + return IteratorBase::Next() && DecodeValue(); } template ::value, bool> = true> bool Next() { - bool hasNext = DoNext(); + bool hasNext = IteratorBase::Next() && DecodeValue(); - if (hasNext && mFabricIndex.HasValue()) + if (hasNext && this->mFabricIndex.HasValue()) { - mValue.SetFabricIndex(mFabricIndex.Value()); + mValue.SetFabricIndex(this->mFabricIndex.Value()); } return hasNext; @@ -179,36 +270,10 @@ class DecodableList : public detail::DecodableListBase */ const T & GetValue() const { return mValue; } - /* - * Returns the result of all previous operations on this iterator. - * - * Notably, if the end-of-list was encountered in a previous call to Next, - * the status returned shall be CHIP_NO_ERROR. - */ - CHIP_ERROR GetStatus() const - { - if (mStatus == CHIP_END_OF_TLV) - { - return CHIP_NO_ERROR; - } - - return mStatus; - } - private: - bool DoNext() + bool DecodeValue() { - if (mReader.GetContainerType() == TLV::kTLVType_NotSpecified) - { - return false; - } - - if (mStatus == CHIP_NO_ERROR) - { - mStatus = mReader.Next(); - } - - if (mStatus == CHIP_NO_ERROR) + if (this->mStatus == CHIP_NO_ERROR) { // // Re-construct mValue to reset its state back to cluster object defaults. @@ -218,22 +283,29 @@ class DecodableList : public detail::DecodableListBase // data from previous decode attempts will continue to linger and give // an incorrect view of the state as seen from a client. // - mValue = T(); - mStatus = DataModel::Decode(mReader, mValue); + mValue = T(); + this->mStatus = DataModel::Decode(this->mReader, mValue); } - return (mStatus == CHIP_NO_ERROR); + return (this->mStatus == CHIP_NO_ERROR); } T mValue; - CHIP_ERROR mStatus; - TLV::TLVReader mReader; - // TODO: Consider some setup where this field does not exist when T - // is not a fabric scoped struct. - const Optional mFabricIndex; }; - Iterator begin() const { return Iterator(mReader, mFabricIndex); } + // Need this->mReader and this->mFabricIndex for the name lookup to realize + // those can be found in our superclasses. + template ::value, bool> = true> + Iterator begin() const + { + return Iterator(this->mReader, this->mFabricIndex); + } + + template ::value, bool> = true> + Iterator begin() const + { + return Iterator(this->mReader); + } }; } // namespace DataModel diff --git a/src/controller/java/OTAProviderDelegateBridge.cpp b/src/controller/java/OTAProviderDelegateBridge.cpp index 77bf3572e0f65c..fe38cbdd920ce2 100644 --- a/src/controller/java/OTAProviderDelegateBridge.cpp +++ b/src/controller/java/OTAProviderDelegateBridge.cpp @@ -154,11 +154,10 @@ void OTAProviderDelegateBridge::HandleQueryImage(CommandHandler * commandObj, co VendorId vendorId = commandData.vendorID; uint16_t productId = commandData.productID; uint32_t softwareVersion = commandData.softwareVersion; - DataModel::DecodableList protocolsSupported = commandData.protocolsSupported; - Optional hardwareVersion = commandData.hardwareVersion; - Optional location = commandData.location; - Optional requestorCanConsent = commandData.requestorCanConsent; - Optional metadataForProvider = commandData.metadataForProvider; + Optional hardwareVersion = commandData.hardwareVersion; + Optional location = commandData.location; + Optional requestorCanConsent = commandData.requestorCanConsent; + Optional metadataForProvider = commandData.metadataForProvider; bool isBDXProtocolSupported = false; diff --git a/src/controller/tests/TestEventChunking.cpp b/src/controller/tests/TestEventChunking.cpp index 74ba8715476443..d0f4999ee782d3 100644 --- a/src/controller/tests/TestEventChunking.cpp +++ b/src/controller/tests/TestEventChunking.cpp @@ -187,7 +187,6 @@ void TestReadCallback::OnAttributeData(const app::ConcreteDataAttributePath & aP { app::DataModel::DecodableList v; EXPECT_EQ(app::DataModel::Decode(*apData, v), CHIP_NO_ERROR); - auto it = v.begin(); size_t arraySize = 0; EXPECT_EQ(v.ComputeSize(&arraySize), CHIP_NO_ERROR); EXPECT_EQ(arraySize, 4u); From d535b905d1c158aedf70eb7e64447cab656af69c Mon Sep 17 00:00:00 2001 From: Amine Alami <43780877+Alami-Amine@users.noreply.github.com> Date: Tue, 29 Oct 2024 21:48:49 +0100 Subject: [PATCH 006/121] Adding a FuzzTest for fuzzing PASE (#36171) --- BUILD.gn | 1 + src/protocols/secure_channel/tests/BUILD.gn | 24 ++ .../secure_channel/tests/FuzzPASE_PW.cpp | 304 ++++++++++++++++++ 3 files changed, 329 insertions(+) create mode 100644 src/protocols/secure_channel/tests/FuzzPASE_PW.cpp diff --git a/BUILD.gn b/BUILD.gn index e05f14312d8a1a..a777fa84b32c99 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -70,6 +70,7 @@ if (current_toolchain != "${dir_pw_toolchain}/default:default") { "${chip_root}/src/lib/core/tests:fuzz-tlv-reader-pw(//build/toolchain/pw_fuzzer:chip_pw_fuzztest)", "${chip_root}/src/lib/dnssd/minimal_mdns/tests:fuzz-minmdns-packet-parsing-pw(//build/toolchain/pw_fuzzer:chip_pw_fuzztest)", "${chip_root}/src/lib/format/tests:fuzz-payload-decoder-pw(//build/toolchain/pw_fuzzer:chip_pw_fuzztest)", + "${chip_root}/src/protocols/secure_channel/tests:fuzz-PASE-pw(//build/toolchain/pw_fuzzer:chip_pw_fuzztest)", "${chip_root}/src/setup_payload/tests:fuzz-setup-payload-base38-pw(//build/toolchain/pw_fuzzer:chip_pw_fuzztest)", ] } diff --git a/src/protocols/secure_channel/tests/BUILD.gn b/src/protocols/secure_channel/tests/BUILD.gn index a5e6d73455eaea..415db1bbd76fd0 100644 --- a/src/protocols/secure_channel/tests/BUILD.gn +++ b/src/protocols/secure_channel/tests/BUILD.gn @@ -1,6 +1,8 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") + import("${chip_root}/build/chip/chip_test_suite.gni") +import("${chip_root}/build/chip/fuzz_test.gni") import("${chip_root}/src/app/icd/icd.gni") chip_test_suite("tests") { @@ -45,3 +47,25 @@ chip_test_suite("tests") { public_deps += [ "${chip_root}/src/app/icd/server:configuration-data" ] } } +if (pw_enable_fuzz_test_targets) { + chip_pw_fuzz_target("fuzz-PASE-pw") { + test_source = [ "FuzzPASE_PW.cpp" ] + public_deps = [ + "${chip_root}/src/app/icd/server:icd-server-config", + "${chip_root}/src/credentials/tests:cert_test_vectors", + "${chip_root}/src/crypto/tests:tests.lib", + "${chip_root}/src/lib/core", + "${chip_root}/src/lib/core:string-builder-adapters", + "${chip_root}/src/lib/support", + "${chip_root}/src/lib/support:test_utils", + "${chip_root}/src/lib/support:testing", + "${chip_root}/src/lib/support/tests:pw-test-macros", + "${chip_root}/src/messaging/tests:helpers", + "${chip_root}/src/protocols", + "${chip_root}/src/protocols/secure_channel", + "${chip_root}/src/protocols/secure_channel:check-in-counter", + "${chip_root}/src/transport/raw/tests:helpers", + "${dir_pw_unit_test}", + ] + } +} diff --git a/src/protocols/secure_channel/tests/FuzzPASE_PW.cpp b/src/protocols/secure_channel/tests/FuzzPASE_PW.cpp new file mode 100644 index 00000000000000..d3dc5998112f2a --- /dev/null +++ b/src/protocols/secure_channel/tests/FuzzPASE_PW.cpp @@ -0,0 +1,304 @@ +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace chip; +using namespace std; + +using namespace chip::Crypto; +using namespace fuzztest; +using namespace chip::Transport; +using namespace chip::Messaging; +using namespace System::Clock::Literals; + +// TODO: #35369 Refactor the classes below to Fixtures once Errors related to FuzzTest Fixtures are resolved +class FuzzLoopbackMessagingContext : public chip::Test::MessagingContext +{ +public: + ~FuzzLoopbackMessagingContext() {} + + // These functions wrap spLoopbackTransportManager methods + static auto & GetSystemLayer() { return spLoopbackTransportManager->GetSystemLayer(); } + static auto & GetLoopback() { return spLoopbackTransportManager->GetLoopback(); } + static auto & GetTransportMgr() { return spLoopbackTransportManager->GetTransportMgr(); } + static auto & GetIOContext() { return spLoopbackTransportManager->GetIOContext(); } + + template + static void DrainAndServiceIO(Ts... args) + { + return spLoopbackTransportManager->DrainAndServiceIO(args...); + } + + // Performs shared setup for all tests in the test suite + static void SetUpTestSuite() + { + // Initialize memory. + ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); + // Instantiate the LoopbackTransportManager. + ASSERT_EQ(spLoopbackTransportManager, nullptr); + spLoopbackTransportManager = new chip::Test::LoopbackTransportManager(); + ASSERT_NE(spLoopbackTransportManager, nullptr); + // Initialize the LoopbackTransportManager. + ASSERT_EQ(spLoopbackTransportManager->Init(), CHIP_NO_ERROR); + } + + // Performs shared teardown for all tests in the test suite + static void TearDownTestSuite() + { + // Shutdown the LoopbackTransportManager. + spLoopbackTransportManager->Shutdown(); + // Destroy the LoopbackTransportManager. + if (spLoopbackTransportManager != nullptr) + { + delete spLoopbackTransportManager; + spLoopbackTransportManager = nullptr; + } + // Shutdown memory. + chip::Platform::MemoryShutdown(); + } + + // Performs setup for each individual test in the test suite + void SetUp() { ASSERT_EQ(MessagingContext::Init(&GetTransportMgr(), &GetIOContext()), CHIP_NO_ERROR); } + + // Performs teardown for each individual test in the test suite + void TearDown() { MessagingContext::Shutdown(); } + + static chip::Test::LoopbackTransportManager * spLoopbackTransportManager; +}; +chip::Test::LoopbackTransportManager * FuzzLoopbackMessagingContext::spLoopbackTransportManager = nullptr; + +class TestSecurePairingDelegate : public SessionEstablishmentDelegate +{ +public: + void OnSessionEstablishmentError(CHIP_ERROR error) override { mNumPairingErrors++; } + + void OnSessionEstablished(const SessionHandle & session) override { mNumPairingComplete++; } + + uint32_t mNumPairingErrors = 0; + uint32_t mNumPairingComplete = 0; +}; + +class TestPASESession : public FuzzLoopbackMessagingContext +{ +public: + TestPASESession() + { + ConfigInitializeNodes(false); + FuzzLoopbackMessagingContext::SetUpTestSuite(); + FuzzLoopbackMessagingContext::SetUp(); + } + ~TestPASESession() + { + FuzzLoopbackMessagingContext::TearDown(); + FuzzLoopbackMessagingContext::TearDownTestSuite(); + } + + void SecurePairingHandshake(SessionManager & sessionManager, PASESession & pairingCommissioner, + TestSecurePairingDelegate & delegateCommissioner, TestSecurePairingDelegate & delegateAccessory, + const Spake2pVerifier & verifier, uint32_t pbkdf2IterCount, const ByteSpan & salt, + uint32_t SetUpPINCode); +}; + +class TemporarySessionManager +{ +public: + TemporarySessionManager(TestPASESession & ctx) : mCtx(ctx) + { + EXPECT_EQ(CHIP_NO_ERROR, + mSessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &ctx.GetMessageCounterManager(), &mStorage, + &ctx.GetFabricTable(), ctx.GetSessionKeystore())); + // The setup here is really weird: we are using one session manager for + // the actual messages we send (the PASE handshake, so the + // unauthenticated sessions) and a different one for allocating the PASE + // sessions. Since our Init() set us up as the thing to handle messages + // on the transport manager, undo that. + mCtx.GetTransportMgr().SetSessionManager(&mCtx.GetSecureSessionManager()); + } + + ~TemporarySessionManager() + { + mSessionManager.Shutdown(); + // Reset the session manager on the transport again, just in case + // shutdown messed with it. + mCtx.GetTransportMgr().SetSessionManager(&mCtx.GetSecureSessionManager()); + } + + operator SessionManager &() { return mSessionManager; } + +private: + TestPASESession & mCtx; + TestPersistentStorageDelegate mStorage; + SessionManager mSessionManager; +}; + +class PASETestLoopbackTransportDelegate : public Test::LoopbackTransportDelegate +{ +public: + void OnMessageDropped() override { mMessageDropped = true; } + bool mMessageDropped = false; +}; + +void TestPASESession::SecurePairingHandshake(SessionManager & sessionManager, PASESession & pairingCommissioner, + TestSecurePairingDelegate & delegateCommissioner, + TestSecurePairingDelegate & delegateAccessory, const Spake2pVerifier & verifier, + uint32_t pbkdf2IterCount, const ByteSpan & salt, uint32_t SetUpPINCode) +{ + + PASESession pairingAccessory; + + PASETestLoopbackTransportDelegate delegate; + auto & loopback = GetLoopback(); + loopback.SetLoopbackTransportDelegate(&delegate); + loopback.mSentMessageCount = 0; + + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(&pairingCommissioner); + + EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::PBKDFParamRequest, + &pairingAccessory), + CHIP_NO_ERROR); + + pairingAccessory.WaitForPairing(sessionManager, verifier, pbkdf2IterCount, salt, + Optional::Missing(), &delegateAccessory); + DrainAndServiceIO(); + + pairingCommissioner.Pair(sessionManager, SetUpPINCode, Optional::Missing(), contextCommissioner, + &delegateCommissioner); + + DrainAndServiceIO(); +} + +//----------------------------------------**********Fuzz Tests*********------------------------------------------------ + +// This Fuzz Test should always result in Successful PASE Pairing, since all fuzzed inputs are within the valid bounds +void PASESession_Bounded(const uint32_t fuzzedSetupPasscode, const vector & fuzzedSalt, uint32_t fuzzedPBKDF2Iter) +{ + + Spake2pVerifier fuzzedSpake2pVerifier; + ByteSpan fuzzedSaltSpan{ fuzzedSalt.data(), fuzzedSalt.size() }; + + // Generating the Spake2+ verifier from the fuzzed inputs + EXPECT_EQ(fuzzedSpake2pVerifier.Generate(fuzzedPBKDF2Iter, fuzzedSaltSpan, fuzzedSetupPasscode), CHIP_NO_ERROR); + + // TODO: #35369 Move this to a Fixture once Errors related to FuzzTest Fixtures are resolved + TestPASESession PASELoopBack; + TemporarySessionManager sessionManager(PASELoopBack); + + PASESession pairingCommissioner; + + TestSecurePairingDelegate delegateCommissioner; + TestSecurePairingDelegate delegateCommissionee; + + PASELoopBack.SecurePairingHandshake(sessionManager, pairingCommissioner, delegateCommissioner, delegateCommissionee, + fuzzedSpake2pVerifier, fuzzedPBKDF2Iter, fuzzedSaltSpan, fuzzedSetupPasscode); + + // Given that the inputs to this Fuzz Test are within the expected boundaries, the Pairing should Always be successful. + EXPECT_EQ(delegateCommissionee.mNumPairingComplete, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 1u); + + EXPECT_EQ(delegateCommissionee.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 0u); +} + +FUZZ_TEST(FuzzPASE_PW, PASESession_Bounded) + .WithDomains( + InRange(00000000, 99999998), + Arbitrary>().WithMinSize(kSpake2p_Min_PBKDF_Salt_Length).WithMaxSize(kSpake2p_Max_PBKDF_Salt_Length), + InRange(kSpake2p_Min_PBKDF_Iterations, kSpake2p_Max_PBKDF_Iterations)); + +/* -------------------------------------------------------------------------------------------*/ +// This Fuzz Test is the equivalent of the previous one, but with the fuzzed inputs not being within the valid bounds. +void PASESession_Unbounded(const uint32_t fuzzedSetupPasscode, const vector & fuzzedSalt, uint32_t fuzzedPBKDF2Iter) +{ + + Spake2pVerifier fuzzedSpake2pVerifier; + ByteSpan fuzzedSaltSpan{ fuzzedSalt.data(), fuzzedSalt.size() }; + + // Generating the Spake2+ verifier from fuzzed inputs + fuzzedSpake2pVerifier.Generate(fuzzedPBKDF2Iter, fuzzedSaltSpan, fuzzedSetupPasscode); + + TestPASESession PASELoopBack; + TemporarySessionManager sessionManager(PASELoopBack); + + PASESession pairingCommissioner; + + TestSecurePairingDelegate delegateCommissioner; + TestSecurePairingDelegate delegateCommissionee; + + PASELoopBack.SecurePairingHandshake(sessionManager, pairingCommissioner, delegateCommissioner, delegateCommissionee, + fuzzedSpake2pVerifier, fuzzedPBKDF2Iter, fuzzedSaltSpan, fuzzedSetupPasscode); +} + +FUZZ_TEST(FuzzPASE_PW, PASESession_Unbounded) + .WithDomains(Arbitrary(), Arbitrary>(), Arbitrary()); + +/* -------------------------------------------------------------------------------------------*/ +// In This FuzzTest, the Spake2pVerifier is fuzzed. +void FuzzSpake2pVerifier(const vector & aW0, const vector & aL, const vector & aSalt, + const uint32_t fuzzedPBKDF2Iter, const uint32_t fuzzedSetupPasscode) +{ + Spake2pVerifier fuzzedSpake2pVerifier; + + copy_n(aW0.data(), aW0.size(), fuzzedSpake2pVerifier.mW0); + copy_n(aL.data(), aL.size(), fuzzedSpake2pVerifier.mL); + + ByteSpan fuzzedSaltSpan(aSalt.data(), aSalt.size()); + + TestPASESession PASELoopBack; + TemporarySessionManager sessionManager(PASELoopBack); + + PASESession pairingCommissioner; + + TestSecurePairingDelegate delegateCommissioner; + TestSecurePairingDelegate delegateCommissionee; + + PASELoopBack.SecurePairingHandshake(sessionManager, pairingCommissioner, delegateCommissioner, delegateCommissionee, + fuzzedSpake2pVerifier, fuzzedPBKDF2Iter, fuzzedSaltSpan, fuzzedSetupPasscode); +} +FUZZ_TEST(FuzzPASE_PW, FuzzSpake2pVerifier) + .WithDomains(Arbitrary>().WithMaxSize(kP256_FE_Length), + Arbitrary>().WithMaxSize(kP256_Point_Length), Arbitrary>(), + Arbitrary(), Arbitrary()); + +/* -------------------------------------------------------------------------------------------*/ +// In This FuzzTest, Fuzzed Serialized Verifier is deserialized and Serialized Again, comparing the original with RoundTrip result. +void Spake2pVerifier_Serialize_RoundTrip(const vector & FuzzedSerializedVerifier) +{ + + Spake2pVerifierSerialized FuzzedSerializedVerifierArray; + + copy_n(FuzzedSerializedVerifier.data(), FuzzedSerializedVerifier.size(), FuzzedSerializedVerifierArray); + + // Deserialize the fuzzed SPAKE2+ Verifier + Spake2pVerifier verifier; + EXPECT_EQ(verifier.Deserialize(ByteSpan(FuzzedSerializedVerifierArray)), CHIP_NO_ERROR); + + // Serialize the fuzzed SPAKE2+ Verifier again + Spake2pVerifierSerialized reserializedVerifier; + MutableByteSpan reserializedVerifierSpan(reserializedVerifier); + EXPECT_EQ(verifier.Serialize(reserializedVerifierSpan), CHIP_NO_ERROR); + EXPECT_EQ(reserializedVerifierSpan.size(), kSpake2p_VerifierSerialized_Length); + + // The original fuzzed SPAKE2+ verifier should be the same as the deserialized and re-serialized verifier (RoundTrip). + EXPECT_EQ(memcmp(reserializedVerifier, FuzzedSerializedVerifierArray, kSpake2p_VerifierSerialized_Length), 0); +} + +FUZZ_TEST(FuzzPASE_PW, Spake2pVerifier_Serialize_RoundTrip) + .WithDomains(Arbitrary>().WithSize(kSpake2p_VerifierSerialized_Length)); + +} // namespace From fef41bd0fb76acbf128ea547330d8792ba7ecc65 Mon Sep 17 00:00:00 2001 From: Ethan Zhou <73028112+ethanzhouyc@users.noreply.github.com> Date: Tue, 29 Oct 2024 17:25:17 -0400 Subject: [PATCH 007/121] Revert "Revert Generate Conformance Data with Alchemy" and Remove Attribute Description (#36233) * Revert "Revert "Generate Conformance Data with Alchemy (#36186)" (#36220)" This reverts commit a4a911c70bc3258077ce8a584ff55856d3e21dc5. * move attribute name - move attribute name from description to name inside attribute tag --- .../chip/access-control-cluster.xml | 51 +- .../data-model/chip/account-login-cluster.xml | 11 +- .../zcl/data-model/chip/actions-cluster.xml | 30 +- .../administrator-commissioning-cluster.xml | 19 +- .../data-model/chip/air-quality-cluster.xml | 4 +- .../chip/application-basic-cluster.xml | 34 +- .../chip/application-launcher-cluster.xml | 16 +- .../data-model/chip/audio-output-cluster.xml | 14 +- .../chip/ballast-configuration-cluster.xml | 76 +- .../chip/basic-information-cluster.xml | 95 +- .../zcl/data-model/chip/binding-cluster.xml | 6 +- .../data-model/chip/boolean-state-cluster.xml | 7 +- .../boolean-state-configuration-cluster.xml | 73 +- .../camera-av-stream-management-cluster.xml | 63 +- .../zcl/data-model/chip/channel-cluster.xml | 50 +- .../zcl/data-model/chip/chip-ota.xml | 3 +- .../data-model/chip/color-control-cluster.xml | 449 ++++- .../chip/commissioner-control-cluster.xml | 8 +- .../concentration-measurement-cluster.xml | 1074 ++++++++---- .../chip/content-app-observer-cluster.xml | 2 + .../chip/content-control-cluster.xml | 78 +- .../chip/content-launch-cluster.xml | 28 +- .../data-model/chip/descriptor-cluster.xml | 24 +- .../chip/device-energy-management-cluster.xml | 87 +- .../device-energy-management-mode-cluster.xml | 10 +- .../chip/diagnostic-logs-cluster.xml | 86 +- .../chip/dishwasher-alarm-cluster.xml | 41 +- .../chip/dishwasher-mode-cluster.xml | 12 +- .../zcl/data-model/chip/door-lock-cluster.xml | 1469 ++++++++++------- .../zcl/data-model/chip/drlc-cluster.xml | 37 +- .../chip/ecosystem-information-cluster.xml | 6 +- .../electrical-energy-measurement-cluster.xml | 52 +- .../electrical-power-measurement-cluster.xml | 103 +- .../data-model/chip/energy-evse-cluster.xml | 131 +- .../chip/energy-evse-mode-cluster.xml | 10 +- .../chip/energy-preference-cluster.xml | 31 +- .../ethernet-network-diagnostics-cluster.xml | 64 +- .../data-model/chip/fixed-label-cluster.xml | 4 +- .../chip/flow-measurement-cluster.xml | 16 +- .../chip/general-commissioning-cluster.xml | 83 +- .../chip/general-diagnostics-cluster.xml | 51 +- .../chip/group-key-mgmt-cluster.xml | 26 +- .../zcl/data-model/chip/groups-cluster.xml | 16 +- .../chip/icd-management-cluster.xml | 250 +-- .../zcl/data-model/chip/identify-cluster.xml | 14 +- .../chip/illuminance-measurement-cluster.xml | 36 +- .../data-model/chip/keypad-input-cluster.xml | 2 + .../chip/laundry-dryer-controls-cluster.xml | 14 +- .../chip/laundry-washer-mode-cluster.xml | 12 +- .../data-model/chip/level-control-cluster.xml | 83 +- .../localization-configuration-cluster.xml | 8 +- .../zcl/data-model/chip/low-power-cluster.xml | 1 + .../data-model/chip/media-input-cluster.xml | 14 +- .../chip/media-playback-cluster.xml | 92 +- .../zcl/data-model/chip/messages-cluster.xml | 15 +- .../chip/microwave-oven-control-cluster.xml | 64 +- .../chip/microwave-oven-mode-cluster.xml | 8 +- .../data-model/chip/mode-select-cluster.xml | 28 +- .../chip/network-commissioning-cluster.xml | 268 +-- .../chip/occupancy-sensing-cluster.xml | 252 ++- .../zcl/data-model/chip/onoff-cluster.xml | 50 +- .../chip/operational-credentials-cluster.xml | 38 +- .../chip/operational-state-cluster.xml | 65 +- .../chip/operational-state-oven-cluster.xml | 47 +- .../chip/operational-state-rvc-cluster.xml | 68 +- .../zcl/data-model/chip/oven-mode-cluster.xml | 12 +- .../data-model/chip/power-source-cluster.xml | 202 ++- .../power-source-configuration-cluster.xml | 4 +- .../chip/power-topology-cluster.xml | 12 +- .../chip/pressure-measurement-cluster.xml | 48 +- ...pump-configuration-and-control-cluster.xml | 181 +- .../data-model/chip/refrigerator-alarm.xml | 25 +- ...rature-controlled-cabinet-mode-cluster.xml | 12 +- .../relative-humidity-measurement-cluster.xml | 16 +- .../chip/resource-monitoring-cluster.xml | 66 +- .../chip/rvc-clean-mode-cluster.xml | 10 +- .../data-model/chip/rvc-run-mode-cluster.xml | 10 +- .../zcl/data-model/chip/scene.xml | 31 +- .../data-model/chip/service-area-cluster.xml | 36 +- .../chip/smoke-co-alarm-cluster.xml | 82 +- .../chip/software-diagnostics-cluster.xml | 24 +- .../zcl/data-model/chip/switch-cluster.xml | 42 +- .../chip/target-navigator-cluster.xml | 13 +- .../chip/temperature-control-cluster.xml | 43 +- .../chip/temperature-measurement-cluster.xml | 16 +- .../data-model/chip/thermostat-cluster.xml | 350 +++- ...t-user-interface-configuration-cluster.xml | 14 +- ...hread-border-router-management-cluster.xml | 45 +- .../thread-network-diagnostics-cluster.xml | 345 +++- .../chip/thread-network-directory-cluster.xml | 106 +- .../chip/time-format-localization-cluster.xml | 20 +- .../chip/time-synchronization-cluster.xml | 105 +- .../chip/unit-localization-cluster.xml | 8 +- .../data-model/chip/user-label-cluster.xml | 4 +- ...alve-configuration-and-control-cluster.xml | 60 +- .../data-model/chip/wake-on-lan-cluster.xml | 10 +- .../chip/washer-controls-cluster.xml | 26 +- .../chip/water-heater-management-cluster.xml | 34 +- .../chip/water-heater-mode-cluster.xml | 10 +- .../chip/wifi-network-diagnostics-cluster.xml | 74 +- .../chip/wifi-network-management-cluster.xml | 10 +- .../zcl/data-model/chip/window-covering.xml | 212 ++- 102 files changed, 6057 insertions(+), 2240 deletions(-) diff --git a/src/app/zap-templates/zcl/data-model/chip/access-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/access-control-cluster.xml index edf1b65e941ad0..67a919eac1df0d 100644 --- a/src/app/zap-templates/zcl/data-model/chip/access-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/access-control-cluster.xml @@ -109,33 +109,55 @@ limitations under the License. and enforce Access Control for the Node's endpoints and their associated cluster instances. - - ACL + + - - Extension + + + + - SubjectsPerAccessControlEntry - TargetsPerAccessControlEntry - AccessControlEntriesPerFabric - CommissioningARL - ARL - + + + + + + + + + + + + + + + + + + + + This command signals to the service associated with the device vendor that the fabric administrator would like a review of the current restrictions on the accessing fabric. - + + + + Returns the review token for the request, which can be used to correlate with a FabricRestrictionReviewUpdate event. + + + @@ -145,6 +167,7 @@ limitations under the License. + @@ -154,6 +177,9 @@ limitations under the License. + + + @@ -162,6 +188,9 @@ limitations under the License. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/account-login-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/account-login-cluster.xml index baf74dc3c2e1da..38fcbcaaf9c5e4 100644 --- a/src/app/zap-templates/zcl/data-model/chip/account-login-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/account-login-cluster.xml @@ -28,31 +28,36 @@ limitations under the License. Upon receipt, the Content App checks if the account associated with the client Temp Account Identifier Rotating ID is the same acount that is active on the given Content App. If the accounts are the same, then the Content App includes the Setup PIN in the GetSetupPIN Response. - + + Upon receipt, the Content App checks if the account associated with the client’s Temp Account Identifier (Rotating ID) has a current active Setup PIN with the given value. If the Setup PIN is valid for the user account associated with the Temp Account Identifier, then the Content App MAY make that user account active. - + - + + The purpose of this command is to instruct the Content App to clear the current user account. This command SHOULD be used by clients of a Content App to indicate the end of a user session. + This message is sent in response to the GetSetupPIN Request, and contains the Setup PIN code, or null when the accounts identified in the request does not match the active account of the running Content App. + This event can be used by the Content App to indicate that the current user has logged out. In response to this event, the Fabric Admin SHALL remove access to this Content App by the specified Node. If no Node is provided, then the Fabric Admin SHALL remove access to all non-Admin Nodes. + diff --git a/src/app/zap-templates/zcl/data-model/chip/actions-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/actions-cluster.xml index acf28b88e46414..73c38134ed8150 100644 --- a/src/app/zap-templates/zcl/data-model/chip/actions-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/actions-cluster.xml @@ -89,11 +89,17 @@ limitations under the License. 0x0025 ACTIONS_CLUSTER This cluster provides a standardized way for a Node (typically a Bridge, but could be any Node) to expose action information. - - ActionList - EndpointLists - SetupURL - + + + + + + + + + + + This command triggers an action (state change) on the involved endpoints. @@ -173,17 +179,19 @@ limitations under the License. This event SHALL be generated when there is a change in the Status of an ActionID. - - + + + This event SHALL be generated when there is some error which prevents the action from its normal planned execution. - - - - + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/administrator-commissioning-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/administrator-commissioning-cluster.xml index 3532c89b931880..ba6b7fd266f4ce 100644 --- a/src/app/zap-templates/zcl/data-model/chip/administrator-commissioning-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/administrator-commissioning-cluster.xml @@ -43,10 +43,16 @@ limitations under the License. - WindowStatus - AdminFabricIndex - AdminVendorId - + + + + + + + + + + This command is used by a current Administrator to instruct a Node to go into commissioning mode using enhanced commissioning method. @@ -55,17 +61,22 @@ limitations under the License. + This command is used by a current Administrator to instruct a Node to go into commissioning mode using basic commissioning method, if the node supports it. + + + This command is used by a current Administrator to instruct a Node to revoke any active Open Commissioning Window or Open Basic Commissioning Window command. + diff --git a/src/app/zap-templates/zcl/data-model/chip/air-quality-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/air-quality-cluster.xml index bbc57510e85dce..1b5d34b7bacb02 100644 --- a/src/app/zap-templates/zcl/data-model/chip/air-quality-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/air-quality-cluster.xml @@ -41,7 +41,9 @@ limitations under the License. - AirQuality + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/application-basic-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/application-basic-cluster.xml index e6331f698fd423..704b8cadbea19c 100644 --- a/src/app/zap-templates/zcl/data-model/chip/application-basic-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/application-basic-cluster.xml @@ -24,16 +24,30 @@ limitations under the License. true true This cluster provides information about an application running on a TV or media player device which is represented as an endpoint. - VendorName - VendorID - ApplicationName - ProductID - Application - Status - ApplicationVersion - - AllowedVendorList - + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/application-launcher-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/application-launcher-cluster.xml index 50b715e138a744..d69437a298f85e 100644 --- a/src/app/zap-templates/zcl/data-model/chip/application-launcher-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/application-launcher-cluster.xml @@ -31,29 +31,39 @@ limitations under the License. - CatalogList - CurrentApp - + + + + + + + + + Upon receipt, this SHALL launch the specified app with optional data. The TV Device SHALL launch and bring to foreground the identified application in the command if the application is not already launched and in foreground. The TV Device SHALL update state attribute on the Application Basic cluster of the Endpoint corresponding to the launched application. This command returns a Launch Response. + Upon receipt on a Video Player endpoint this SHALL stop the specified application if it is running. + Upon receipt on a Video Player endpoint this SHALL hide the specified application if it is running and visible. + This command SHALL be generated in response to LaunchApp commands. + diff --git a/src/app/zap-templates/zcl/data-model/chip/audio-output-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/audio-output-cluster.xml index acaa9deadb6a3b..d24b34f40235c2 100644 --- a/src/app/zap-templates/zcl/data-model/chip/audio-output-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/audio-output-cluster.xml @@ -31,12 +31,17 @@ limitations under the License. - OutputList - CurrentOutput - + + + + + + + Upon receipt, this SHALL change the output on the media device to the output at a specific index in the Output List. + @@ -44,6 +49,9 @@ limitations under the License. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/ballast-configuration-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/ballast-configuration-cluster.xml index 32450208914a6d..80119e8ec0a006 100644 --- a/src/app/zap-templates/zcl/data-model/chip/ballast-configuration-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/ballast-configuration-cluster.xml @@ -41,53 +41,61 @@ limitations under the License. - PhysicalMinLevel - PhysicalMaxLevel - BallastStatus + + + + + + + + + - - MinLevel - + + + - - MaxLevel - + + + - - IntrinsicBallastFactor - + + + - - BallastFactorAdjustment - + + + - LampQuantity + + + - - LampType - + + + - - LampManufacturer - + + + - - LampRatedHours - + + + - - LampBurnHours - + + + - - LampAlarmMode - + + + - - LampBurnHoursTripPoint - + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/basic-information-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/basic-information-cluster.xml index 7f6320a5880dc9..f08d9dc2be7d2b 100644 --- a/src/app/zap-templates/zcl/data-model/chip/basic-information-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/basic-information-cluster.xml @@ -74,52 +74,95 @@ limitations under the License. which apply to the whole Node. Also allows setting user device information such as location. - DataModelRevision - VendorName - VendorID - ProductName - ProductID - - NodeLabel + + + + + + + + + + + + + + + + + - - Location + + + + + + + + + + + + + + + + + - HardwareVersion - HardwareVersionString - SoftwareVersion - SoftwareVersionString - ManufacturingDate - PartNumber - ProductURL - ProductLabel - SerialNumber - - LocalConfigDisabled + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - Reachable - UniqueID - CapabilityMinima - ProductAppearance - SpecificationVersion - MaxPathsPerInvoke The StartUp event SHALL be emitted by a Node as soon as reasonable after completing a boot or reboot process. + The ShutDown event SHOULD be emitted by a Node prior to any orderly shutdown sequence on a best-effort basis. + The Leave event SHOULD be emitted by a Node prior to permanently leaving the Fabric. + This event (when supported) SHALL be generated when there is a change in the Reachable attribute. diff --git a/src/app/zap-templates/zcl/data-model/chip/binding-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/binding-cluster.xml index 741a5a9372edc0..19f2b0933c82c1 100644 --- a/src/app/zap-templates/zcl/data-model/chip/binding-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/binding-cluster.xml @@ -31,9 +31,9 @@ limitations under the License. 0x001e BINDING_CLUSTER The Binding Cluster is meant to replace the support from the Zigbee Device Object (ZDO) for supporting the binding table. - - Binding - + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/boolean-state-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/boolean-state-cluster.xml index 0dee692affacee..292067d12aa456 100644 --- a/src/app/zap-templates/zcl/data-model/chip/boolean-state-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/boolean-state-cluster.xml @@ -26,11 +26,14 @@ limitations under the License. true true - StateValue - + + + + This event SHALL be generated when the StateValue attribute changes. + diff --git a/src/app/zap-templates/zcl/data-model/chip/boolean-state-configuration-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/boolean-state-configuration-cluster.xml index 4fb33dd9749a0e..a301b4eacf066b 100644 --- a/src/app/zap-templates/zcl/data-model/chip/boolean-state-configuration-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/boolean-state-configuration-cluster.xml @@ -58,34 +58,89 @@ limitations under the License. - CurrentSensitivityLevel - SupportedSensitivityLevels - DefaultSensitivityLevel - AlarmsActive - AlarmsSuppressed - AlarmsEnabled - AlarmsSupported - SensorFault - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This command is used to suppress the specified alarm mode. + + + This command is used to enable or disable the specified alarm mode. + + + + + + This event SHALL be generated when any bits in the AlarmsActive and/or AlarmsSuppressed attributes change. + + + + + + This event SHALL be generated when the device registers or clears a fault. + diff --git a/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml index 5cbf1d28ec89d3..13d1f7a9e77be2 100644 --- a/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml @@ -194,8 +194,7 @@ Git: 0.9-fall2024-411-g9835b5cd7 SupportedSnapshotParams MaxNetworkBandwidth CurrentFrameRate - - HDRModeEnabled + @@ -205,110 +204,90 @@ Git: 0.9-fall2024-411-g9835b5cd7 AllocatedVideoStreams AllocatedAudioStreams AllocatedSnapshotStreams - - RankedVideoStreamPrioritiesList + SoftRecordingPrivacyModeEnabled SoftLivestreamPrivacyModeEnabled HardPrivacyModeOn - - NightVision + - - NightVisionIllum + - - AWBEnabled + - - AutoShutterSpeedEnabled + - - AutoISOEnabled + Viewport - - SpeakerMuted + - - SpeakerVolumeLevel + - - SpeakerMaxLevel + - - SpeakerMinLevel + - - MicrophoneMuted + - - MicrophoneVolumeLevel + - - MicrophoneMaxLevel + - - MicrophoneMinLevel + - - MicrophoneAGCEnabled + ImageRotation ImageFlipHorizontal ImageFlipVertical - - LocalVideoRecordingEnabled + - - LocalSnapshotRecordingEnabled + - - StatusLightEnabled + - - StatusLightBrightness + - - DepthSensorStatus + diff --git a/src/app/zap-templates/zcl/data-model/chip/channel-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/channel-cluster.xml index 25ec7b7062f97a..cb4bcd9adb5ab1 100644 --- a/src/app/zap-templates/zcl/data-model/chip/channel-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/channel-cluster.xml @@ -41,30 +41,54 @@ limitations under the License. - ChannelList - Lineup - CurrentChannel - + + + + + + + + + + + + + + Change the channel on the media player to the channel case-insensitive exact matching the value passed as an argument. + + + + + + Change the channel on the media plaeyer to the channel with the given Number in the ChannelList attribute. + This command provides channel up and channel down functionality, but allows channel index jumps of size Count. When the value of the increase or decrease is larger than the number of channels remaining in the given direction, then the behavior SHALL be to return to the beginning (or end) of the channel list and continue. For example, if the current channel is at index 0 and count value of -1 is given, then the current channel should change to the last channel. + Upon receipt, this SHALL display the active status of the input list on screen. + + + + + + @@ -76,12 +100,18 @@ limitations under the License. + + + This command is a response to the GetProgramGuide command. + + + @@ -90,6 +120,12 @@ limitations under the License. + + + + + + @@ -98,6 +134,12 @@ limitations under the License. + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/chip-ota.xml b/src/app/zap-templates/zcl/data-model/chip/chip-ota.xml index 04fa27436383b2..14767f6429d6c5 100644 --- a/src/app/zap-templates/zcl/data-model/chip/chip-ota.xml +++ b/src/app/zap-templates/zcl/data-model/chip/chip-ota.xml @@ -121,8 +121,7 @@ limitations under the License. OTA_SOFTWARE_UPDATE_REQUESTOR_CLUSTER true true - - DefaultOTAProviders + diff --git a/src/app/zap-templates/zcl/data-model/chip/color-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/color-control-cluster.xml index 3623ce1ccf925c..b3be97a2176d3c 100644 --- a/src/app/zap-templates/zcl/data-model/chip/color-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/color-control-cluster.xml @@ -127,135 +127,359 @@ limitations under the License. - CurrentHue + + + + + - CurrentSaturation + + + + + - RemainingTime + + + - CurrentX + + + + + - CurrentY + + + + + - DriftCompensation + + + - CompensationText + + + - ColorTemperatureMireds + + + + + - ColorMode + + + - Options + + + - NumberOfPrimaries + + + - Primary1X + + + + + + + + + + + - Primary1Y + + + + + + + + + + + - Primary1Intensity + + + + + + + + + + + - Primary2X + + + + + + + + + + + - Primary2Y + + + + + + + + + + + - Primary2Intensity + + + + + + + + + + + - Primary3X + + + + + + + + + + + - Primary3Y + + + + + + + + + + + - Primary3Intensity + + + + + + + + + + + - Primary4X + + + + + + + + + + + - Primary4Y + + + + + + + + + + + - Primary4Intensity + + + + + + + + + + + - Primary5X + + + + + + + + + + + - Primary5Y + + + + + + + + + + + - Primary5Intensity + + + + + + + + + + + - Primary6X + + + + + + + + + + + - Primary6Y + + + + + + + + + + + - Primary6Intensity + + + + + + + + + + + - - WhitePointX + + - - WhitePointY + + - - ColorPointRX + + - - ColorPointRY + + - - ColorPointRIntensity + + - - ColorPointGX + + - - ColorPointGY + + - - ColorPointGIntensity + + - - ColorPointBX + + - - ColorPointBY + + - - ColorPointBIntensity + + - CoupleColorTempToLevelMinMireds - - StartUpColorTemperatureMireds + + + + + + + + + + + + + + + @@ -267,6 +491,9 @@ limitations under the License. + + + @@ -277,6 +504,9 @@ limitations under the License. + + + @@ -288,6 +518,9 @@ limitations under the License. + + + @@ -298,6 +531,9 @@ limitations under the License. + + + @@ -308,6 +544,9 @@ limitations under the License. + + + @@ -319,6 +558,9 @@ limitations under the License. + + + @@ -330,6 +572,9 @@ limitations under the License. + + + @@ -341,6 +586,9 @@ limitations under the License. + + + @@ -351,6 +599,9 @@ limitations under the License. + + + @@ -362,6 +613,9 @@ limitations under the License. + + + @@ -372,20 +626,59 @@ limitations under the License. + + + - EnhancedCurrentHue - EnhancedColorMode - ColorLoopActive - ColorLoopDirection - ColorLoopTime - ColorLoopStartEnhancedHue - ColorLoopStoredEnhancedHue - ColorCapabilities - ColorTempPhysicalMinMireds - ColorTempPhysicalMaxMireds + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -396,6 +689,9 @@ limitations under the License. + + + @@ -406,6 +702,9 @@ limitations under the License. + + + @@ -417,6 +716,9 @@ limitations under the License. + + + @@ -428,6 +730,9 @@ limitations under the License. + + + @@ -441,6 +746,9 @@ limitations under the License. + + + @@ -449,6 +757,13 @@ limitations under the License. + + + + + + + @@ -461,6 +776,9 @@ limitations under the License. + + + @@ -474,6 +792,9 @@ limitations under the License. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/commissioner-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/commissioner-control-cluster.xml index dcfb1dfa7096b8..1422733cc0af76 100644 --- a/src/app/zap-templates/zcl/data-model/chip/commissioner-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/commissioner-control-cluster.xml @@ -32,9 +32,9 @@ limitations under the License. - - SupportedDeviceCategories + + @@ -44,6 +44,7 @@ limitations under the License. + @@ -51,6 +52,7 @@ limitations under the License. + @@ -60,6 +62,7 @@ limitations under the License. + @@ -68,6 +71,7 @@ limitations under the License. + diff --git a/src/app/zap-templates/zcl/data-model/chip/concentration-measurement-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/concentration-measurement-cluster.xml index 4d03c539103970..27b298ae25d14c 100644 --- a/src/app/zap-templates/zcl/data-model/chip/concentration-measurement-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/concentration-measurement-cluster.xml @@ -58,17 +58,59 @@ limitations under the License. - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - PeakMeasuredValue - PeakMeasuredValueWindow - AverageMeasuredValue - AverageMeasuredValueWindow - Uncertainty - MeasurementUnit - MeasurementMedium - LevelValue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -113,17 +155,59 @@ limitations under the License. - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - PeakMeasuredValue - PeakMeasuredValueWindow - AverageMeasuredValue - AverageMeasuredValueWindow - Uncertainty - MeasurementUnit - MeasurementMedium - LevelValue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -139,45 +223,87 @@ limitations under the License. - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - PeakMeasuredValue - PeakMeasuredValueWindow - AverageMeasuredValue - AverageMeasuredValueWindow - Uncertainty - MeasurementUnit - MeasurementMedium - LevelValue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -193,45 +319,87 @@ limitations under the License. - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - PeakMeasuredValue - PeakMeasuredValueWindow - AverageMeasuredValue - AverageMeasuredValueWindow - Uncertainty - MeasurementUnit - MeasurementMedium - LevelValue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -247,45 +415,87 @@ limitations under the License. - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - PeakMeasuredValue - PeakMeasuredValueWindow - AverageMeasuredValue - AverageMeasuredValueWindow - Uncertainty - MeasurementUnit - MeasurementMedium - LevelValue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -301,45 +511,87 @@ limitations under the License. - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - PeakMeasuredValue - PeakMeasuredValueWindow - AverageMeasuredValue - AverageMeasuredValueWindow - Uncertainty - MeasurementUnit - MeasurementMedium - LevelValue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -355,45 +607,87 @@ limitations under the License. - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - PeakMeasuredValue - PeakMeasuredValueWindow - AverageMeasuredValue - AverageMeasuredValueWindow - Uncertainty - MeasurementUnit - MeasurementMedium - LevelValue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -409,45 +703,87 @@ limitations under the License. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - PeakMeasuredValue - PeakMeasuredValueWindow - AverageMeasuredValue - AverageMeasuredValueWindow - Uncertainty - MeasurementUnit - MeasurementMedium - LevelValue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -463,45 +799,87 @@ limitations under the License. - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - PeakMeasuredValue - PeakMeasuredValueWindow - AverageMeasuredValue - AverageMeasuredValueWindow - Uncertainty - MeasurementUnit - MeasurementMedium - LevelValue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -517,45 +895,87 @@ limitations under the License. - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - PeakMeasuredValue - PeakMeasuredValueWindow - AverageMeasuredValue - AverageMeasuredValueWindow - Uncertainty - MeasurementUnit - MeasurementMedium - LevelValue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/content-app-observer-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/content-app-observer-cluster.xml index 6e241c7b5c3cd0..0f5a99b6ba9266 100644 --- a/src/app/zap-templates/zcl/data-model/chip/content-app-observer-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/content-app-observer-cluster.xml @@ -29,6 +29,7 @@ limitations under the License. Upon receipt, the data field MAY be parsed and interpreted. Message encoding is specific to the Content App. A Content App MAY when possible read attributes from the Basic Information Cluster on the Observer and use this to determine the Message encoding. + @@ -36,6 +37,7 @@ limitations under the License. + diff --git a/src/app/zap-templates/zcl/data-model/chip/content-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/content-control-cluster.xml index 06468c114c42dc..d628663fccaca4 100644 --- a/src/app/zap-templates/zcl/data-model/chip/content-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/content-control-cluster.xml @@ -43,69 +43,131 @@ limitations under the License. - Enabled - OnDemandRatings - OnDemandRatingThreshold - ScheduledContentRatings - ScheduledContentRatingThreshold - ScreenDailyTime - RemainingScreenTime - BlockUnrated + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The purpose of this command is to update the PIN used for protecting configuration of the content control settings. Upon success, the old PIN SHALL no longer work. The PIN is used to ensure that only the Node (or User) with the PIN code can make changes to the Content Control settings, for example, turn off Content Controls or modify the ScreenDailyTime. The PIN is composed of a numeric string of up to 6 human readable characters (displayable) . Upon receipt of this command, the media device SHALL check if the OldPIN field of this command is the same as the current PIN. If the PINs are the same, then the PIN code SHALL be set to NewPIN. Otherwise a response with InvalidPINCode error status SHALL be returned. The media device MAY provide a default PIN to the User via an out of band mechanism. For security reasons, it is recommended that a client encourage the user to update the PIN from its default value when performing configuration of the Content Control settings exposed by this cluster. The ResetPIN command can also be used to obtain the default PIN. + + + The purpose of this command is to reset the PIN. If this command is executed successfully, a ResetPINResponse command with a new PIN SHALL be returned. + + + This command SHALL be generated in response to a ResetPIN command. The data for this command SHALL be as follows: + + + The purpose of this command is to turn on the Content Control feature on a media device. On receipt of the Enable command, the media device SHALL set the Enabled attribute to TRUE. + The purpose of this command is to turn off the Content Control feature on a media device. On receipt of the Disable command, the media device SHALL set the Enabled attribute to FALSE. + The purpose of this command is to add the extra screen time for the user. If a client with Operate privilege invokes this command, the media device SHALL check whether the PINCode passed in the command matches the current PINCode value. If these match, then the RemainingScreenTime attribute SHALL be increased by the specified BonusTime value. If the PINs do not match, then a response with InvalidPINCode error status SHALL be returned, and no changes SHALL be made to RemainingScreenTime. If a client with Manage privilege or greater invokes this command, the media device SHALL ignore the PINCode field and directly increase the RemainingScreenTime attribute by the specified BonusTime value. A server that does not support the PM feature SHALL respond with InvalidPINCode to clients that only have Operate privilege unless: It has been provided with the PIN value to expect via an out of band mechanism, and The client has provided a PINCode that matches the expected PIN value. + + + The purpose of this command is to set the ScreenDailyTime attribute. On receipt of the SetScreenDailyTime command, the media device SHALL set the ScreenDailyTime attribute to the ScreenTime value. + + + The purpose of this command is to specify whether programs with no Content rating must be blocked by this media device. On receipt of the BlockUnratedContent command, the media device SHALL set the BlockUnrated attribute to TRUE. + + + The purpose of this command is to specify whether programs with no Content rating must be blocked by this media device. On receipt of the UnblockUnratedContent command, the media device SHALL set the BlockUnrated attribute to FALSE. + + + The purpose of this command is to set the OnDemandRatingThreshold attribute. On receipt of the SetOnDemandRatingThreshold command, the media device SHALL check if the Rating field is one of values present in the OnDemandRatings attribute. If not, then a response with InvalidRating error status SHALL be returned. + + + The purpose of this command is to set ScheduledContentRatingThreshold attribute. On receipt of the SetScheduledContentRatingThreshold command, the media device SHALL check if the Rating field is one of values present in the ScheduledContentRatings attribute. If not, then a response with InvalidRating error status SHALL be returned. + + + This event SHALL be generated when the RemainingScreenTime equals 0. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/content-launch-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/content-launch-cluster.xml index 7058f969799087..4d96173013856f 100644 --- a/src/app/zap-templates/zcl/data-model/chip/content-launch-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/content-launch-cluster.xml @@ -25,10 +25,18 @@ limitations under the License. true This cluster provides an interface for launching content on a media player device such as a TV or Speaker. - - AcceptHeader - SupportedStreamingProtocols - + + + + + + + + + + + + Upon receipt, this SHALL launch the specified content with optional search criteria. @@ -36,6 +44,9 @@ limitations under the License. + + + @@ -43,12 +54,21 @@ limitations under the License. + + + This command SHALL be generated in response to LaunchContent command. + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/descriptor-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/descriptor-cluster.xml index d63dbeb05ca11a..b7495d2d84302d 100644 --- a/src/app/zap-templates/zcl/data-model/chip/descriptor-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/descriptor-cluster.xml @@ -44,11 +44,23 @@ limitations under the License. - - DeviceTypeList - ServerList - ClientList - PartsList - TagList + + + + + + + + + + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/device-energy-management-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/device-energy-management-cluster.xml index 3550dd0301be99..2d551a2d428121 100644 --- a/src/app/zap-templates/zcl/data-model/chip/device-energy-management-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/device-energy-management-cluster.xml @@ -74,41 +74,87 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 - ESAType - ESACanGenerate - ESAState - AbsMinPower - AbsMaxPower + + + + + + + + + + + + + + + - PowerAdjustmentCapability + + + + + - Forecast - OptOutState + + + + + + + + + + + + + + + + + + + Allows a client to request an adjustment in the power consumption of an ESA for a specified duration. + + + Allows a client to cancel an ongoing PowerAdjustmentRequest operation. + + + Allows a client to adjust the start time of a Forecast sequence that has not yet started operation (i.e. where the current Forecast StartTime is in the future). + + + Allows a client to temporarily pause an operation and reduce the ESAs energy demand. + + + Allows a client to cancel the PauseRequest command and enable earlier resumption of operation. + + + @@ -116,20 +162,36 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 + + + Allows a client to ask the ESA to recompute its Forecast based on power and time constraints. + + + Allows a client to request cancellation of a previous adjustment request in a StartTimeAdjustRequest, ModifyForecastRequest or RequestConstraintBasedForecast command. + + + + + + + This event SHALL be generated when the Power Adjustment session is started. + + + @@ -137,15 +199,24 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 + + + This event SHALL be generated when the ESA enters the Paused state. + + + This event SHALL be generated when the ESA leaves the Paused state and resumes operation. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/device-energy-management-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/device-energy-management-mode-cluster.xml index c3440adebef3f6..bad3b92e06179c 100644 --- a/src/app/zap-templates/zcl/data-model/chip/device-energy-management-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/device-energy-management-mode-cluster.xml @@ -59,18 +59,24 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 - SupportedModes - CurrentMode + + + + + + This command is used to change device modes. + This command is sent by the device on receipt of the ChangeToMode command. + diff --git a/src/app/zap-templates/zcl/data-model/chip/diagnostic-logs-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/diagnostic-logs-cluster.xml index 27162f66e5e6db..4140fd18a0eaec 100644 --- a/src/app/zap-templates/zcl/data-model/chip/diagnostic-logs-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/diagnostic-logs-cluster.xml @@ -15,46 +15,48 @@ See the License for the specific language governing permissions and limitations under the License. --> - - - - - - - - - - - - - - - - - - - - - - Diagnostic Logs - CHIP - The cluster provides commands for retrieving unstructured diagnostic logs from a Node that may be used to aid in diagnostics. - 0x0032 - DIAGNOSTIC_LOGS_CLUSTER - true - true - - Retrieving diagnostic logs from a Node - - - - - - Response to the RetrieveLogsRequest - - - - - - + + + + + + + + + + + + + + + + + + + + + + Diagnostic Logs + CHIP + The cluster provides commands for retrieving unstructured diagnostic logs from a Node that may be used to aid in diagnostics. + 0x0032 + DIAGNOSTIC_LOGS_CLUSTER + true + true + + Retrieving diagnostic logs from a Node + + + + + + + Response to the RetrieveLogsRequest + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/dishwasher-alarm-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/dishwasher-alarm-cluster.xml index 7e41a7a1c03f99..f460f42a1971ae 100644 --- a/src/app/zap-templates/zcl/data-model/chip/dishwasher-alarm-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/dishwasher-alarm-cluster.xml @@ -43,27 +43,42 @@ limitations under the License. - Mask - Latch - State - Supported + + + + + + + + + + + + + + - Reset alarm - + Reset alarm + + + + - Modify enabled alarms - + Modify enabled alarms + + - Notify - - - - + Notify + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/dishwasher-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/dishwasher-mode-cluster.xml index 7c7dec635f3b6c..49403ab54716be 100644 --- a/src/app/zap-templates/zcl/data-model/chip/dishwasher-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/dishwasher-mode-cluster.xml @@ -57,11 +57,15 @@ limitations under the License. - SupportedModes - CurrentMode + + + + + + StartUpMode OnMode - + @@ -69,6 +73,7 @@ limitations under the License. On receipt of this command the device SHALL respond with a ChangeToModeResponse command. + @@ -77,6 +82,7 @@ limitations under the License. + diff --git a/src/app/zap-templates/zcl/data-model/chip/door-lock-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/door-lock-cluster.xml index b25cd549d90091..03042ad346ff2d 100644 --- a/src/app/zap-templates/zcl/data-model/chip/door-lock-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/door-lock-cluster.xml @@ -131,659 +131,856 @@ limitations under the License. 3. Everything that depends on a certain feature is optional because we have no way of setting up the dependencies here. Dependencies would be probably resolved in the cluster itself. Those attributes/commands are marked with a special comment. --> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This command causes the lock device to lock the door. + + + + + + This command causes the lock device to unlock the door. + + + + + + + This command causes the lock device to unlock the door with a timeout parameter. + + + + + + + + Set a weekly repeating schedule for a specified user. + + + + + + + + + + + + + + + Retrieve the specific weekly schedule for the specific user. + + + + + + + + + + Returns the weekly repeating schedule data for the specified schedule index. + + + + + + + + + + + + + + + Clear the specific weekly schedule or all weekly schedules for the specific user. + + + + + + + + + + Set a time-specific schedule ID for a specified user. + + + + + + + + + + + + Returns the year day schedule data for the specified schedule and user indexes. + + + + + + + + + + Returns the year day schedule data for the specified schedule and user indexes. + + + + + + + + + + + + Clears the specific year day schedule or all year day schedules for the specific user. + + + + + + + + + + Set the holiday Schedule by specifying local start time and local end time with respect to any Lock Operating Mode. + + + + + + + + + + + + Get the holiday schedule for the specified index. + + + + + + + + + Returns the Holiday Schedule Entry for the specified Holiday ID. + + + + + + + + + + + + Clears the holiday schedule or all holiday schedules. + + + + + + + + + Set User into the lock. + + + + + + + + + + + + + + + Retrieve User. + + + + + + + + + Returns the User for the specified UserIndex. + + + + + + + + + + + + + + + + + Clears a User or all Users. + + + + + + + + + Set a credential (e.g. PIN, RFID, Fingerprint, etc.) into the lock for a new user, existing user, or ProgrammingUser. + + + + + + + + + + + + + + Returns the status for setting the specified credential. + + + + + + + + + + Retrieve the status of a particular credential (e.g. PIN, RFID, Fingerprint, etc.) by index. + + + + + + + + + Returns the status for the specified credential. + + + + + + + + + + + + + Clear one, one type, or all credentials except ProgrammingPIN credential. + + + + + + + + This command causes the lock device to unlock the door without pulling the latch. + + + + + + + + This command communicates an Aliro Reader configuration to the lock. + + + + + + + + + + + This command clears an existing Aliro Reader configuration for the lock. + + + + + - - LockState - LockType - ActuatorEnabled - - DoorState - - - DoorOpenEvents - - - - - - DoorClosedEvents - - - - - - OpenPeriod - - - - - NumberOfTotalUsersSupported - - NumberOfPINUsersSupported - - NumberOfRFIDUsersSupported - - NumberOfWeekDaySchedulesSupportedPerUser - - NumberOfYearDaySchedulesSupportedPerUser - - NumberOfHolidaySchedulesSupported - - MaxPINCodeLength - - MinPINCodeLength - - MaxRFIDCodeLength - - MinRFIDCodeLength - - CredentialRulesSupport - - NumberOfCredentialsSupportedPerUser - - Language - - - - - LEDSettings - - - - - AutoRelockTime - - - - - SoundVolume - - - - - OperatingMode - - - - SupportedOperatingModes - DefaultConfigurationRegister - - EnableLocalProgramming - - - - - EnableOneTouchLocking - - - - - EnableInsideStatusLED - - - - - EnablePrivacyModeButton - - - - - LocalProgrammingFeatures - - - - - - WrongCodeEntryLimit - - - - - - UserCodeTemporaryDisableTime - - - - - - SendPINOverTheAir - - - - - - RequirePINforRemoteOperation - - - - - - - ExpiringUserTimeout - - - - - - AliroReaderVerificationKey - - - - - AliroReaderGroupIdentifier - - - - - AliroReaderGroupSubIdentifier - - - - - AliroExpeditedTransactionSupportedProtocolVersions - - - - - AliroGroupResolvingKey - - - - - AliroSupportedBLEUWBProtocolVersions - - - - - AliroBLEAdvertisingVersion - - - - NumberOfAliroCredentialIssuerKeysSupported - - NumberOfAliroEndpointKeysSupported - - - - This command causes the lock device to lock the door. - - - - - This command causes the lock device to unlock the door. - - - - - - This command causes the lock device to unlock the door with a timeout parameter. - - - - - - - Set a weekly repeating schedule for a specified user. - - - - - - - - - - - - Retrieve the specific weekly schedule for the specific user. - - - - - - - Returns the weekly repeating schedule data for the specified schedule index. - - - - - - - - - - - - Clear the specific weekly schedule or all weekly schedules for the specific user. - - - - - - - Set a time-specific schedule ID for a specified user. - - - - - - - - - Returns the year day schedule data for the specified schedule and user indexes. - - - - - - - Returns the year day schedule data for the specified schedule and user indexes. - - - - - - - - - Clears the specific year day schedule or all year day schedules for the specific user. - - - - - - - Set the holiday Schedule by specifying local start time and local end time with respect to any Lock Operating Mode. - - - - - - - - - Get the holiday schedule for the specified index. - - - - - - Returns the Holiday Schedule Entry for the specified Holiday ID. - - - - - - - - - Clears the holiday schedule or all holiday schedules. - - - - - - Set User into the lock. - - - - - - - - - - - - Retrieve User. - - - - - - Returns the User for the specified UserIndex. - - - - - - - - - - - - - - Clears a User or all Users. - - - - - - Set a credential (e.g. PIN, RFID, Fingerprint, etc.) into the lock for a new user, existing user, or ProgrammingUser. - - - - - - - - - - - Returns the status for setting the specified credential. - - - - - - - Retrieve the status of a particular credential (e.g. PIN, RFID, Fingerprint, etc.) by index. - - - - - - Returns the status for the specified credential. - - - - - - - - - - Clear one, one type, or all credentials except ProgrammingPIN credential. - - - - - This command causes the lock device to unlock the door without pulling the latch. - - - - - This command communicates an Aliro Reader configuration to the lock. - - - - - - - - This command clears an existing Aliro Reader configuration for the lock. - - - - - - - The door lock cluster provides several alarms which can be sent when there is a critical state on the door lock. - - - - - The door lock server sends out a DoorStateChange event when the door lock door state changes. - - - - The door lock server sends out a LockOperation event when the event is triggered by the various lock operation sources. - - - - - - - - - - The door lock server sends out a LockOperationError event when a lock operation fails for various reasons. - - - - - - - - - - - The door lock server sends out a LockUserChange event when a lock user, schedule, or credential change has occurred. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + The door lock cluster provides several alarms which can be sent when there is a critical state on the door lock. + + + + + + The door lock server sends out a DoorStateChange event when the door lock door state changes. + + + + + + + The door lock server sends out a LockOperation event when the event is triggered by the various lock operation sources. + + + + + + + + + + + The door lock server sends out a LockOperationError event when a lock operation fails for various reasons. + + + + + + + + + + + + The door lock server sends out a LockUserChange event when a lock user, schedule, or credential change has occurred. + + + + + + + + + + + + - - - - - - - - - - - + + + + + + + + + + + + - - - - - - - - - - - - + + + + + + - - - - - - + + + + + + - - - - - - - - - - + + + + + - - - - - - - - - + + + + + + + + + + + + - - - - - - - - - - - - - - - - - + + + + + + - - - - - - - - + + + + + + + + + + - - - - - - - - + + + + + + + + + - - - - - - - - + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - + + + + + + + + - - - - - - + + + + + + + + - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - + + + + + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + - - - - - - - - - - - - - - - - + + + + + + + + + - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + @@ -796,7 +993,7 @@ limitations under the License. - + @@ -808,7 +1005,7 @@ limitations under the License. - + @@ -824,7 +1021,7 @@ limitations under the License. - + @@ -836,7 +1033,7 @@ limitations under the License. - + @@ -846,7 +1043,7 @@ limitations under the License. - + @@ -858,7 +1055,7 @@ limitations under the License. - + diff --git a/src/app/zap-templates/zcl/data-model/chip/drlc-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/drlc-cluster.xml index d64bce1c85b7f6..752a917fd33ff6 100644 --- a/src/app/zap-templates/zcl/data-model/chip/drlc-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/drlc-cluster.xml @@ -199,21 +199,33 @@ limitations under the License. - LoadControlPrograms - NumberOfLoadControlPrograms - Events - ActiveEvents - NumberOfEventsPerProgram - NumberOfTransitions - - DefaultRandomStart + + + + + + + + + + + + + + + + + + + + - - DefaultRandomDuration + + @@ -221,18 +233,21 @@ limitations under the License. Upon receipt, this SHALL insert a new LoadControlProgramStruct into LoadControlPrograms, or if the ProgramID matches an existing LoadControlProgramStruct, then the provider SHALL be updated with the provided values. + Upon receipt, this SHALL remove a the LoadControlProgramStruct from LoadControlPrograms with the matching ProgramID. + On receipt of the AddLoadControlEventsRequest command, the server SHALL add a load control event. + @@ -240,6 +255,7 @@ limitations under the License. + + diff --git a/src/app/zap-templates/zcl/data-model/chip/ecosystem-information-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/ecosystem-information-cluster.xml index 73ae522365f410..06f931ef0783d2 100644 --- a/src/app/zap-templates/zcl/data-model/chip/ecosystem-information-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/ecosystem-information-cluster.xml @@ -44,12 +44,10 @@ limitations under the License. true - - DeviceDirectory + - - LocationDirectory + diff --git a/src/app/zap-templates/zcl/data-model/chip/electrical-energy-measurement-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/electrical-energy-measurement-cluster.xml index eb05052538d2de..c8501c412c19d5 100644 --- a/src/app/zap-templates/zcl/data-model/chip/electrical-energy-measurement-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/electrical-energy-measurement-cluster.xml @@ -42,25 +42,65 @@ limitations under the License. - Accuracy - CumulativeEnergyImported + + + + + + + + + + + - CumulativeEnergyExported + + + + + + + + - PeriodicEnergyImported + + + + + + + + - PeriodicEnergyExported - CumulativeEnergyReset + + + + + + + + + + + + + CumulativeEnergyMeasured + + + PeriodicEnergyMeasured + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/electrical-power-measurement-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/electrical-power-measurement-cluster.xml index 7f49a643d1b1f9..0a4fccb6b914f4 100644 --- a/src/app/zap-templates/zcl/data-model/chip/electrical-power-measurement-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/electrical-power-measurement-cluster.xml @@ -51,40 +51,105 @@ limitations under the License. - PowerMode - NumberOfMeasurementTypes - Accuracy - Ranges - Voltage + + + + + + + + + + + + + + + - ActiveCurrent + + + - ReactiveCurrent - ApparentCurrent + + + + + + + + + + - ActivePower + + + - ReactivePower + + + + + - ApparentPower + + + + + - RMSVoltage + + + + + - RMSCurrent + + + + + - RMSPower + + + + + - Frequency + + + + + - HarmonicCurrents + + + + + - HarmonicPhases + + + + + - PowerFactor - NeutralCurrent + + + + + + + + + + MeasurementPeriodRanges + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/energy-evse-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/energy-evse-cluster.xml index 7a4a40d2e39966..8c26a925876744 100644 --- a/src/app/zap-templates/zcl/data-model/chip/energy-evse-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/energy-evse-cluster.xml @@ -128,53 +128,119 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 - State - SupplyState - FaultState - ChargingEnabledUntil + + + + + + + + + + + + - DischargingEnabledUntil - CircuitCapacity - MinimumChargeCurrent - MaximumChargeCurrent + + + + + + + + + + + + + + - MaximumDischargeCurrent + + + + + UserMaximumChargeCurrent + RandomizationDelayWindow + - NextChargeStartTime + + + + + - NextChargeTargetTime + + + + + - NextChargeRequiredEnergy + + + + + - NextChargeTargetSoC + + + + + ApproximateEVEfficiency + + + - StateOfCharge + + + + + - BatteryCapacity + + + + + - VehicleID - SessionID - SessionDuration - SessionEnergyCharged + + + + + + + + + + + + + + - SessionEnergyDischarged + + + + + Allows a client to disable the EVSE from charging and discharging. + @@ -182,39 +248,57 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 This command allows a client to enable the EVSE to charge an EV, and to provide or update the maximum and minimum charge current. + Upon receipt, this SHALL allow a client to enable the discharge of an EV, and to provide or update the maximum discharge current. + + + Allows a client to put the EVSE into a self-diagnostics mode. + Allows a client to set the user specified charging targets. + + + Allows a client to retrieve the current set of charging targets. + + + Allows a client to clear all stored charging targets. + + + The GetTargetsResponse is sent in response to the GetTargets Command. + + + This event SHALL be generated when the EV is plugged in. + @@ -224,6 +308,7 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 + @@ -232,6 +317,7 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 + @@ -241,6 +327,7 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 + @@ -249,11 +336,15 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 + This event SHALL be generated when a RFID card has been read. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/energy-evse-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/energy-evse-mode-cluster.xml index b28daf8899636c..52b066d7b84fdf 100644 --- a/src/app/zap-templates/zcl/data-model/chip/energy-evse-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/energy-evse-mode-cluster.xml @@ -59,18 +59,24 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 - SupportedModes - CurrentMode + + + + + + This command is used to change device modes. + This command is sent by the device on receipt of the ChangeToMode command. + diff --git a/src/app/zap-templates/zcl/data-model/chip/energy-preference-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/energy-preference-cluster.xml index a5e1ea8e950ae1..19fdceb111676f 100644 --- a/src/app/zap-templates/zcl/data-model/chip/energy-preference-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/energy-preference-cluster.xml @@ -34,26 +34,43 @@ limitations under the License. - EnergyBalances - + + + + + + - + - CurrentEnergyBalance + + + - EnergyPriorities + + + + + - LowPowerModeSensitivities + + + + + - + CurrentLowPowerModeSensitivity + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/ethernet-network-diagnostics-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/ethernet-network-diagnostics-cluster.xml index f2cf3173c68b29..5474ebaba2eb15 100644 --- a/src/app/zap-templates/zcl/data-model/chip/ethernet-network-diagnostics-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/ethernet-network-diagnostics-cluster.xml @@ -37,26 +37,60 @@ limitations under the License. The Ethernet Network Diagnostics Cluster provides a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. - + + + + + + + + + - - + + - - - - PHYRate - FullDuplex - PacketRxCount - PacketTxCount - TxErrCount - CollisionCount - OverrunCount - CarrierDetect - TimeSinceReset + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Reception of this command SHALL reset the attributes: PacketRxCount, PacketTxCount, TxErrCount, CollisionCount, OverrunCount to 0 + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/fixed-label-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/fixed-label-cluster.xml index 96e420f01902de..67506a1827e2fe 100644 --- a/src/app/zap-templates/zcl/data-model/chip/fixed-label-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/fixed-label-cluster.xml @@ -31,6 +31,8 @@ limitations under the License. FIXED_LABEL_CLUSTER The Fixed Label Cluster provides a feature for the device to tag an endpoint with zero or more read only labels. - LabelList + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/flow-measurement-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/flow-measurement-cluster.xml index 3e546e968514ea..14b22a16b19e3c 100644 --- a/src/app/zap-templates/zcl/data-model/chip/flow-measurement-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/flow-measurement-cluster.xml @@ -24,10 +24,18 @@ limitations under the License. FLOW_MEASUREMENT_CLUSTER true true - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - Tolerance + + + + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/general-commissioning-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/general-commissioning-cluster.xml index 167f7d13e322af..f7f81c3f59d624 100644 --- a/src/app/zap-templates/zcl/data-model/chip/general-commissioning-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/general-commissioning-cluster.xml @@ -52,45 +52,80 @@ limitations under the License. - - Breadcrumb + + - BasicCommissioningInfo - RegulatoryConfig - LocationCapability - SupportsConcurrentConnection - - TCAcceptedVersion + + + + + + + + + + + + + + + + + + + - - TCMinRequiredVersion + + + + + + + - - TCAcknowledgements + + + + + + + - - TCAcknowledgementsRequired + + + + + + + - - TCUpdateDeadline + + + + + + + Arm the persistent fail-safe timer with an expiry time of now + ExpiryLengthSeconds using device clock + Success/failure response for ArmFailSafe command + Set the regulatory configuration to be used during commissioning @@ -98,30 +133,46 @@ limitations under the License. + Success/failure response for SetRegulatoryConfig command + Signals the Server that the Client has successfully completed all steps of Commissioning/Recofiguration needed during fail-safe period. + Indicates to client whether CommissioningComplete command succeeded + This command sets the user acknowledgements received in the Enhanced Setup Flow Terms and Conditions into the node. + + + + + + This command is used to convey the result from SetTCAcknowledgements. + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/general-diagnostics-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/general-diagnostics-cluster.xml index 26f0e5708dd280..c3bae609c66a21 100644 --- a/src/app/zap-templates/zcl/data-model/chip/general-diagnostics-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/general-diagnostics-cluster.xml @@ -92,17 +92,35 @@ limitations under the License. - NetworkInterfaces - RebootCount + + + + + + - UpTime - TotalOperationalHours - BootReason - ActiveHardwareFaults - ActiveRadioFaults - ActiveNetworkFaults - TestEventTriggersEnabled + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -> -> -> -> -> - - - - - - IdleModeDuration - ActiveModeDuration - ActiveModeThreshold - - RegisteredClients - - - - ICDCounter - - - ClientsSupportedPerFabric - UserActiveModeTriggerHint - UserActiveModeTriggerInstruction - OperatingMode - MaximumCheckInBackOff - - - Register a client to the end device - - - - - - - - - - RegisterClient response command - - - - - Unregister a client from an end device - - - - - - - Request the end device to stay in Active Mode for an additional ActiveModeThreshold - - - - - - StayActiveRequest response command - - - + + General + ICD Management + 0x0046 + ICD_MANAGEMENT_CLUSTER + Allows servers to ensure that listed clients are notified when a server is available for communication. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Register a client to the end device + + + + + + + + + + + + + RegisterClient response command + + + + + + + + Unregister a client from an end device + + + + + + + + + + Request the end device to stay in Active Mode for an additional ActiveModeThreshold + + + + + + + + + + + + StayActiveRequest response command + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/identify-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/identify-cluster.xml index b64eb7702f1517..e2a2a7fd59cdff 100644 --- a/src/app/zap-templates/zcl/data-model/chip/identify-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/identify-cluster.xml @@ -51,16 +51,21 @@ limitations under the License. true true - - IdentifyTime - IdentifyType - + + + + + + + + Command description for Identify + @@ -69,6 +74,7 @@ limitations under the License. + diff --git a/src/app/zap-templates/zcl/data-model/chip/illuminance-measurement-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/illuminance-measurement-cluster.xml index b744964ca0a9aa..be373be05c1f2a 100644 --- a/src/app/zap-templates/zcl/data-model/chip/illuminance-measurement-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/illuminance-measurement-cluster.xml @@ -18,19 +18,29 @@ limitations under the License. - Illuminance Measurement - Measurement & Sensing - Attributes and commands for configuring the measurement of illuminance, and reporting illuminance measurements. - 0x0400 - ILLUMINANCE_MEASUREMENT_CLUSTER - true - true - - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - Tolerance - LightSensorType + Illuminance Measurement + Measurement & Sensing + Attributes and commands for configuring the measurement of illuminance, and reporting illuminance measurements. + 0x0400 + ILLUMINANCE_MEASUREMENT_CLUSTER + true + true + + + + + + + + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/keypad-input-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/keypad-input-cluster.xml index b43ace5c0c8383..c21a58ca0f0fbf 100644 --- a/src/app/zap-templates/zcl/data-model/chip/keypad-input-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/keypad-input-cluster.xml @@ -40,11 +40,13 @@ limitations under the License. Upon receipt, this SHALL process a keycode as input to the media device. + This command SHALL be generated in response to a SendKey Request command. + diff --git a/src/app/zap-templates/zcl/data-model/chip/laundry-dryer-controls-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/laundry-dryer-controls-cluster.xml index f126d8836f720c..e18476fdb230d8 100644 --- a/src/app/zap-templates/zcl/data-model/chip/laundry-dryer-controls-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/laundry-dryer-controls-cluster.xml @@ -36,9 +36,13 @@ limitations under the License. This cluster provides a way to access options associated with the operation of a laundry dryer device type. - - - SupportedDrynessLevels - SelectedDrynessLevel - + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/laundry-washer-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/laundry-washer-mode-cluster.xml index b8afd87d76665c..8ceab130559836 100644 --- a/src/app/zap-templates/zcl/data-model/chip/laundry-washer-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/laundry-washer-mode-cluster.xml @@ -58,11 +58,15 @@ limitations under the License. - SupportedModes - CurrentMode + + + + + + StartUpMode OnMode - + @@ -70,6 +74,7 @@ limitations under the License. On receipt of this command the device SHALL respond with a ChangeToModeResponse command. + @@ -78,6 +83,7 @@ limitations under the License. + diff --git a/src/app/zap-templates/zcl/data-model/chip/level-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/level-control-cluster.xml index 4d0e67ddbd1b47..448b5ff0c98eec 100644 --- a/src/app/zap-templates/zcl/data-model/chip/level-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/level-control-cluster.xml @@ -61,25 +61,63 @@ limitations under the License. - - CurrentLevel - RemainingTime - MinLevel - MaxLevel - CurrentFrequency - MinFrequency - MaxFrequency - - OnOffTransitionTime - OnLevel - OnTransitionTime - OffTransitionTime - DefaultMoveRate - Options - - StartUpCurrentLevel + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -90,6 +128,7 @@ limitations under the License. + @@ -100,6 +139,7 @@ limitations under the License. + @@ -111,6 +151,7 @@ limitations under the License. + @@ -119,6 +160,7 @@ limitations under the License. + @@ -129,6 +171,7 @@ limitations under the License. + @@ -139,6 +182,7 @@ limitations under the License. + @@ -150,6 +194,7 @@ limitations under the License. + @@ -158,6 +203,7 @@ limitations under the License. + @@ -166,6 +212,9 @@ limitations under the License. approximation if the exact provided one is not possible. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/localization-configuration-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/localization-configuration-cluster.xml index 9bdededd0fcd6e..bd1149e9b0fa4e 100644 --- a/src/app/zap-templates/zcl/data-model/chip/localization-configuration-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/localization-configuration-cluster.xml @@ -28,10 +28,12 @@ limitations under the License. standards. As such, Nodes that visually or audibly convey information need a mechanism by which they can be configured to use a user’s preferred language, units, etc - - ActiveLocale + + + + + - SupportedLocales diff --git a/src/app/zap-templates/zcl/data-model/chip/low-power-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/low-power-cluster.xml index c1cc5b38ede202..4b9ea09104994e 100644 --- a/src/app/zap-templates/zcl/data-model/chip/low-power-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/low-power-cluster.xml @@ -26,6 +26,7 @@ limitations under the License. This cluster provides an interface for managing low power mode on a device. This command shall put the device into low power mode. + diff --git a/src/app/zap-templates/zcl/data-model/chip/media-input-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/media-input-cluster.xml index 597b285cc1b5dd..1e1da7336593dc 100644 --- a/src/app/zap-templates/zcl/data-model/chip/media-input-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/media-input-cluster.xml @@ -32,20 +32,27 @@ limitations under the License. - InputList - CurrentInput + + + + + + Upon receipt, this SHALL change the input on the media device to the input at a specific index in the Input List. + Upon receipt, this SHALL display the active status of the input list on screen. + Upon receipt, this SHALL hide the input list from the screen. + @@ -53,6 +60,9 @@ limitations under the License. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/media-playback-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/media-playback-cluster.xml index a77b8fa4befb4c..9e0896f777988c 100644 --- a/src/app/zap-templates/zcl/data-model/chip/media-playback-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/media-playback-cluster.xml @@ -46,87 +46,156 @@ limitations under the License. - CurrentState - StartTime - Duration - SampledPosition - PlaybackSpeed - SeekRangeEnd - SeekRangeStart - ActiveAudioTrack - AvailableAudioTracks - ActiveTextTrack - AvailableTextTracks + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Upon receipt, this SHALL play media. + Upon receipt, this SHALL pause media. + Upon receipt, this SHALL stop media. User experience is context-specific. This will often navigate the user back to the location where media was originally launched. + Upon receipt, this SHALL Start Over with the current media playback item. + Upon receipt, this SHALL cause the handler to be invoked for "Previous". User experience is context-specific. This will often Go back to the previous media playback item. + Upon receipt, this SHALL cause the handler to be invoked for "Next". User experience is context-specific. This will often Go forward to the next media playback item. + Upon receipt, this SHALL Rewind through media. Different Rewind speeds can be used on the TV based upon the number of sequential calls to this function. This is to avoid needing to define every speed now (multiple fast, slow motion, etc). + + + Upon receipt, this SHALL Advance through media. Different FF speeds can be used on the TV based upon the number of sequential calls to this function. This is to avoid needing to define every speed now (multiple fast, slow motion, etc). + + + Upon receipt, this SHALL Skip forward in the media by the given number of seconds, using the data as follows: + Upon receipt, this SHALL Skip backward in the media by the given number of seconds, using the data as follows: + Upon receipt, this SHALL Skip backward in the media by the given number of seconds, using the data as follows: + + + This command SHALL be generated in response to various Playback Request commands. + Upon receipt, the server SHALL set the active Audio Track to the one identified by the TrackID in the Track catalog for the streaming media. If the TrackID does not exist in the Track catalog, OR does not correspond to the streaming media OR no media is being streamed at the time of receipt of this command, the server will return an error status of INVALID_ARGUMENT. + + + Upon receipt, the server SHALL set the active Text Track to the one identified by the TrackID in the Track catalog for the streaming media. If the TrackID does not exist in the Track catalog, OR does not correspond to the streaming media OR no media is being streamed at the time of receipt of this command, the server SHALL return an error status of INVALID_ARGUMENT. + + + If a Text Track is active (i.e. being displayed), upon receipt of this command, the server SHALL stop displaying it. + + + @@ -140,6 +209,7 @@ limitations under the License. + diff --git a/src/app/zap-templates/zcl/data-model/chip/messages-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/messages-cluster.xml index 741ba801f5c092..52581674888a29 100644 --- a/src/app/zap-templates/zcl/data-model/chip/messages-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/messages-cluster.xml @@ -91,8 +91,12 @@ limitations under the License. - Messages - ActiveMessageIDs + + + + + + Command for requesting messages be presented @@ -104,20 +108,24 @@ limitations under the License. + Command for cancelling message present requests + This event SHALL be generated when the message is confirmed by the user, or when the expiration date of the message is reached. + This event SHALL be generated when the message is presented to the user. + This event SHALL be generated when the message is confirmed by the user, or when the expiration date of the message is reached. @@ -125,6 +133,7 @@ limitations under the License. + - \ No newline at end of file + diff --git a/src/app/zap-templates/zcl/data-model/chip/microwave-oven-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/microwave-oven-control-cluster.xml index 954bd898b6aa00..6ee5fac92c5210 100644 --- a/src/app/zap-templates/zcl/data-model/chip/microwave-oven-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/microwave-oven-control-cluster.xml @@ -41,27 +41,65 @@ limitations under the License. - CookTime - MaxCookTime - PowerSetting - MinPower - MaxPower - PowerStep - SupportedWatts - SelectedWattIndex - WattRating - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - Set Cooking Parameters + Set Cooking Parameters + - Add More Cooking Time - + Add More Cooking Time + + diff --git a/src/app/zap-templates/zcl/data-model/chip/microwave-oven-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/microwave-oven-mode-cluster.xml index 856fde36da15ee..f217da41608f3d 100644 --- a/src/app/zap-templates/zcl/data-model/chip/microwave-oven-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/microwave-oven-mode-cluster.xml @@ -55,7 +55,11 @@ limitations under the License. - SupportedModes - CurrentMode + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/mode-select-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/mode-select-cluster.xml index 443acb1c955c36..adc776dbe68482 100644 --- a/src/app/zap-templates/zcl/data-model/chip/mode-select-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/mode-select-cluster.xml @@ -48,19 +48,33 @@ limitations under the License. Attributes and commands for selecting a mode from a list of supported options. - Description - StandardNamespace - SupportedModes - CurrentMode - StartUpMode - OnMode - + + + + + + + + + + + + + + + + + + + + On receipt of this command, if the NewMode field matches the Mode field in an entry of the SupportedModes list, the server SHALL set the CurrentMode attribute to the NewMode value, otherwise, the server SHALL respond with an INVALID_COMMAND status response. + diff --git a/src/app/zap-templates/zcl/data-model/chip/network-commissioning-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/network-commissioning-cluster.xml index 964923be4f2dfa..33533dfa24d4e7 100644 --- a/src/app/zap-templates/zcl/data-model/chip/network-commissioning-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/network-commissioning-cluster.xml @@ -107,120 +107,196 @@ limitations under the License. - - + + + + - - MaxNetworks + + - - Networks + + + + + + + + + + + + + + + + + + - ScanMaxTimeSeconds - ConnectMaxTimeSeconds - - InterfaceEnabled + + - - LastNetworkingStatus + + - - LastNetworkID + + - - LastConnectErrorValue + + - - SupportedWiFiBands + + + + - - SupportedThreadFeatures + + + + - - ThreadVersion + + + + - - Detemine the set of networks the device sees as available. - - - - - - Relay the set of networks the device sees as available back to the client. - - - - - - - Add or update the credentials for a given Wi-Fi network. - - - - - - - - - - Add or update the credentials for a given Thread network. - - - - - - Remove the definition of a given network (including its credentials). - - - - - - Response command for various commands that add/remove/modify network credentials. - - - - - - - - Connect to the specified network, using previously-defined credentials. - - - - - - Command that indicates whether we have succcessfully connected to a network. - - - - - - Modify the order in which networks will be presented in the Networks attribute. - - - - - - - Retrieve details about and optionally proof of possession of a network client identity. - - - - - - Command that contains details about a network client identity and optionally a proof of possession. - - - - + + Detemine the set of networks the device sees as available. + + + + + + + + + + + + Relay the set of networks the device sees as available back to the client. + + + + + + + + + + + + + Add or update the credentials for a given Wi-Fi network. + + + + + + + + + + + + + Add or update the credentials for a given Thread network. + + + + + + + + + Remove the definition of a given network (including its credentials). + + + + + + + + + + + + Response command for various commands that add/remove/modify network credentials. + + + + + + + + + + + + + + Connect to the specified network, using previously-defined credentials. + + + + + + + + + + + + Command that indicates whether we have succcessfully connected to a network. + + + + + + + + + + + + Modify the order in which networks will be presented in the Networks attribute. + + + + + + + + + + + + + Retrieve details about and optionally proof of possession of a network client identity. + + + + + + + + + Command that contains details about a network client identity and optionally a proof of possession. + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/occupancy-sensing-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/occupancy-sensing-cluster.xml index 0141a7542f4d78..414eb2c287e5e7 100644 --- a/src/app/zap-templates/zcl/data-model/chip/occupancy-sensing-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/occupancy-sensing-cluster.xml @@ -83,74 +83,274 @@ limitations under the License. - Occupancy - OccupancySensorType - OccupancySensorTypeBitmap - - - HoldTime - + + + + + + + + + + + + + + - HoldTimeLimits + + + + - - PIROccupiedToUnoccupiedDelay + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - PIRUnoccupiedToOccupiedDelay + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - PIRUnoccupiedToOccupiedThreshold + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - UltrasonicOccupiedToUnoccupiedDelay + + + + + + + + + + - - UltrasonicUnoccupiedToOccupiedDelay + + + + + + + + + + + + + + + + + - - UltrasonicUnoccupiedToOccupiedThreshold + + + + + + + + + + + + + + + + + - - PhysicalContactOccupiedToUnoccupiedDelay + + + + + + + + + + - - PhysicalContactUnoccupiedToOccupiedDelay + + + + + + + + + + + + + + + + + - - PhysicalContactUnoccupiedToOccupiedThreshold + + + + + + + + + + + + + + + + + If this event is supported, it SHALL be generated when the Occupancy attribute changes. + diff --git a/src/app/zap-templates/zcl/data-model/chip/onoff-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/onoff-cluster.xml index 04dcfed83766e8..6ed5cfec078a96 100644 --- a/src/app/zap-templates/zcl/data-model/chip/onoff-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/onoff-cluster.xml @@ -81,37 +81,70 @@ limitations under the License. - - OnOff - GlobalSceneControl - OnTime - OffWaitTime - - StartUpOnOff + + + + + + + + + + + + + + + + + + + + + + + On receipt of this command, a device SHALL enter its ‘Off’ state. This state is device dependent, but it is recommended that it is used for power off or similar functions. On receipt of the Off command, the OnTime attribute SHALL be set to 0. + On receipt of this command, a device SHALL enter its ‘On’ state. This state is device dependent, but it is recommended that it is used for power on or similar functions. On receipt of the On command, if the value of the OnTime attribute is equal to 0, the device SHALL set the OffWaitTime attribute to 0. + + + + + On receipt of this command, if a device is in its ‘Off’ state it SHALL enter its ‘On’ state. Otherwise, if it is in its ‘On’ state it SHALL enter its ‘Off’ state. On receipt of the Toggle command, if the value of the OnOff attribute is equal to FALSE and if the value of the OnTime attribute is equal to 0, the device SHALL set the OffWaitTime attribute to 0. If the value of the OnOff attribute is equal to TRUE, the OnTime attribute SHALL be set to 0. + + + + + The OffWithEffect command allows devices to be turned off using enhanced ways of fading. + + + The OnWithRecallGlobalScene command allows the recall of the settings when the device was turned off. + + + @@ -119,6 +152,9 @@ limitations under the License. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/operational-credentials-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/operational-credentials-cluster.xml index 5b06c93e0ab7fd..61dd99e58b5d29 100644 --- a/src/app/zap-templates/zcl/data-model/chip/operational-credentials-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/operational-credentials-cluster.xml @@ -59,37 +59,51 @@ limitations under the License. OPERATIONAL_CREDENTIALS_CLUSTER This cluster is used to add or remove Operational Credentials on a Commissionee or Node, as well as manage the associated Fabrics. - - NOCs + + + + + + + + + + + + + + + + + - Fabrics - SupportedFabrics - CommissionedFabrics - TrustedRootCertificates - CurrentFabricIndex Sender is requesting attestation information from the receiver. + An attestation information confirmation from the server. + Sender is requesting a device attestation certificate from the receiver. + A device attestation certificate (DAC) or product attestation intermediate (PAI) certificate from the server. + @@ -97,6 +111,7 @@ limitations under the License. + @@ -104,6 +119,7 @@ limitations under the License. A certificate signing request (CSR) from the server. + @@ -114,6 +130,7 @@ limitations under the License. + @@ -121,31 +138,36 @@ limitations under the License. + - + Response to AddNOC or UpdateNOC commands. + This command SHALL be used by an Administrative Node to set the user-visible Label field for a given Fabric, as reflected by entries in the Fabrics attribute. + This command is used by Administrative Nodes to remove a given fabric index and delete all associated fabric-scoped data. + This command SHALL add a Trusted Root CA Certificate, provided as its CHIP Certificate representation. + diff --git a/src/app/zap-templates/zcl/data-model/chip/operational-state-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/operational-state-cluster.xml index 53b9c73cad6b3e..07b874e4626c5f 100644 --- a/src/app/zap-templates/zcl/data-model/chip/operational-state-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/operational-state-cluster.xml @@ -58,47 +58,88 @@ limitations under the License. true true This cluster supports remotely monitoring and, where supported, changing the operational state of any device where a state machine is a part of the operation. - - - - PhaseList - CurrentPhase - CountdownTime - OperationalStateList - OperationalState - OperationalError - + + + + + + + + + + + + + + + + + + + + + + Upon receipt, the device SHALL pause its operation if it is possible based on the current function of the server. + + + + + + Upon receipt, the device SHALL stop its operation if it is at a position where it is safe to do so and/or permitted. + + + + + + Upon receipt, the device SHALL start its operation if it is safe to do so and the device is in an operational state from which it can be started. + Upon receipt, the device SHALL resume its operation from the point it was at when it received the Pause command, or from the point when it was paused by means outside of this cluster (for example by manual button press). + + + + + + This command SHALL be generated in response to any of the Start, Stop, Pause, or Resume commands. + + + + + + + + OperationalError - + + OperationCompletion - + + diff --git a/src/app/zap-templates/zcl/data-model/chip/operational-state-oven-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/operational-state-oven-cluster.xml index fd52204b02fe85..0b18947c5dd666 100644 --- a/src/app/zap-templates/zcl/data-model/chip/operational-state-oven-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/operational-state-oven-cluster.xml @@ -53,13 +53,25 @@ limitations under the License. This cluster supports remotely monitoring and, where supported, changing the operational state of an Oven. - - PhaseList - CurrentPhase - CountdownTime - OperationalStateList - OperationalState - OperationalError + + + + + + + + + + + + + + + + + + + Upon receipt, the device SHALL pause its operation if it is possible based on the current function of the server. @@ -67,10 +79,17 @@ limitations under the License. Upon receipt, the device SHALL stop its operation if it is at a position where it is safe to do so and/or permitted. + + + + + + Upon receipt, the device SHALL start its operation if it is safe to do so and the device is in an operational state from which it can be started. + @@ -80,18 +99,28 @@ limitations under the License. This command SHALL be generated in response to any of the Start, Stop, Pause, or Resume commands. + + + + + + + + OperationalError - + + OperationCompletion - + + diff --git a/src/app/zap-templates/zcl/data-model/chip/operational-state-rvc-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/operational-state-rvc-cluster.xml index e3b054fe3fedce..bf09a56329f7a1 100644 --- a/src/app/zap-templates/zcl/data-model/chip/operational-state-rvc-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/operational-state-rvc-cluster.xml @@ -64,24 +64,42 @@ limitations under the License. true true This cluster supports remotely monitoring and, where supported, changing the operational state of a Robotic Vacuum. - - - - PhaseList - CurrentPhase - CountdownTime - OperationalStateList - - - OperationalState - OperationalError + + + + + + Upon receipt, the device SHALL pause its operation if it is possible based on the current function of the server. + + + + + + @@ -90,27 +108,47 @@ both values from this cluster and from the base cluster. Upon receipt, the device SHALL resume its operation from the point it was at when it received the Pause command, or from the point when it was paused by means outside of this cluster (for example by manual button press). + + + + + + This command SHALL be generated in response to any of the Start, Stop, Pause, or Resume commands. + + + + + + + + On receipt of this command, the device SHALL start seeking the charging dock, if possible in the current state of the device. + + + + OperationalError - + + - + OperationCompletion - - + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/oven-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/oven-mode-cluster.xml index 0faa1b037eb318..ff71dcc12cbfe3 100644 --- a/src/app/zap-templates/zcl/data-model/chip/oven-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/oven-mode-cluster.xml @@ -62,11 +62,15 @@ limitations under the License. - SupportedModes - CurrentMode + + + + + + StartUpMode OnMode - + @@ -74,6 +78,7 @@ limitations under the License. On receipt of this command the device SHALL respond with a ChangeToModeResponse command. + @@ -82,6 +87,7 @@ limitations under the License. + diff --git a/src/app/zap-templates/zcl/data-model/chip/power-source-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/power-source-cluster.xml index 5701dc6ec61e65..16b0c0c30787a0 100644 --- a/src/app/zap-templates/zcl/data-model/chip/power-source-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/power-source-cluster.xml @@ -43,58 +43,190 @@ limitations under the License. - - Status - Order - Description - - WiredAssessedInputVoltage - WiredAssessedInputFrequency - WiredCurrentType - WiredAssessedCurrent - WiredNominalVoltage - WiredMaximumCurrent - WiredPresent - ActiveWiredFaults - - BatVoltage - BatPercentRemaining - BatTimeRemaining - BatChargeLevel - BatReplacementNeeded - BatReplaceability - BatPresent - ActiveBatFaults - BatReplacementDescription - BatCommonDesignation - BatANSIDesignation - BatIECDesignation - BatApprovedChemistry - BatCapacity - BatQuantity - BatChargeState - BatTimeToFullCharge - BatFunctionalWhileCharging - BatChargingCurrent - ActiveBatChargeFaults - EndpointList + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The WiredFaultChange Event SHALL indicate a change in the set of wired faults currently detected by the Node on this wired power source. + + + The BatFaultChange Event SHALL indicate a change in the set of battery faults currently detected by the Node on this battery power source. + + + The BatChargeFaultChange Event SHALL indicate a change in the set of charge faults currently detected by the Node on this battery power source. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/power-source-configuration-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/power-source-configuration-cluster.xml index 04a7cdb121c775..ee99575b3b5cc6 100644 --- a/src/app/zap-templates/zcl/data-model/chip/power-source-configuration-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/power-source-configuration-cluster.xml @@ -26,6 +26,8 @@ limitations under the License. true true - Sources + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/power-topology-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/power-topology-cluster.xml index 3bca0bd43ee8af..9d5aa74931a6e4 100644 --- a/src/app/zap-templates/zcl/data-model/chip/power-topology-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/power-topology-cluster.xml @@ -44,7 +44,15 @@ limitations under the License. - AvailableEndpoints - ActiveEndpoints + + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/pressure-measurement-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/pressure-measurement-cluster.xml index f9487af7f3a9e2..61f9ccc1401a2b 100644 --- a/src/app/zap-templates/zcl/data-model/chip/pressure-measurement-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/pressure-measurement-cluster.xml @@ -31,16 +31,44 @@ limitations under the License. - - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - Tolerance - ScaledValue - MinScaledValue - MaxScaledValue - ScaledTolerance - Scale + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/pump-configuration-and-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/pump-configuration-and-control-cluster.xml index 74416092e7c7f8..0158c4077da4d3 100644 --- a/src/app/zap-templates/zcl/data-model/chip/pump-configuration-and-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/pump-configuration-and-control-cluster.xml @@ -49,97 +49,222 @@ limitations under the License. - - MaxPressure - MaxSpeed - MaxFlow - MinConstPressure - MaxConstPressure - MinCompPressure - MaxCompPressure - MinConstSpeed - MaxConstSpeed - MinConstFlow - MaxConstFlow - MinConstTemp - MaxConstTemp - PumpStatus - EffectiveOperationMode - EffectiveControlMode - Capacity - Speed - - LifetimeRunningHours + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - Power - - LifetimeEnergyConsumed + + - - OperationMode + + - - ControlMode + + SupplyVoltageLow + SupplyVoltageHigh + PowerMissingPhase + SystemPressureLow + SystemPressureHigh + DryRunning + MotorTemperatureHigh + PumpMotorFatalFailure + ElectronicTemperatureHigh + PumpBlocked + SensorFailure + ElectronicNonFatalFailure + ElectronicFatalFailure + GeneralFault + Leakage + AirDetection + TurbineOperation + diff --git a/src/app/zap-templates/zcl/data-model/chip/refrigerator-alarm.xml b/src/app/zap-templates/zcl/data-model/chip/refrigerator-alarm.xml index 58fa70163f65ea..ca091a5deab23e 100644 --- a/src/app/zap-templates/zcl/data-model/chip/refrigerator-alarm.xml +++ b/src/app/zap-templates/zcl/data-model/chip/refrigerator-alarm.xml @@ -28,17 +28,24 @@ limitations under the License. REFRIGERATOR_ALARM_CLUSTER true true - - Mask - State - Supported + + + + + + + + + + - Notify - - - - + Notify + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/refrigerator-and-temperature-controlled-cabinet-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/refrigerator-and-temperature-controlled-cabinet-mode-cluster.xml index e29080ce4a43cb..7ed1160ce7410c 100644 --- a/src/app/zap-templates/zcl/data-model/chip/refrigerator-and-temperature-controlled-cabinet-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/refrigerator-and-temperature-controlled-cabinet-mode-cluster.xml @@ -56,11 +56,15 @@ limitations under the License. - SupportedModes - CurrentMode + + + + + + StartUpMode OnMode - + @@ -68,6 +72,7 @@ limitations under the License. On receipt of this command the device SHALL respond with a ChangeToModeResponse command. + @@ -76,6 +81,7 @@ limitations under the License. + diff --git a/src/app/zap-templates/zcl/data-model/chip/relative-humidity-measurement-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/relative-humidity-measurement-cluster.xml index e309b75dcc46bd..047258fcbb87f6 100644 --- a/src/app/zap-templates/zcl/data-model/chip/relative-humidity-measurement-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/relative-humidity-measurement-cluster.xml @@ -25,9 +25,17 @@ limitations under the License. true true - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - Tolerance + + + + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/resource-monitoring-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/resource-monitoring-cluster.xml index 66de9ee66cbebd..d85bf3dfb5c7ba 100644 --- a/src/app/zap-templates/zcl/data-model/chip/resource-monitoring-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/resource-monitoring-cluster.xml @@ -38,16 +38,35 @@ limitations under the License. - Condition - DegradationDirection - ChangeIndication - InPlaceIndicator - LastChangedTime - ReplacementProductList - + + + + + + + + + + + + + + + + + + + + + + + + + Reset the condition of the replaceable to the non degraded state + @@ -73,16 +92,35 @@ limitations under the License. - Condition - DegradationDirection - ChangeIndication - InPlaceIndicator - LastChangedTime - ReplacementProductList - + + + + + + + + + + + + + + + + + + + + + + + + + Reset the condition of the replaceable to the non degraded state + diff --git a/src/app/zap-templates/zcl/data-model/chip/rvc-clean-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/rvc-clean-mode-cluster.xml index 65c2f17a3e8e75..f3ac53b22d3bdc 100644 --- a/src/app/zap-templates/zcl/data-model/chip/rvc-clean-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/rvc-clean-mode-cluster.xml @@ -67,8 +67,12 @@ limitations under the License. - SupportedModes - CurrentMode + + + + + + @@ -78,6 +82,7 @@ limitations under the License. On receipt of this command the device SHALL respond with a ChangeToModeResponse command. + @@ -86,6 +91,7 @@ limitations under the License. + diff --git a/src/app/zap-templates/zcl/data-model/chip/rvc-run-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/rvc-run-mode-cluster.xml index ce835576396bb8..2ca053546c2234 100644 --- a/src/app/zap-templates/zcl/data-model/chip/rvc-run-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/rvc-run-mode-cluster.xml @@ -73,8 +73,12 @@ limitations under the License. - SupportedModes - CurrentMode + + + + + + @@ -84,6 +88,7 @@ limitations under the License. On receipt of this command the device SHALL respond with a ChangeToModeResponse command. + @@ -92,6 +97,7 @@ limitations under the License. + diff --git a/src/app/zap-templates/zcl/data-model/chip/scene.xml b/src/app/zap-templates/zcl/data-model/chip/scene.xml index b6315bdc1287c1..ceea35e3759e69 100644 --- a/src/app/zap-templates/zcl/data-model/chip/scene.xml +++ b/src/app/zap-templates/zcl/data-model/chip/scene.xml @@ -80,10 +80,16 @@ limitations under the License. - - LastConfiguredBy - SceneTableSize - FabricSceneInfo + + + + + + + + + + Add a scene to the scene table. Extension field sets are supported, and are inputed as '{"ClusterID": VALUE, "AttributeValueList":[{"AttributeID": VALUE, "Value*": VALUE}]}' @@ -94,6 +100,7 @@ limitations under the License. + @@ -102,6 +109,7 @@ limitations under the License. + @@ -111,6 +119,7 @@ limitations under the License. + @@ -119,6 +128,7 @@ limitations under the License. + @@ -128,6 +138,7 @@ limitations under the License. + @@ -137,6 +148,7 @@ limitations under the License. + @@ -144,6 +156,7 @@ limitations under the License. Get an unused scene identifier when no commissioning tool is in the network, or for a commissioning tool to get the used scene identifiers within a certain group + @@ -155,6 +168,7 @@ limitations under the License. + @@ -164,6 +178,7 @@ limitations under the License. + @@ -176,6 +191,7 @@ limitations under the License. + @@ -185,6 +201,7 @@ limitations under the License. + @@ -193,6 +210,7 @@ limitations under the License. + @@ -202,6 +220,7 @@ limitations under the License. + @@ -212,6 +231,7 @@ limitations under the License. + @@ -221,6 +241,9 @@ limitations under the License. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/service-area-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/service-area-cluster.xml index 8c2ba832c85604..f74647a260e8c0 100644 --- a/src/app/zap-templates/zcl/data-model/chip/service-area-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/service-area-cluster.xml @@ -96,19 +96,37 @@ limitations under the License. - SupportedAreas - SupportedMaps - SelectedAreas - CurrentArea - EstimatedEndTime - Progress - + + + + + + + + + + + + + + + + + + + + + + + + Command used to select a set of device areas, where the device is to operate. + @@ -117,6 +135,7 @@ limitations under the License. + @@ -132,6 +151,9 @@ limitations under the License. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/smoke-co-alarm-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/smoke-co-alarm-cluster.xml index 31ae0bba9e7d99..e5a3afb75d39d6 100644 --- a/src/app/zap-templates/zcl/data-model/chip/smoke-co-alarm-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/smoke-co-alarm-cluster.xml @@ -46,66 +46,118 @@ limitations under the License. - ExpressedState - SmokeState - COState - BatteryAlert - DeviceMuted - TestInProgress - HardwareFaultAlert - EndOfServiceAlert - InterconnectSmokeAlarm - InterconnectCOAlarm - ContaminationState - - SmokeSensitivityLevel + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - ExpiryDate - + + + + This command SHALL initiate a device self-test. + This event SHALL be generated when SmokeState attribute changes to either Warning or Critical state. + + + This event SHALL be generated when COState attribute changes to either Warning or Critical state. + + + This event SHALL be generated when BatteryAlert attribute changes to either Warning or Critical state. + This event SHALL be generated when the device detects a hardware fault that leads to setting HardwareFaultAlert to True. + This event SHALL be generated when the EndOfServiceAlert is set to Expired. + This event SHALL be generated when the SelfTest completes, and the attribute TestInProgress changes to False. + This event SHALL be generated when the DeviceMuted attribute changes to Muted. + This event SHALL be generated when DeviceMuted attribute changes to NotMuted. + This event SHALL be generated when the device hosting the server receives a smoke alarm from an interconnected sensor. + + + This event SHALL be generated when the device hosting the server receives a smoke alarm from an interconnected sensor. + + + This event SHALL be generated when ExpressedState attribute returns to Normal state. + diff --git a/src/app/zap-templates/zcl/data-model/chip/software-diagnostics-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/software-diagnostics-cluster.xml index 3ac2ba42e8e22e..9d4026187f2420 100644 --- a/src/app/zap-templates/zcl/data-model/chip/software-diagnostics-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/software-diagnostics-cluster.xml @@ -37,20 +37,34 @@ limitations under the License. - ThreadMetrics - CurrentHeapFree - CurrentHeapUsed - CurrentHeapHighWatermark + + + + + + + + + + + + + + Reception of this command SHALL reset the values: The StackFreeMinimum field of the ThreadMetrics attribute, CurrentHeapHighWaterMark attribute. + + + Indicate the last software fault that has taken place on the Node. - + + diff --git a/src/app/zap-templates/zcl/data-model/chip/switch-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/switch-cluster.xml index 176163fae7fce6..1ab3f1d9509cb3 100644 --- a/src/app/zap-templates/zcl/data-model/chip/switch-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/switch-cluster.xml @@ -78,38 +78,72 @@ Interactions with the switch device are exposed as attributes (for the latching - NumberOfPositions - CurrentPosition - MultiPressMax + + + + + + + + + + + SwitchLatched + + + InitialPress + + + LongPress + + + ShortRelease + + + LongRelease + + + MultiPressOngoing + + + + + + + + MultiPressComplete - + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/target-navigator-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/target-navigator-cluster.xml index bc665905df1eb2..86edb7478da629 100644 --- a/src/app/zap-templates/zcl/data-model/chip/target-navigator-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/target-navigator-cluster.xml @@ -25,19 +25,25 @@ limitations under the License. true This cluster provides an interface for UX navigation within a set of targets on a device or endpoint. - TargetList - CurrentTarget - + + + + + + + Upon receipt, this SHALL navigation the UX to the target identified. + This command SHALL be generated in response to NavigateTarget commands. + @@ -45,6 +51,7 @@ limitations under the License. + diff --git a/src/app/zap-templates/zcl/data-model/chip/temperature-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/temperature-control-cluster.xml index da0c0bcee983bb..b3f7b6a86b03a0 100644 --- a/src/app/zap-templates/zcl/data-model/chip/temperature-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/temperature-control-cluster.xml @@ -40,17 +40,42 @@ limitations under the License. - TemperatureSetpoint - MinTemperature - MaxTemperature - Step - SelectedTemperatureLevel - SupportedTemperatureLevels + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - Set Temperature - - + Set Temperature + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/temperature-measurement-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/temperature-measurement-cluster.xml index d141743fafde56..8b5a4ac7302510 100644 --- a/src/app/zap-templates/zcl/data-model/chip/temperature-measurement-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/temperature-measurement-cluster.xml @@ -24,9 +24,17 @@ limitations under the License. TEMPERATURE_MEASUREMENT_CLUSTER true true - MeasuredValue - MinMeasuredValue - MaxMeasuredValue - Tolerance + + + + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/thermostat-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/thermostat-cluster.xml index 6f75aa45e985f6..d52c730d05ddc9 100644 --- a/src/app/zap-templates/zcl/data-model/chip/thermostat-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/thermostat-cluster.xml @@ -312,146 +312,308 @@ limitations under the License. - LocalTemperature - OutdoorTemperature - Occupancy - AbsMinHeatSetpointLimit - AbsMaxHeatSetpointLimit - AbsMinCoolSetpointLimit - AbsMaxCoolSetpointLimit - PICoolingDemand - PIHeatingDemand - - HVACSystemTypeConfiguration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - LocalTemperatureCalibration + + + + + + - OccupiedCoolingSetpoint - OccupiedHeatingSetpoint - UnoccupiedCoolingSetpoint - UnoccupiedHeatingSetpoint - - MinHeatSetpointLimit + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - MaxHeatSetpointLimit + + + + - - MinCoolSetpointLimit + + + + - - MaxCoolSetpointLimit + + + + - - MinSetpointDeadBand + + + + - - RemoteSensing + + - - ControlSequenceOfOperation + + - - SystemMode + + + + + + + - ThermostatRunningMode - StartOfWeek - NumberOfWeeklyTransitions - NumberOfDailyTransitions - - TemperatureSetpointHold + + + + + + + + + + + + + + + + + - - TemperatureSetpointHoldDuration + + - - ThermostatProgrammingOperationMode + + + + + - ThermostatRunningState - SetpointChangeSource - SetpointChangeAmount - SetpointChangeSourceTimestamp - - OccupiedSetback + + + + + + + + + + + + + + + + + + + + + + + - OccupiedSetbackMin - OccupiedSetbackMax - - UnoccupiedSetback + + + + + + + - UnoccupiedSetbackMin - UnoccupiedSetbackMax - - EmergencyHeatDelta + + + + + + + + + + + + + + + + + + - - ACType + + - - ACCapacity + + - - ACRefrigerantType + + - - ACCompressorType + + - - ACErrorCode + + - - ACLouverPosition + + - ACCoilTemperature - - ACCapacityformat + + + + + + + + + + - PresetTypes - ScheduleTypes - NumberOfPresets - NumberOfSchedules - NumberOfScheduleTransitions - NumberOfScheduleTransitionPerDay - ActivePresetHandle - ActiveScheduleHandle - - Presets + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - Schedules + + + + + + + - SetpointHoldExpiryTimestamp Upon receipt, the attributes for the indicated setpoint(s) SHALL have the amount specified in the Amount field added to them. + @@ -461,27 +623,42 @@ limitations under the License. + + + The Current Weekly Schedule Command is sent from the server in response to the Get Weekly Schedule Command. + + + This command is used to clear the weekly schedule. + + + Upon receipt, if the Schedules attribute contains a ScheduleStruct whose ScheduleHandle field matches the value of the ScheduleHandle field, the server SHALL set the thermostat's ActiveScheduleHandle attribute to the value of the ScheduleHandle field. + + + ID + + + @@ -491,6 +668,9 @@ limitations under the License. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/thermostat-user-interface-configuration-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/thermostat-user-interface-configuration-cluster.xml index cd3491cc079024..ed0b412570f3dd 100644 --- a/src/app/zap-templates/zcl/data-model/chip/thermostat-user-interface-configuration-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/thermostat-user-interface-configuration-cluster.xml @@ -29,18 +29,20 @@ limitations under the License. - TemperatureDisplayMode - - - KeypadLockout + + + + + + - - ScheduleProgrammingVisibility + + diff --git a/src/app/zap-templates/zcl/data-model/chip/thread-border-router-management-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/thread-border-router-management-cluster.xml index d05ce70c34aca3..38612b5eb6d117 100644 --- a/src/app/zap-templates/zcl/data-model/chip/thread-border-router-management-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/thread-border-router-management-cluster.xml @@ -33,31 +33,46 @@ limitations under the License. - BorderRouterName - - BorderAgentID - - ThreadVersion - - InterfaceEnabled - - ActiveDatasetTimestamp - - PendingDatasetTimestamp - + + + + + + + + + + + + + + + + + + + + + + + + Command to request the active operational dataset of the Thread network to which the border router is connected. This command must be sent over a valid CASE session + Command to request the pending dataset of the Thread network to which the border router is connected. This command must be sent over a valid CASE session + - + Generated response to GetActiveDatasetRequest or GetPendingDatasetRequest commands. + @@ -65,12 +80,16 @@ limitations under the License. + Command set or update the pending Dataset of the Thread network to which the Border Router is connected. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/thread-network-diagnostics-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/thread-network-diagnostics-cluster.xml index 77ec8699615156..943f69f58f9378 100644 --- a/src/app/zap-templates/zcl/data-model/chip/thread-network-diagnostics-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/thread-network-diagnostics-cluster.xml @@ -107,82 +107,299 @@ limitations under the License. - - Channel - RoutingRole - NetworkName - PanId - ExtendedPanId - MeshLocalPrefix - OverrunCount - NeighborTable - RouteTable - PartitionId - Weighting - DataVersion - StableDataVersion - LeaderRouterId - DetachedRoleCount - ChildRoleCount - RouterRoleCount - LeaderRoleCount - AttachAttemptCount - PartitionIdChangeCount - BetterPartitionAttachAttemptCount - ParentChangeCount - TxTotalCount - TxUnicastCount - TxBroadcastCount - TxAckRequestedCount - TxAckedCount - TxNoAckRequestedCount - TxDataCount - TxDataPollCount - TxBeaconCount - TxBeaconRequestCount - TxOtherCount - TxRetryCount - TxDirectMaxRetryExpiryCount - TxIndirectMaxRetryExpiryCount - TxErrCcaCount - TxErrAbortCount - TxErrBusyChannelCount - RxTotalCount - RxUnicastCount - RxBroadcastCount - RxDataCount - RxDataPollCount - RxBeaconCount - RxBeaconRequestCount - RxOtherCount - RxAddressFilteredCount - RxDestAddrFilteredCount - RxDuplicatedCount - RxErrNoFrameCount - RxErrUnknownNeighborCount - RxErrInvalidSrcAddrCount - RxErrSecCount - RxErrFcsCount - RxErrOtherCount - ActiveTimestamp - PendingTimestamp - Delay - SecurityPolicy - ChannelPage0Mask - OperationalDatasetComponents - ActiveNetworkFaultsList + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Reception of this command SHALL reset the OverrunCount attributes to 0 + + + Indicate that a Node’s connection status to a Thread network has changed + Indicate a change in the set of network faults currently detected by the Node + diff --git a/src/app/zap-templates/zcl/data-model/chip/thread-network-directory-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/thread-network-directory-cluster.xml index 3a6445b15bbad3..2b00af31024a29 100644 --- a/src/app/zap-templates/zcl/data-model/chip/thread-network-directory-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/thread-network-directory-cluster.xml @@ -15,58 +15,64 @@ See the License for the specific language governing permissions and limitations under the License. --> - + + + + + + + + + - - - - - - - + + Network Infrastructure + Thread Network Directory + 0x0453 + THREAD_NETWORK_DIRECTORY_CLUSTER + Manages the names and credentials of Thread networks visible to the user. - - Network Infrastructure - Thread Network Directory - 0x0453 - THREAD_NETWORK_DIRECTORY_CLUSTER - Manages the names and credentials of Thread networks visible to the user. + true + true - true - true + + + + + + + + + + + + + + + - - - - - PreferredExtendedPanID - - - - - ThreadNetworks - - - ThreadNetworkTableSize - - - Adds an entry to the ThreadNetworks list. - - - - - Removes an entry from the ThreadNetworks list. - - - - - Retrieves a Thread Operational Dataset from the ThreadNetworks list. - - - - - This is the response to a GetOperationalDataset request. - - - + + Adds an entry to the ThreadNetworks list. + + + + + + Removes an entry from the ThreadNetworks list. + + + + + + Retrieves a Thread Operational Dataset from the ThreadNetworks list. + + + + + + This is the response to a GetOperationalDataset request. + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/time-format-localization-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/time-format-localization-cluster.xml index 6ade7abe2e446c..b71b710b707471 100644 --- a/src/app/zap-templates/zcl/data-model/chip/time-format-localization-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/time-format-localization-cluster.xml @@ -58,14 +58,20 @@ limitations under the License. - - HourFormat - + + + - - ActiveCalendarType - + + + + + + + + + + - SupportedCalendarTypes diff --git a/src/app/zap-templates/zcl/data-model/chip/time-synchronization-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/time-synchronization-cluster.xml index 9336a6a944735e..a352b2a181b8e8 100644 --- a/src/app/zap-templates/zcl/data-model/chip/time-synchronization-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/time-synchronization-cluster.xml @@ -114,78 +114,153 @@ limitations under the License. - UTCTime - Granularity - TimeSource - TrustedTimeSource - DefaultNTP - TimeZone - DSTOffset - LocalTime - TimeZoneDatabase - NTPServerAvailable - TimeZoneListMaxSize - DSTOffsetListMaxSize - SupportsDNSResolve - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This command MAY be issued by Administrator to set the time. + This command SHALL set TrustedTimeSource. + + + This command SHALL set TimeZone. + + + Response to SetTimeZone. + + + This command SHALL set DSTOffset. + + + This command is used to set DefaultNTP. + + + This event SHALL be generated when the server stops applying the current DSTOffset and there are no entries in the list with a larger ValidStarting time. + + + This event SHALL be generated when the server starts or stops applying a DST offset. - + + + + This event SHALL be generated when the server changes its time zone offset or name. + + + This event SHALL be generated if the node has attempted to update its time, but was unable to find a good time from any source. + This event SHALL be generated if the node attempts to update its time and finds that the TrustedTimeSource is null, or the specified peer cannot be reached. + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/unit-localization-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/unit-localization-cluster.xml index fb6238add46a4f..d79a265f633a39 100644 --- a/src/app/zap-templates/zcl/data-model/chip/unit-localization-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/unit-localization-cluster.xml @@ -42,9 +42,11 @@ limitations under the License. - - TemperatureUnit - + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/user-label-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/user-label-cluster.xml index 24260b78307bd3..acea3035a4029f 100644 --- a/src/app/zap-templates/zcl/data-model/chip/user-label-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/user-label-cluster.xml @@ -23,10 +23,10 @@ limitations under the License. 0x0041 USER_LABEL_CLUSTER The User Label Cluster provides a feature to tag an endpoint with zero or more labels. - - LabelList + + diff --git a/src/app/zap-templates/zcl/data-model/chip/valve-configuration-and-control-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/valve-configuration-and-control-cluster.xml index 80c1cdb60c8ccc..6656876c991c92 100644 --- a/src/app/zap-templates/zcl/data-model/chip/valve-configuration-and-control-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/valve-configuration-and-control-cluster.xml @@ -59,39 +59,75 @@ limitations under the License. - OpenDuration + + + - DefaultOpenDuration - AutoCloseTime - RemainingDuration - CurrentState - TargetState - CurrentLevel - TargetLevel - DefaultOpenLevel - ValveFault - LevelStep - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This command is used to set the valve to its open position. + This command is used to set the valve to its closed position. + This event SHALL be generated when the valve state changed. + This event SHALL be generated when the valve registers or clears a fault. + diff --git a/src/app/zap-templates/zcl/data-model/chip/wake-on-lan-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/wake-on-lan-cluster.xml index 90bd18b5b7baaa..700f25b1986b3a 100644 --- a/src/app/zap-templates/zcl/data-model/chip/wake-on-lan-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/wake-on-lan-cluster.xml @@ -27,8 +27,12 @@ limitations under the License. - - MACAddress - LinkLocalAddress + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/washer-controls-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/washer-controls-cluster.xml index 2dc01920ae3e37..d566acb28cf306 100644 --- a/src/app/zap-templates/zcl/data-model/chip/washer-controls-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/washer-controls-cluster.xml @@ -45,11 +45,27 @@ limitations under the License. - - SpinSpeeds - SpinSpeedCurrent - NumberOfRinses - SupportedRinses + + + + + + + + + + + + + + + + + + + + + diff --git a/src/app/zap-templates/zcl/data-model/chip/water-heater-management-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/water-heater-management-cluster.xml index beeaf277b77d2e..60fc9ce3e0f009 100644 --- a/src/app/zap-templates/zcl/data-model/chip/water-heater-management-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/water-heater-management-cluster.xml @@ -64,30 +64,52 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 true - HeaterTypes - HeatDemand - TankVolume - EstimatedHeatRequired - TankPercentage - BoostState + + + + + + + + + + + + + + + + + + + + + + + + Allows a client to request that the water heater is put into a Boost state. + Allows a client to cancel an ongoing Boost operation. + This event SHALL be generated whenever a Boost command is accepted. + This event SHALL be generated whenever the BoostState transitions from Active to Inactive. + diff --git a/src/app/zap-templates/zcl/data-model/chip/water-heater-mode-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/water-heater-mode-cluster.xml index d9211e808467fb..a1d3b27255f98c 100644 --- a/src/app/zap-templates/zcl/data-model/chip/water-heater-mode-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/water-heater-mode-cluster.xml @@ -58,18 +58,24 @@ Git: 1.4-prerelease-ipr-69-ge15ff5700 - SupportedModes - CurrentMode + + + + + + This command is used to change device modes. + This command is sent by the device on receipt of the ChangeToMode command. + diff --git a/src/app/zap-templates/zcl/data-model/chip/wifi-network-diagnostics-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/wifi-network-diagnostics-cluster.xml index 7fb35aab255ed7..784568337b9773 100644 --- a/src/app/zap-templates/zcl/data-model/chip/wifi-network-diagnostics-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/wifi-network-diagnostics-cluster.xml @@ -63,35 +63,81 @@ limitations under the License. - - BSSID - SecurityType - WiFiVersion - ChannelNumber - RSSI - BeaconLostCount - BeaconRxCount - PacketMulticastRxCount - PacketMulticastTxCount - PacketUnicastRxCount - PacketUnicastTxCount - CurrentMaxRate - OverrunCount + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Reception of this command SHALL reset the Breacon and Packet related count attributes to 0 + + + Indicate that a Node’s Wi-Fi connection has been disconnected as a result of de-authenticated or dis-association and indicates the reason. + Indicate that a Node has failed to connect, or reconnect, to a Wi-Fi access point. + Indicate that a Node’s connection status to a Wi-Fi network has changed. + diff --git a/src/app/zap-templates/zcl/data-model/chip/wifi-network-management-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/wifi-network-management-cluster.xml index 8c8b4d40c3abdd..1c14050fc24451 100644 --- a/src/app/zap-templates/zcl/data-model/chip/wifi-network-management-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/wifi-network-management-cluster.xml @@ -30,19 +30,23 @@ limitations under the License. - SSID - - PassphraseSurrogate + + + + + Request the current WPA-Personal passphrase or PSK associated with the managed Wi-Fi network. + This is the response to a NetworkPassphraseRequest. + diff --git a/src/app/zap-templates/zcl/data-model/chip/window-covering.xml b/src/app/zap-templates/zcl/data-model/chip/window-covering.xml index 0e1c97a4d45040..5795e8efc34a88 100644 --- a/src/app/zap-templates/zcl/data-model/chip/window-covering.xml +++ b/src/app/zap-templates/zcl/data-model/chip/window-covering.xml @@ -57,91 +57,251 @@ limitations under the License. - Type + + + - PhysicalClosedLimitLift + + + + + + + + + - PhysicalClosedLimitTilt + + + + + + + + + - CurrentPositionLift + + + + + + + + + - CurrentPositionTilt + + + + + + + + + - NumberOfActuationsLift + + + + + - NumberOfActuationsTilt + + + + + - ConfigStatus + + + - CurrentPositionLiftPercentage + + + + + + + + - CurrentPositionTiltPercentage + + + + + + + + - OperationalStatus + + + - TargetPositionLiftPercent100ths + + + + + + + + - TargetPositionTiltPercent100ths + + + + + + + + - EndProductType + + + - CurrentPositionLiftPercent100ths + + + + + + + + - CurrentPositionTiltPercent100ths - + + + + + + + + - InstalledOpenLimitLift - InstalledClosedLimitLift + + + + + + + + + + + + + + + + + + - InstalledOpenLimitTilt - InstalledClosedLimitTilt + + + + + + + + + + + + + + + + + + - - Mode + - + + - SafetyStatus - + + + + Moves window covering to InstalledOpenLimitLift and InstalledOpenLimitTilt + Moves window covering to InstalledClosedLimitLift and InstalledCloseLimitTilt + Stop any adjusting of window covering + Go to lift value specified + + + + + + Go to lift percentage specified + + + + + + + + + + + Go to tilt value specified + + + + + + Go to tilt percentage specified + + + + + + + + + + + From eb5da6eca182b79cc65514b4e7e95e7067c9c1b3 Mon Sep 17 00:00:00 2001 From: yunhanw-google Date: Tue, 29 Oct 2024 21:13:56 -0700 Subject: [PATCH 008/121] [Java][Controller] Add custom cert support for java controller (#33342) * add custom cert support for java controller * Restyled by clang-format * Restyled by gn --------- Co-authored-by: Restyled.io --- src/controller/java/AndroidDeviceControllerWrapper.cpp | 8 +------- src/controller/java/AndroidDeviceControllerWrapper.h | 7 ++----- src/controller/java/BUILD.gn | 2 ++ .../android => controller/java}/CHIPP256KeypairBridge.cpp | 3 +-- .../android => controller/java}/CHIPP256KeypairBridge.h | 0 src/platform/android/BUILD.gn | 2 -- 6 files changed, 6 insertions(+), 16 deletions(-) rename src/{platform/android => controller/java}/CHIPP256KeypairBridge.cpp (98%) rename src/{platform/android => controller/java}/CHIPP256KeypairBridge.h (100%) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index ba0342629a73df..7f821fefc0c9ac 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -42,9 +42,7 @@ #include #include #include -#ifndef JAVA_MATTER_CONTROLLER_TEST -#include -#endif // JAVA_MATTER_CONTROLLER_TEST + using namespace chip; using namespace chip::Controller; using namespace chip::Credentials; @@ -54,13 +52,11 @@ AndroidDeviceControllerWrapper::~AndroidDeviceControllerWrapper() { mController->Shutdown(); -#ifndef JAVA_MATTER_CONTROLLER_TEST if (mKeypairBridge != nullptr) { chip::Platform::Delete(mKeypairBridge); mKeypairBridge = nullptr; } -#endif // JAVA_MATTER_CONTROLLER_TEST if (mDeviceAttestationDelegateBridge != nullptr) { @@ -298,7 +294,6 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( // The lifetime of the ephemeralKey variable must be kept until SetupParams is saved. Crypto::P256Keypair ephemeralKey; -#ifndef JAVA_MATTER_CONTROLLER_TEST if (rootCertificate != nullptr && nodeOperationalCertificate != nullptr && keypairDelegate != nullptr) { CHIPP256KeypairBridge * nativeKeypairBridge = wrapper->GetP256KeypairBridge(); @@ -335,7 +330,6 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( setupParams.controllerNOC = chip::ByteSpan(wrapper->mNocCertificate.data(), wrapper->mNocCertificate.size()); } else -#endif // JAVA_MATTER_CONTROLLER_TEST { ChipLogProgress(Controller, "No existing credentials provided: generating ephemeral local NOC chain with OperationalCredentialsIssuer"); diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 02d50499bbbcda..93374a1e0f1795 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -28,19 +28,18 @@ #include #include #include +#include #include #include #include #include #include #include - #ifdef JAVA_MATTER_CONTROLLER_TEST #include #include #else #include -#include #endif // JAVA_MATTER_CONTROLLER_TEST #include "AndroidCheckInDelegate.h" @@ -71,7 +70,6 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel jobject JavaObjectRef() { return mJavaObjectRef.ObjectRef(); } jlong ToJNIHandle(); -#ifndef JAVA_MATTER_CONTROLLER_TEST /** * Returns a CHIPP256KeypairBridge which can be used to delegate signing operations * to a KeypairDelegate in the Java layer. Note that this will always return a pointer @@ -85,7 +83,6 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel } return mKeypairBridge; } -#endif // JAVA_MATTER_CONTROLLER_TEST void CallJavaIntMethod(const char * methodName, jint argument); void CallJavaLongMethod(const char * methodName, jlong argument); @@ -235,12 +232,12 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel JavaVM * mJavaVM = nullptr; chip::JniGlobalReference mJavaObjectRef; + CHIPP256KeypairBridge * mKeypairBridge = nullptr; #ifdef JAVA_MATTER_CONTROLLER_TEST ExampleOperationalCredentialsIssuerPtr mOpCredsIssuer; PersistentStorage mExampleStorage; #else AndroidOperationalCredentialsIssuerPtr mOpCredsIssuer; - CHIPP256KeypairBridge * mKeypairBridge = nullptr; #endif // JAVA_MATTER_CONTROLLER_TEST // These fields allow us to release the string/byte array memory later. diff --git a/src/controller/java/BUILD.gn b/src/controller/java/BUILD.gn index 480e30f704ab29..2ae828ad09c47e 100644 --- a/src/controller/java/BUILD.gn +++ b/src/controller/java/BUILD.gn @@ -136,6 +136,8 @@ shared_library("jni") { "AttestationTrustStoreBridge.cpp", "AttestationTrustStoreBridge.h", "CHIPDeviceController-JNI.cpp", + "CHIPP256KeypairBridge.cpp", + "CHIPP256KeypairBridge.h", "DeviceAttestation-JNI.cpp", "DeviceAttestationDelegateBridge.cpp", "DeviceAttestationDelegateBridge.h", diff --git a/src/platform/android/CHIPP256KeypairBridge.cpp b/src/controller/java/CHIPP256KeypairBridge.cpp similarity index 98% rename from src/platform/android/CHIPP256KeypairBridge.cpp rename to src/controller/java/CHIPP256KeypairBridge.cpp index a6be8799ab7b96..a73eb417203c10 100644 --- a/src/platform/android/CHIPP256KeypairBridge.cpp +++ b/src/controller/java/CHIPP256KeypairBridge.cpp @@ -15,7 +15,7 @@ * limitations under the License. */ -#include "platform/android/CHIPP256KeypairBridge.h" +#include "CHIPP256KeypairBridge.h" #include "lib/core/CHIPError.h" #include "lib/support/CHIPJNIError.h" #include "lib/support/JniReferences.h" @@ -26,7 +26,6 @@ #include #include #include -#include #include #include diff --git a/src/platform/android/CHIPP256KeypairBridge.h b/src/controller/java/CHIPP256KeypairBridge.h similarity index 100% rename from src/platform/android/CHIPP256KeypairBridge.h rename to src/controller/java/CHIPP256KeypairBridge.h diff --git a/src/platform/android/BUILD.gn b/src/platform/android/BUILD.gn index 640b52490078eb..9893907f8588ba 100644 --- a/src/platform/android/BUILD.gn +++ b/src/platform/android/BUILD.gn @@ -64,8 +64,6 @@ static_library("android") { "BleConnectCallback-JNI.cpp", "BlePlatformConfig.h", "CHIPDevicePlatformEvent.h", - "CHIPP256KeypairBridge.cpp", - "CHIPP256KeypairBridge.h", "CommissionableDataProviderImpl.cpp", "CommissionableDataProviderImpl.h", "ConfigurationManagerImpl.cpp", From f99a2c3b16d3d26f91a0c5efb2770d1c488697d1 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Wed, 30 Oct 2024 05:14:25 +0100 Subject: [PATCH 009/121] Install chip-testing package in the final docker image (#36285) * Install cmakeeee from APT * Install PIP from APT * Properly install chip-testing package * Install GI repository dev package --- .../docker/images/chip-cert-bins/Dockerfile | 51 +++++-------------- 1 file changed, 12 insertions(+), 39 deletions(-) diff --git a/integrations/docker/images/chip-cert-bins/Dockerfile b/integrations/docker/images/chip-cert-bins/Dockerfile index 37552c983f8eba..59c127dc1f8191 100644 --- a/integrations/docker/images/chip-cert-bins/Dockerfile +++ b/integrations/docker/images/chip-cert-bins/Dockerfile @@ -40,11 +40,13 @@ RUN set -x \ clang \ clang-format \ clang-tidy \ + cmake \ curl \ flex \ - gcc \ g++ \ + gcc \ git \ + git-lfs \ gperf \ iproute2 \ jq \ @@ -54,11 +56,12 @@ RUN set -x \ libcairo2-dev \ libdbus-1-dev \ libdbus-glib-1-dev \ + libdmalloc-dev \ libgif-dev \ + libgirepository1.0-dev \ libglib2.0-dev \ libical-dev \ libjpeg-dev \ - libdmalloc-dev \ libmbedtls-dev \ libncurses5-dev \ libncursesw5-dev \ @@ -79,55 +82,23 @@ RUN set -x \ pkg-config \ python3 \ python3-dev \ + python3-pip \ python3-venv \ rsync \ shellcheck \ + software-properties-common \ strace \ systemd \ udev \ unzip \ wget \ - git-lfs \ zlib1g-dev \ && git lfs install \ && : # last line -# Cmake (Mbed OS requires >=3.19.0-rc3 version which is not available in Ubuntu 20.04 repository) -RUN case ${TARGETPLATFORM} in \ - "linux/amd64") \ - set -x \ - && (cd /tmp \ - && wget --progress=dot:giga https://github.com/Kitware/CMake/releases/download/v3.19.3/cmake-3.19.3-Linux-x86_64.sh \ - && sh cmake-3.19.3-Linux-x86_64.sh --exclude-subdir --prefix=/usr/local \ - && rm -rf cmake-3.19.3-Linux-x86_64.sh) \ - && exec bash \ - ;; \ - "linux/arm64") \ - set -x \ - && (cd /tmp \ - && wget --progress=dot:giga https://github.com/Kitware/CMake/releases/download/v3.19.3/cmake-3.19.3-Linux-aarch64.sh \ - && sh cmake-3.19.3-Linux-aarch64.sh --exclude-subdir --prefix=/usr/local \ - && rm -rf cmake-3.19.3-Linux-aarch64.sh) \ - && exec bash \ - ;; \ - *) \ - test -n "$TARGETPLATFORM" \ - echo "Unsupported platform ${TARGETPLATFORM}" \ - ;; \ - esac - -# Python 3 and PIP -RUN set -x \ - && DEBIAN_FRONTEND=noninteractive apt-get install -y \ - libgirepository1.0-dev \ - software-properties-common \ - && add-apt-repository universe \ - && curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py \ - && python3 get-pip.py --break-system-packages \ - && : # last line - RUN set -x \ - && pip3 install attrs coloredlogs PyGithub pygit future portpicker mobly click cxxfilt ghapi pandas tabulate --break-system-packages \ + && pip3 install --break-system-packages \ + attrs coloredlogs PyGithub pygit future portpicker mobly click cxxfilt ghapi pandas tabulate \ && : # last line # build and install gn @@ -327,4 +298,6 @@ RUN pip install --break-system-packages -r /tmp/requirements.txt && rm /tmp/requ # PIP requires MASON package compilation, which seems to require a JDK RUN set -x && DEBIAN_FRONTEND=noninteractive apt-get update; apt-get install -fy openjdk-8-jdk -RUN pip install --break-system-packages --no-cache-dir python_lib/controller/python/chip*.whl +RUN pip install --break-system-packages --no-cache-dir \ + python_lib/python/obj/src/python_testing/matter_testing_infrastructure/chip-testing._build_wheel/chip_testing-*.whl \ + python_lib/controller/python/chip*.whl From 83e2db56b6ff444126914f82cea09b9447465221 Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Wed, 30 Oct 2024 09:17:23 -0400 Subject: [PATCH 010/121] Split UniqueId and PersistentUniqueId (#36292) --- .../provision/ProvisionStorageDefault.cpp | 8 +-- .../provision/ProvisionStorageFlash.cpp | 8 +-- src/platform/silabs/SilabsConfig.h | 72 ++++++++++--------- .../silabs/provision/ProvisionStorage.h | 32 +++++---- third_party/silabs/matter_support | 2 +- 5 files changed, 64 insertions(+), 58 deletions(-) diff --git a/examples/platform/silabs/provision/ProvisionStorageDefault.cpp b/examples/platform/silabs/provision/ProvisionStorageDefault.cpp index 5180e031f07238..bc0bfbd8f06918 100644 --- a/examples/platform/silabs/provision/ProvisionStorageDefault.cpp +++ b/examples/platform/silabs/provision/ProvisionStorageDefault.cpp @@ -403,14 +403,14 @@ CHIP_ERROR Storage::GetManufacturingDate(uint8_t * value, size_t max, size_t & s return SilabsConfig::ReadConfigValueStr(SilabsConfig::kConfigKey_ManufacturingDate, (char *) value, max, size); } -CHIP_ERROR Storage::SetUniqueId(const uint8_t * value, size_t size) +CHIP_ERROR Storage::SetPersistentUniqueId(const uint8_t * value, size_t size) { - return SilabsConfig::WriteConfigValueBin(SilabsConfig::kConfigKey_UniqueId, value, size); + return SilabsConfig::WriteConfigValueBin(SilabsConfig::kConfigKey_PersistentUniqueId, value, size); } -CHIP_ERROR Storage::GetUniqueId(uint8_t * value, size_t max, size_t & size) +CHIP_ERROR Storage::GetPersistentUniqueId(uint8_t * value, size_t max, size_t & size) { - return SilabsConfig::ReadConfigValueBin(SilabsConfig::kConfigKey_UniqueId, value, max, size); + return SilabsConfig::ReadConfigValueBin(SilabsConfig::kConfigKey_PersistentUniqueId, value, max, size); } // diff --git a/examples/platform/silabs/provision/ProvisionStorageFlash.cpp b/examples/platform/silabs/provision/ProvisionStorageFlash.cpp index abca012e361b13..fae1b5c713b910 100644 --- a/examples/platform/silabs/provision/ProvisionStorageFlash.cpp +++ b/examples/platform/silabs/provision/ProvisionStorageFlash.cpp @@ -470,14 +470,14 @@ CHIP_ERROR Storage::GetManufacturingDate(uint8_t * value, size_t max, size_t & s return Flash::Get(Parameters::ID::kManufacturingDate, value, max, size); } -CHIP_ERROR Storage::SetUniqueId(const uint8_t * value, size_t size) +CHIP_ERROR Storage::SetPersistentUniqueId(const uint8_t * value, size_t size) { - return Flash::Set(Parameters::ID::kUniqueId, value, size); + return Flash::Set(Parameters::ID::kPersistentUniqueId, value, size); } -CHIP_ERROR Storage::GetUniqueId(uint8_t * value, size_t max, size_t & size) +CHIP_ERROR Storage::GetPersistentUniqueId(uint8_t * value, size_t max, size_t & size) { - return Flash::Get(Parameters::ID::kUniqueId, value, max, size); + return Flash::Get(Parameters::ID::kPersistentUniqueId, value, max, size); } // diff --git a/src/platform/silabs/SilabsConfig.h b/src/platform/silabs/SilabsConfig.h index cef9ca323f74d2..c30d4d653dd6c8 100644 --- a/src/platform/silabs/SilabsConfig.h +++ b/src/platform/silabs/SilabsConfig.h @@ -120,42 +120,46 @@ class SilabsConfig static constexpr Key kConfigKey_hostname = SilabsConfigKey(kMatterFactory_KeyBase, 0x15); static constexpr Key kConfigKey_clientid = SilabsConfigKey(kMatterFactory_KeyBase, 0x16); static constexpr Key kConfigKey_Test_Event_Trigger_Key = SilabsConfigKey(kMatterFactory_KeyBase, 0x17); - static constexpr Key kConfigKey_UniqueId = SilabsConfigKey(kMatterFactory_KeyBase, 0x1F); - static constexpr Key kConfigKey_Creds_KeyId = SilabsConfigKey(kMatterFactory_KeyBase, 0x20); - static constexpr Key kConfigKey_Creds_Base_Addr = SilabsConfigKey(kMatterFactory_KeyBase, 0x21); - static constexpr Key kConfigKey_Creds_DAC_Offset = SilabsConfigKey(kMatterFactory_KeyBase, 0x22); - static constexpr Key kConfigKey_Creds_DAC_Size = SilabsConfigKey(kMatterFactory_KeyBase, 0x23); - static constexpr Key kConfigKey_Creds_PAI_Offset = SilabsConfigKey(kMatterFactory_KeyBase, 0x24); - static constexpr Key kConfigKey_Creds_PAI_Size = SilabsConfigKey(kMatterFactory_KeyBase, 0x25); - static constexpr Key kConfigKey_Creds_CD_Offset = SilabsConfigKey(kMatterFactory_KeyBase, 0x26); - static constexpr Key kConfigKey_Creds_CD_Size = SilabsConfigKey(kMatterFactory_KeyBase, 0x27); - static constexpr Key kConfigKey_Provision_Request = SilabsConfigKey(kMatterFactory_KeyBase, 0x28); - static constexpr Key kConfigKey_Provision_Version = SilabsConfigKey(kMatterFactory_KeyBase, 0x29); - - static constexpr Key kOtaTlvEncryption_KeyId = SilabsConfigKey(kMatterFactory_KeyBase, 0x30); + // kConfigKey_PersistentUniqueId is the inputkey in the generating of the Rotating Device ID + // SHALL NOT be the same as the UniqueID attribute exposed in the Basic Information cluster. + static constexpr Key kConfigKey_PersistentUniqueId = SilabsConfigKey(kMatterFactory_KeyBase, 0x1F); + static constexpr Key kConfigKey_Creds_KeyId = SilabsConfigKey(kMatterFactory_KeyBase, 0x20); + static constexpr Key kConfigKey_Creds_Base_Addr = SilabsConfigKey(kMatterFactory_KeyBase, 0x21); + static constexpr Key kConfigKey_Creds_DAC_Offset = SilabsConfigKey(kMatterFactory_KeyBase, 0x22); + static constexpr Key kConfigKey_Creds_DAC_Size = SilabsConfigKey(kMatterFactory_KeyBase, 0x23); + static constexpr Key kConfigKey_Creds_PAI_Offset = SilabsConfigKey(kMatterFactory_KeyBase, 0x24); + static constexpr Key kConfigKey_Creds_PAI_Size = SilabsConfigKey(kMatterFactory_KeyBase, 0x25); + static constexpr Key kConfigKey_Creds_CD_Offset = SilabsConfigKey(kMatterFactory_KeyBase, 0x26); + static constexpr Key kConfigKey_Creds_CD_Size = SilabsConfigKey(kMatterFactory_KeyBase, 0x27); + static constexpr Key kConfigKey_Provision_Request = SilabsConfigKey(kMatterFactory_KeyBase, 0x28); + static constexpr Key kConfigKey_Provision_Version = SilabsConfigKey(kMatterFactory_KeyBase, 0x29); + static constexpr Key kOtaTlvEncryption_KeyId = SilabsConfigKey(kMatterFactory_KeyBase, 0x30); // Matter Config Keys - static constexpr Key kConfigKey_ServiceConfig = SilabsConfigKey(kMatterConfig_KeyBase, 0x01); - static constexpr Key kConfigKey_PairedAccountId = SilabsConfigKey(kMatterConfig_KeyBase, 0x02); - static constexpr Key kConfigKey_ServiceId = SilabsConfigKey(kMatterConfig_KeyBase, 0x03); - static constexpr Key kConfigKey_LastUsedEpochKeyId = SilabsConfigKey(kMatterConfig_KeyBase, 0x05); - static constexpr Key kConfigKey_FailSafeArmed = SilabsConfigKey(kMatterConfig_KeyBase, 0x06); - static constexpr Key kConfigKey_GroupKey = SilabsConfigKey(kMatterConfig_KeyBase, 0x07); - static constexpr Key kConfigKey_HardwareVersion = SilabsConfigKey(kMatterConfig_KeyBase, 0x08); - static constexpr Key kConfigKey_RegulatoryLocation = SilabsConfigKey(kMatterConfig_KeyBase, 0x09); - static constexpr Key kConfigKey_CountryCode = SilabsConfigKey(kMatterConfig_KeyBase, 0x0A); - static constexpr Key kConfigKey_WiFiSSID = SilabsConfigKey(kMatterConfig_KeyBase, 0x0C); - static constexpr Key kConfigKey_WiFiPSK = SilabsConfigKey(kMatterConfig_KeyBase, 0x0D); - static constexpr Key kConfigKey_WiFiSEC = SilabsConfigKey(kMatterConfig_KeyBase, 0x0E); - static constexpr Key kConfigKey_GroupKeyBase = SilabsConfigKey(kMatterConfig_KeyBase, 0x0F); - static constexpr Key kConfigKey_LockUser = SilabsConfigKey(kMatterConfig_KeyBase, 0x10); - static constexpr Key kConfigKey_Credential = SilabsConfigKey(kMatterConfig_KeyBase, 0x11); - static constexpr Key kConfigKey_LockUserName = SilabsConfigKey(kMatterConfig_KeyBase, 0x12); - static constexpr Key kConfigKey_CredentialData = SilabsConfigKey(kMatterConfig_KeyBase, 0x13); - static constexpr Key kConfigKey_UserCredentials = SilabsConfigKey(kMatterConfig_KeyBase, 0x14); - static constexpr Key kConfigKey_WeekDaySchedules = SilabsConfigKey(kMatterConfig_KeyBase, 0x15); - static constexpr Key kConfigKey_YearDaySchedules = SilabsConfigKey(kMatterConfig_KeyBase, 0x16); - static constexpr Key kConfigKey_HolidaySchedules = SilabsConfigKey(kMatterConfig_KeyBase, 0x17); + static constexpr Key kConfigKey_ServiceConfig = SilabsConfigKey(kMatterConfig_KeyBase, 0x01); + static constexpr Key kConfigKey_PairedAccountId = SilabsConfigKey(kMatterConfig_KeyBase, 0x02); + static constexpr Key kConfigKey_ServiceId = SilabsConfigKey(kMatterConfig_KeyBase, 0x03); + static constexpr Key kConfigKey_LastUsedEpochKeyId = SilabsConfigKey(kMatterConfig_KeyBase, 0x05); + static constexpr Key kConfigKey_FailSafeArmed = SilabsConfigKey(kMatterConfig_KeyBase, 0x06); + static constexpr Key kConfigKey_GroupKey = SilabsConfigKey(kMatterConfig_KeyBase, 0x07); + static constexpr Key kConfigKey_HardwareVersion = SilabsConfigKey(kMatterConfig_KeyBase, 0x08); + static constexpr Key kConfigKey_RegulatoryLocation = SilabsConfigKey(kMatterConfig_KeyBase, 0x09); + static constexpr Key kConfigKey_CountryCode = SilabsConfigKey(kMatterConfig_KeyBase, 0x0A); + static constexpr Key kConfigKey_WiFiSSID = SilabsConfigKey(kMatterConfig_KeyBase, 0x0C); + static constexpr Key kConfigKey_WiFiPSK = SilabsConfigKey(kMatterConfig_KeyBase, 0x0D); + static constexpr Key kConfigKey_WiFiSEC = SilabsConfigKey(kMatterConfig_KeyBase, 0x0E); + static constexpr Key kConfigKey_GroupKeyBase = SilabsConfigKey(kMatterConfig_KeyBase, 0x0F); + static constexpr Key kConfigKey_LockUser = SilabsConfigKey(kMatterConfig_KeyBase, 0x10); + static constexpr Key kConfigKey_Credential = SilabsConfigKey(kMatterConfig_KeyBase, 0x11); + static constexpr Key kConfigKey_LockUserName = SilabsConfigKey(kMatterConfig_KeyBase, 0x12); + static constexpr Key kConfigKey_CredentialData = SilabsConfigKey(kMatterConfig_KeyBase, 0x13); + static constexpr Key kConfigKey_UserCredentials = SilabsConfigKey(kMatterConfig_KeyBase, 0x14); + static constexpr Key kConfigKey_WeekDaySchedules = SilabsConfigKey(kMatterConfig_KeyBase, 0x15); + static constexpr Key kConfigKey_YearDaySchedules = SilabsConfigKey(kMatterConfig_KeyBase, 0x16); + static constexpr Key kConfigKey_HolidaySchedules = SilabsConfigKey(kMatterConfig_KeyBase, 0x17); + // UniqueId exposed in the Basic Information cluster. It is cleared on factoryreset + // We will generate a random ID, if none was previously provided. + static constexpr Key kConfigKey_UniqueId = SilabsConfigKey(kMatterConfig_KeyBase, 0x18); static constexpr Key kConfigKey_OpKeyMap = SilabsConfigKey(kMatterConfig_KeyBase, 0x20); static constexpr Key kConfigKey_BootCount = SilabsConfigKey(kMatterConfig_KeyBase, 0x21); static constexpr Key kConfigKey_TotalOperationalHours = SilabsConfigKey(kMatterConfig_KeyBase, 0x22); diff --git a/src/platform/silabs/provision/ProvisionStorage.h b/src/platform/silabs/provision/ProvisionStorage.h index ff012491ae3d7c..916d088fb66f10 100644 --- a/src/platform/silabs/provision/ProvisionStorage.h +++ b/src/platform/silabs/provision/ProvisionStorage.h @@ -62,18 +62,18 @@ enum ID : uint16_t kCertToolPath = 0x0137, kPylinkLib = 0x0138, // Instance Info, - kSerialNumber = 0x0141, - kVendorId = 0x0142, - kVendorName = 0x0143, - kProductId = 0x0144, - kProductName = 0x0145, - kProductLabel = 0x0146, - kProductUrl = 0x0147, - kPartNumber = 0x0148, - kHwVersion = 0x0151, - kHwVersionStr = 0x0152, - kManufacturingDate = 0x0153, - kUniqueId = 0x0154, + kSerialNumber = 0x0141, + kVendorId = 0x0142, + kVendorName = 0x0143, + kProductId = 0x0144, + kProductName = 0x0145, + kProductLabel = 0x0146, + kProductUrl = 0x0147, + kPartNumber = 0x0148, + kHwVersion = 0x0151, + kHwVersionStr = 0x0152, + kManufacturingDate = 0x0153, + kPersistentUniqueId = 0x0154, // Commissionable Data, kDiscriminator = 0x0161, kSpake2pPasscode = 0x0162, @@ -143,7 +143,7 @@ struct Storage : public GenericStorage, static constexpr size_t kPartNumberLengthMax = 32; static constexpr size_t kHardwareVersionStrLengthMax = 32; static constexpr size_t kManufacturingDateLengthMax = 11; // yyyy-mm-dd + \0 - static constexpr size_t kUniqueIdLengthMax = 16; + static constexpr size_t kPersistentUniqueIdMaxLength = 16; static constexpr size_t kSpake2pVerifierB64LengthMax = BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_VerifierSerialized_Length) + 1; static constexpr size_t kSpake2pSaltB64LengthMax = BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_Max_PBKDF_Salt_Length) + 1; static constexpr size_t kFirmwareInfoSizeMax = 32; @@ -259,8 +259,10 @@ struct Storage : public GenericStorage, CHIP_ERROR SetHardwareVersionString(const char * value, size_t len); CHIP_ERROR SetManufacturingDate(const char * value, size_t len); CHIP_ERROR GetManufacturingDate(uint8_t * value, size_t max, size_t & size); - CHIP_ERROR SetUniqueId(const uint8_t * value, size_t size); - CHIP_ERROR GetUniqueId(uint8_t * value, size_t max, size_t & size); + // PersistentUniqueId is used to generate the RotatingUniqueId + // This PersistentUniqueId SHALL NOT be the same as the UniqueID attribute exposed in the Basic Information cluster. + CHIP_ERROR SetPersistentUniqueId(const uint8_t * value, size_t size); + CHIP_ERROR GetPersistentUniqueId(uint8_t * value, size_t max, size_t & size); // CommissionableDataProvider CHIP_ERROR SetSetupDiscriminator(uint16_t value); CHIP_ERROR SetSpake2pIterationCount(uint32_t value); diff --git a/third_party/silabs/matter_support b/third_party/silabs/matter_support index bf647de36d841e..fddcd73de5d30e 160000 --- a/third_party/silabs/matter_support +++ b/third_party/silabs/matter_support @@ -1 +1 @@ -Subproject commit bf647de36d841e62fdac5d37c0cdfc5ebf9200bc +Subproject commit fddcd73de5d30e41036993dc575f78835fba6e7c From 7e0634cfbcbf4d12885a7ec778e1ce9ba5cb6bd7 Mon Sep 17 00:00:00 2001 From: Raul Marquez <130402456+raul-marquez-csa@users.noreply.github.com> Date: Wed, 30 Oct 2024 06:25:59 -0700 Subject: [PATCH 011/121] Updates variable utcTime to utcTime2 (#33831) --- src/python_testing/TC_VALCC_4_4.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/python_testing/TC_VALCC_4_4.py b/src/python_testing/TC_VALCC_4_4.py index b85ff9a9f024e4..63cc6170ab5888 100644 --- a/src/python_testing/TC_VALCC_4_4.py +++ b/src/python_testing/TC_VALCC_4_4.py @@ -172,17 +172,17 @@ async def test_TC_VALCC_4_4(self): pass self.step(11) - utcTime = await self.read_single_attribute_check_success(endpoint=0, cluster=Clusters.Objects.TimeSynchronization, attribute=Clusters.TimeSynchronization.Attributes.UTCTime) + utcTime2 = await self.read_single_attribute_check_success(endpoint=0, cluster=Clusters.Objects.TimeSynchronization, attribute=Clusters.TimeSynchronization.Attributes.UTCTime) - asserts.assert_true(utcTime is not NullValue, "OpenDuration is null") + asserts.assert_true(utcTime2 is not NullValue, "OpenDuration is null") self.step(12) auto_close_time_dut = await self.read_valcc_attribute_expect_success(endpoint=endpoint, attribute=attributes.AutoCloseTime) asserts.assert_true(auto_close_time_dut is not NullValue, "AutoCloseTime is null") - asserts.assert_greater_equal(auto_close_time_dut, (utcTime + ((defaultOpenDuration - 5) * 1000000)), + asserts.assert_greater_equal(auto_close_time_dut, (utcTime2 + ((defaultOpenDuration - 5) * 1000000)), "AutoCloseTime is not in the expected range") - asserts.assert_less_equal(auto_close_time_dut, (utcTime + (defaultOpenDuration * 1000000)), + asserts.assert_less_equal(auto_close_time_dut, (utcTime2 + (defaultOpenDuration * 1000000)), "AutoCloseTime is not in the expected range") self.step(13) From 7df767603817b737bd2d173d30da9751492bca39 Mon Sep 17 00:00:00 2001 From: Shubham Patil Date: Wed, 30 Oct 2024 19:26:12 +0530 Subject: [PATCH 012/121] OpenThread: ClearAllSrpHostAndServices should be guarded with CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT (#36284) The code block added in #35065 should be guarded, if the thread stack manager is not pulled in then this function is not available and breaks the compilation. --- .../OpenThread/GenericNetworkCommissioningThreadDriver.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp b/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp index 0c1d482f84c751..fe5bd40a0afb42 100644 --- a/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp +++ b/src/platform/OpenThread/GenericNetworkCommissioningThreadDriver.cpp @@ -189,6 +189,7 @@ void GenericThreadDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * c status = Status::kUnknownError; } +#if CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT if (status == Status::kSuccess && ThreadStackMgrImpl().IsThreadAttached()) { Thread::OperationalDataset currentDataset; @@ -206,6 +207,7 @@ void GenericThreadDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * c status = Status::kUnknownError; } } +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD_SRP_CLIENT if (status == Status::kSuccess && DeviceLayer::ThreadStackMgrImpl().AttachToThreadNetwork(mStagingNetwork, callback) != CHIP_NO_ERROR) From fe5ddda8cdc897bc73ed0e94faaa2cb2d926cf9d Mon Sep 17 00:00:00 2001 From: Marius Tache <102153746+marius-alex-tache@users.noreply.github.com> Date: Wed, 30 Oct 2024 18:12:14 +0200 Subject: [PATCH 013/121] [NXP] Update gn args naming (#36294) * [nxp][common] Update gn args after name change Signed-off-by: marius-alex-tache * [nxp] Bump nxp_matter_support Signed-off-by: marius-alex-tache * Restyled by gn * Restyled by prettier-markdown * [nxp] Fix rt1060 arg Signed-off-by: marius-alex-tache * [nxp] Fix rt1170 arg Signed-off-by: marius-alex-tache --------- Signed-off-by: marius-alex-tache Co-authored-by: Restyled.io --- config/nxp/chip-cmake-freertos/CMakeLists.txt | 8 ++--- docs/platforms/nxp/nxp_manufacturing_flow.md | 16 ++++----- docs/platforms/nxp/nxp_mcxw71_ota_guide.md | 2 +- .../all-clusters-app/nxp/rt/rt1060/BUILD.gn | 2 +- .../all-clusters-app/nxp/rt/rt1060/README.md | 10 +++--- .../all-clusters-app/nxp/rt/rt1170/BUILD.gn | 2 +- .../all-clusters-app/nxp/rt/rt1170/README.md | 8 ++--- .../all-clusters-app/nxp/rt/rw61x/BUILD.gn | 12 +++---- .../all-clusters-app/nxp/rt/rw61x/README.md | 16 ++++----- examples/contact-sensor-app/nxp/README.md | 6 ++-- .../contact-sensor-app/nxp/k32w0/BUILD.gn | 2 +- .../contact-sensor-app/nxp/k32w0/README.md | 18 +++++----- .../contact-sensor-app/nxp/k32w0/args.gni | 2 +- .../nxp/k32w0/include/FreeRTOSConfig.h | 2 +- .../nxp/k32w0/main/AppTask.cpp | 26 +++++++------- .../nxp/k32w0/main/include/AppEvent.h | 4 +-- .../nxp/k32w0/main/main.cpp | 10 +++--- .../contact-sensor-app/nxp/k32w1/BUILD.gn | 12 +++---- .../contact-sensor-app/nxp/k32w1/args.gni | 2 +- .../contact-sensor-app/nxp/mcxw71/BUILD.gn | 12 +++---- .../contact-sensor-app/nxp/mcxw71/args.gni | 2 +- .../laundry-washer-app/nxp/rt/rt1060/BUILD.gn | 2 +- .../laundry-washer-app/nxp/rt/rt1170/BUILD.gn | 2 +- .../laundry-washer-app/nxp/rt/rw61x/BUILD.gn | 12 +++---- examples/lighting-app/nxp/README.md | 2 +- examples/lighting-app/nxp/k32w0/BUILD.gn | 2 +- examples/lighting-app/nxp/k32w0/README.md | 14 ++++---- examples/lighting-app/nxp/k32w0/args.gni | 2 +- examples/lighting-app/nxp/k32w1/BUILD.gn | 12 +++---- examples/lighting-app/nxp/k32w1/README.md | 14 ++++---- examples/lighting-app/nxp/k32w1/args.gni | 8 ++--- .../lighting-app/nxp/k32w1/with_pw_rpc.gni | 2 +- examples/lighting-app/nxp/mcxw71/BUILD.gn | 12 +++---- examples/lighting-app/nxp/mcxw71/README.md | 14 ++++---- examples/lighting-app/nxp/mcxw71/args.gni | 8 ++--- .../lighting-app/nxp/mcxw71/with_pw_rpc.gni | 2 +- examples/lock-app/nxp/README.md | 2 +- examples/lock-app/nxp/k32w1/BUILD.gn | 14 ++++---- examples/lock-app/nxp/k32w1/args.gni | 6 ++-- examples/lock-app/nxp/mcxw71/BUILD.gn | 14 ++++---- examples/lock-app/nxp/mcxw71/args.gni | 6 ++-- .../k32w0/doc/CustomFactoryDataProvider.md | 4 +-- .../project_include/freeRTOS/FreeRTOSConfig.h | 2 +- .../nxp/mcxw71_k32w1/app/support/BUILD.gn | 6 ++-- .../mcxw71_k32w1/app/support/FreeRtosHooks.c | 5 +-- examples/thermostat/nxp/rt/rt1060/BUILD.gn | 2 +- examples/thermostat/nxp/rt/rt1170/BUILD.gn | 2 +- examples/thermostat/nxp/rt/rw61x/BUILD.gn | 12 +++---- scripts/build/builders/nxp.py | 10 +++--- .../nxp/common/ble/BLEManagerCommon.cpp | 28 +++++++-------- src/platform/nxp/k32w0/BLEManagerImpl.cpp | 4 +-- src/platform/nxp/k32w0/BUILD.gn | 9 +++-- src/platform/nxp/k32w0/LowPowerHooks.cpp | 2 +- .../nxp/k32w0/PlatformManagerImpl.cpp | 4 +-- .../nxp/k32w0/ThreadStackManagerImpl.cpp | 4 +-- src/platform/nxp/mcxw71_k32w1/BUILD.gn | 20 +++++------ .../nxp/mcxw71_k32w1/LowPowerHooks.cpp | 2 +- src/platform/nxp/mcxw71_k32w1/args.gni | 12 +------ src/platform/nxp/rt/rt1060/BUILD.gn | 4 +-- src/platform/nxp/rt/rt1170/BUILD.gn | 4 +-- src/platform/nxp/rt/rw61x/BUILD.gn | 20 +++++------ third_party/nxp/nxp_matter_support | 2 +- .../openthread/platforms/nxp/k32w0/BUILD.gn | 2 +- .../platforms/nxp/mcxw71_k32w1/BUILD.gn | 36 +++++++++++-------- .../platforms/nxp/rt/rt1060/BUILD.gn | 4 +-- .../platforms/nxp/rt/rt1170/BUILD.gn | 4 +-- .../platforms/nxp/rt/rw61x/BUILD.gn | 4 +-- 67 files changed, 263 insertions(+), 269 deletions(-) diff --git a/config/nxp/chip-cmake-freertos/CMakeLists.txt b/config/nxp/chip-cmake-freertos/CMakeLists.txt index 27bedc50ae53a9..517d3539329b2b 100644 --- a/config/nxp/chip-cmake-freertos/CMakeLists.txt +++ b/config/nxp/chip-cmake-freertos/CMakeLists.txt @@ -44,10 +44,10 @@ endif() # ============================================================================== matter_add_gn_arg_string("nxp_nvm_component" ${CONFIG_CHIP_NVM_COMPONENT}) matter_add_gn_arg_string("nxp_platform" ${CONFIG_CHIP_NXP_PLATFORM}) -matter_add_gn_arg("chip_with_factory_data" ${CONFIG_CHIP_FACTORY_DATA}) -matter_add_gn_arg("chip_enable_secure_dac_private_key_storage" ${CONFIG_CHIP_SECURE_DAC_PRIVATE_KEY_STORAGE}) -matter_add_gn_arg("chip_enable_secure_whole_factory_data" ${CONFIG_CHIP_ENABLE_SECURE_WHOLE_FACTORY_DATA}) -matter_add_gn_arg_bool("chip_enable_matter_cli" CONFIG_CHIP_LIB_SHELL) +matter_add_gn_arg_bool("nxp_use_factory_data" ${CONFIG_CHIP_FACTORY_DATA}) +matter_add_gn_arg_bool("nxp_enable_secure_dac_private_key_storage" ${CONFIG_CHIP_SECURE_DAC_PRIVATE_KEY_STORAGE}) +matter_add_gn_arg_bool("nxp_enable_secure_whole_factory_data" ${CONFIG_CHIP_ENABLE_SECURE_WHOLE_FACTORY_DATA}) +matter_add_gn_arg_bool("nxp_enable_matter_cli" CONFIG_CHIP_LIB_SHELL) matter_add_gn_arg_bool("chip_enable_pairing_autostart" CONFIG_CHIP_ENABLE_PAIRING_AUTOSTART) if (CONFIG_USE_CHIP_DATA_MODEL_INTERFACE) diff --git a/docs/platforms/nxp/nxp_manufacturing_flow.md b/docs/platforms/nxp/nxp_manufacturing_flow.md index 08e09c866388ff..28618b276a5e01 100644 --- a/docs/platforms/nxp/nxp_manufacturing_flow.md +++ b/docs/platforms/nxp/nxp_manufacturing_flow.md @@ -148,7 +148,7 @@ Here is the interpretation of the **optional** parameters: ## 4. Build app and usage -Use `chip_with_factory_data=1` when compiling to enable factory data usage. +Use `nxp_use_factory_data=true` when compiling to enable factory data usage. Run chip-tool with a new PAA: @@ -177,7 +177,7 @@ Implementation of manufacturing data provisioning has been validated using test certificates generated by `OpenSSL 1.1.1l`. Also, demo **DAC**, **PAI** and **PAA** certificates needed in case -`chip_with_factory_data=1` is used can be found in +`nxp_use_factory_data=true` is used can be found in `./scripts/tools/nxp/demo_generated_certs`. ## 6. Increased security for DAC private key @@ -207,7 +207,7 @@ python3 ./scripts/tools/nxp/factory_data_generator/generate.py -i 10000 -s UXKLz There is no need for an extra binary. - Write factory data binary. -- Build the application with `chip_with_factory_data=1` set. +- Build the application with `nxp_use_factory_data=true` set. - Write the application to the board and use it as usual. Factory data should now contain a corresponding encrypted blob instead of the @@ -236,19 +236,19 @@ Supported platforms: there are three implementations for factory data protection -- whole factory data protection with AES encryption ( chip_with_factory_data=1 - chip_enable_secure_whole_factory_data=true ) +- whole factory data protection with AES encryption ( + nxp_use_factory_data=true nxp_enable_secure_whole_factory_data=true ) `examples/platform/nxp/rt/rw61x/factory_data/source/AppFactoryDataExample.cpp`\ `src/platform/nxp/rt/rw61x/FactoryDataProviderEncImpl.cpp` -- only dac private key protection ( chip_with_factory_data=1 - chip_enable_secure_dac_private_key_storage=true ) +- only dac private key protection ( nxp_use_factory_data=true + nxp_enable_secure_dac_private_key_storage=true ) `examples/platform/nxp/rt/rw61x/factory_data/source/AppFactoryDataExample.cpp` \ `src/platform/nxp/rt/rw61x/FactoryDataProviderImpl.cpp` - whole factory data protection with hard-coded AES key ( - chip_with_factory_data=1 ) + nxp_use_factory_data=true ) `examples/platform/nxp/common/factory_data/source/AppFactoryDataDefaultImpl.cpp` \ `src/platform/nxp/common/factory_data/FactoryDataProviderFwkImpl.cpp` diff --git a/docs/platforms/nxp/nxp_mcxw71_ota_guide.md b/docs/platforms/nxp/nxp_mcxw71_ota_guide.md index b21bf933d7e98e..c8d97b7ade4690 100644 --- a/docs/platforms/nxp/nxp_mcxw71_ota_guide.md +++ b/docs/platforms/nxp/nxp_mcxw71_ota_guide.md @@ -61,7 +61,7 @@ version. A user can update the factory data through OTA, at the same time the application firmware is updated by enabling the following processor in the `gn args`: -- `chip_enable_ota_factory_data_processor=1` to enable default factory data +- `nxp_enable_ota_factory_data_processor=true` to enable default factory data update processor (disabled by default). The OTA image used must be updated to include the new factory data. diff --git a/examples/all-clusters-app/nxp/rt/rt1060/BUILD.gn b/examples/all-clusters-app/nxp/rt/rt1060/BUILD.gn index 16e0b03e017c94..beca71ac1002d8 100644 --- a/examples/all-clusters-app/nxp/rt/rt1060/BUILD.gn +++ b/examples/all-clusters-app/nxp/rt/rt1060/BUILD.gn @@ -167,7 +167,7 @@ rt_executable("all_cluster_app") { "${chip_root}/examples/${app_common_folder}/src/static-supported-modes-manager.cpp", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "ENABLE_CHIP_SHELL" ] deps += [ "${chip_root}/examples/shell/shell_common:shell_common", diff --git a/examples/all-clusters-app/nxp/rt/rt1060/README.md b/examples/all-clusters-app/nxp/rt/rt1060/README.md index 558ae4127fe72e..96822ff6eb2453 100644 --- a/examples/all-clusters-app/nxp/rt/rt1060/README.md +++ b/examples/all-clusters-app/nxp/rt/rt1060/README.md @@ -393,14 +393,14 @@ thermostat application for now. - Build Matter with Border Router configuration with ble-wifi commissioning: ``` -user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1060$ gn gen --args="chip_enable_wifi=true w8801_transceiver=true chip_enable_matter_cli=true chip_config_network_layer_ble=true chip_enable_openthread=true k32w0_transceiver=true k32w0_transceiver_bin_path=\"/path/to/ot-rcp/ot-rcp-ble-hci-bb-k32w061.elf.bin.h\" hci_spinel_single_uart=true" out/debug +user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1060$ gn gen --args="chip_enable_wifi=true w8801_transceiver=true nxp_enable_matter_cli=true chip_config_network_layer_ble=true chip_enable_openthread=true k32w0_transceiver=true k32w0_transceiver_bin_path=\"/path/to/ot-rcp/ot-rcp-ble-hci-bb-k32w061.elf.bin.h\" hci_spinel_single_uart=true" out/debug user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1060$ ninja -C out/debug ``` - Build Matter with Border Router configuration with onnetwork commissioning: ``` -user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1060$ gn gen --args="chip_enable_wifi=true w8801_transceiver=true chip_enable_matter_cli=true chip_config_network_layer_ble=false wifi_auto_connect_at_boot=true wifi_auto_connect_at_boot_ssid=\"your_wifi_ssid\" wifi_auto_connect_at_boot_password=\"your_wifi_password\" chip_enable_openthread=true k32w0_transceiver=true k32w0_transceiver_bin_path=\"/path/to/ot-rcp/ot-rcp-ble-hci-bb-k32w061.elf.bin.h\"" out/debug +user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1060$ gn gen --args="chip_enable_wifi=true w8801_transceiver=true nxp_enable_matter_cli=true chip_config_network_layer_ble=false wifi_auto_connect_at_boot=true wifi_auto_connect_at_boot_ssid=\"your_wifi_ssid\" wifi_auto_connect_at_boot_password=\"your_wifi_password\" chip_enable_openthread=true k32w0_transceiver=true k32w0_transceiver_bin_path=\"/path/to/ot-rcp/ot-rcp-ble-hci-bb-k32w061.elf.bin.h\"" out/debug user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1060$ ninja -C out/debug ``` @@ -419,15 +419,15 @@ Optional GN options that can be added when building an application: Wifi + OpenThread Border Router configuration. Note that is only supported on the on the thermostat application for now. - To enable the [matter CLI](README.md#matter-shell), the argument - `chip_enable_matter_cli=true` must be added to the _gn gen_ command. + `nxp_enable_matter_cli=true` must be added to the _gn gen_ command. - To build the application in debug mode, the argument `is_debug=true optimize_debug=false` must be added to the _gn gen_ command. - By default, the MIMXRT1060-EVK-B will be chosen. To switch to an MIMXRT1060-EVK, the argument `evkname=\"evkmimxrt1060\"` must be added to the _gn gen_ command. - To build with the option to have Matter certificates/keys pre-loaded in a - specific flash area the argument `chip_with_factory_data=1` must be added to - the _gn gen_ command. For more information, see + specific flash area the argument `nxp_use_factory_data=true` must be added + to the _gn gen_ command. For more information, see [Guide for writing manufacturing data on NXP devices](../../../../../docs/platforms/nxp/nxp_manufacturing_flow.md) diff --git a/examples/all-clusters-app/nxp/rt/rt1170/BUILD.gn b/examples/all-clusters-app/nxp/rt/rt1170/BUILD.gn index 724a6e89ec6558..70a0a4d640738c 100644 --- a/examples/all-clusters-app/nxp/rt/rt1170/BUILD.gn +++ b/examples/all-clusters-app/nxp/rt/rt1170/BUILD.gn @@ -153,7 +153,7 @@ rt_executable("all_cluster_app") { "${chip_root}/examples/${app_common_folder}/src/static-supported-modes-manager.cpp", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "ENABLE_CHIP_SHELL" ] deps += [ "${chip_root}/examples/shell/shell_common:shell_common", diff --git a/examples/all-clusters-app/nxp/rt/rt1170/README.md b/examples/all-clusters-app/nxp/rt/rt1170/README.md index 7ff91872a4b1b4..8b992982045e71 100644 --- a/examples/all-clusters-app/nxp/rt/rt1170/README.md +++ b/examples/all-clusters-app/nxp/rt/rt1170/README.md @@ -218,7 +218,7 @@ thermostat application for now. (ble-wifi) : ``` -user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt11170$ gn gen --args="chip_enable_wifi=true iwx12_transceiver=true chip_config_network_layer_ble=true chip_enable_ble=true chip_enable_openthread=true chip_enable_matter_cli=true" out/debug +user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt11170$ gn gen --args="chip_enable_wifi=true iwx12_transceiver=true chip_config_network_layer_ble=true chip_enable_ble=true chip_enable_openthread=true nxp_enable_matter_cli=true" out/debug user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rt1170$ ninja -C out/debug ``` @@ -238,13 +238,13 @@ Optional GN options that can be added when building an application: on the on the thermostat application for now. - To enable the [matter CLI](#testing-the-all-clusters-application-with-matter-cli-enabled), - the argument `chip_enable_matter_cli=true` must be added to the _gn gen_ + the argument `nxp_enable_matter_cli=true` must be added to the _gn gen_ command. - To build the application in debug mode, the argument `is_debug=true optimize_debug=false` must be added to the _gn gen_ command. - To build with the option to have Matter certificates/keys pre-loaded in a - specific flash area the argument `chip_with_factory_data=1` must be added to - the _gn gen_ command. For more information, see + specific flash area the argument `nxp_use_factory_data=true` must be added + to the _gn gen_ command. For more information, see [Guide for writing manufacturing data on NXP devices](../../../../../docs/platforms/nxp/nxp_manufacturing_flow.md) - To build the application with the OTA Requestor enabled, the arguments `chip_enable_ota_requestor=true no_mcuboot=false` must be added to the _gn diff --git a/examples/all-clusters-app/nxp/rt/rw61x/BUILD.gn b/examples/all-clusters-app/nxp/rt/rw61x/BUILD.gn index 19fa822ec24688..73f21538380b0e 100644 --- a/examples/all-clusters-app/nxp/rt/rw61x/BUILD.gn +++ b/examples/all-clusters-app/nxp/rt/rw61x/BUILD.gn @@ -56,8 +56,8 @@ rt_sdk("sdk") { defines = [] # To be moved, temporary mbedtls config fix to build app with factory data - if (chip_enable_secure_dac_private_key_storage || - chip_enable_secure_whole_factory_data) { + if (nxp_enable_secure_dac_private_key_storage || + nxp_enable_secure_whole_factory_data) { defines += [ "MBEDTLS_NIST_KW_C", "MBEDTLS_PSA_CRYPTO_CLIENT", @@ -141,10 +141,10 @@ rt_executable("all_cluster_app") { "../../common/main/main.cpp", ] - if (chip_enable_secure_dac_private_key_storage || - chip_enable_secure_whole_factory_data) { + if (nxp_enable_secure_dac_private_key_storage || + nxp_enable_secure_whole_factory_data) { sources += [ "${chip_root}/examples/platform/nxp/${nxp_platform}/factory_data/source/AppFactoryDataExample.cpp" ] - if (chip_enable_secure_whole_factory_data) { + if (nxp_enable_secure_whole_factory_data) { defines += [ "ENABLE_SECURE_WHOLE_FACTORY_DATA" ] } } else { @@ -184,7 +184,7 @@ rt_executable("all_cluster_app") { "${chip_root}/examples/all-clusters-app/all-clusters-common/src/static-supported-modes-manager.cpp", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "ENABLE_CHIP_SHELL" ] deps += [ "${chip_root}/examples/shell/shell_common:shell_common", diff --git a/examples/all-clusters-app/nxp/rt/rw61x/README.md b/examples/all-clusters-app/nxp/rt/rw61x/README.md index 9b19031c00b44d..455073d390fc02 100644 --- a/examples/all-clusters-app/nxp/rt/rw61x/README.md +++ b/examples/all-clusters-app/nxp/rt/rw61x/README.md @@ -137,7 +137,7 @@ thermostat application for now. (ble-wifi) : ``` -user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rw610$ gn gen --args="chip_enable_wifi=true chip_enable_openthread=true chip_enable_matter_cli=true" out/debug +user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rw610$ gn gen --args="chip_enable_wifi=true chip_enable_openthread=true nxp_enable_matter_cli=true" out/debug user@ubuntu:~/Desktop/git/connectedhomeip/examples/all-clusters-app/nxp/rt/rw610$ ninja -C out/debug ``` @@ -157,7 +157,7 @@ Optional GN options that can be added when building an application: on the on the thermostat application for now. - To enable the [matter CLI](README.md#testing-the-all-clusters-application-with-matter-cli-enabled), - the argument `chip_enable_matter_cli=true` must be added to the _gn gen_ + the argument `nxp_enable_matter_cli=true` must be added to the _gn gen_ command. - By default, the `NXP RD-RW612-BGA` board revision will be chosen. To switch to `NXP FRDM-RW612` board revision, the argument `board_version=\"frdm\"` @@ -165,8 +165,8 @@ Optional GN options that can be added when building an application: - To build the application in debug mode, the argument `is_debug=true optimize_debug=false` must be added to the _gn gen_ command. - To build with the option to have Matter certificates/keys pre-loaded in a - specific flash area the argument `chip_with_factory_data=1` must be added to - the _gn gen_ command. (for more information see + specific flash area the argument `nxp_use_factory_data=true` must be added + to the _gn gen_ command. (for more information see [Guide for writing manufacturing data on NXP devices](../../../../../docs/platforms/nxp/nxp_manufacturing_flow.md). - To build the application with the OTA Requestor enabled, the arguments `chip_enable_ota_requestor=true no_mcuboot=false` must be added to the _gn @@ -187,13 +187,13 @@ software key before flashing them to the device flash. Using DAC private key secure usage: Experimental feature, contain some limitation: potential concurrent access issue during sign with dac key operation due to the lack of protection between multiple access to `ELS` crypto module. -The argument `chip_enable_secure_dac_private_key_storage=1` must be added to the -_gn gen_ command to enable secure private DAC key usage with S50. -`chip_with_factory_data=1` must have been added to the _gn gen_ command +The argument `nxp_enable_secure_dac_private_key_storage=true` must be added to +the _gn gen_ command to enable secure private DAC key usage with S50. +`nxp_use_factory_data=true` must have been added to the _gn gen_ command DAC private key generation: The argument `chip_convert_dac_private_key=1` must be added to the _gn gen_ command to enable DAC private plain key conversion to -blob with S50. `chip_enable_secure_dac_private_key_storage=1` must have been +blob with S50. `nxp_enable_secure_dac_private_key_storage=1` must have been added to the _gn gen_ command `ELS` contain concurrent access risks. They must be fixed before enabling it by diff --git a/examples/contact-sensor-app/nxp/README.md b/examples/contact-sensor-app/nxp/README.md index 803f067ce3de72..908da90cfcb664 100644 --- a/examples/contact-sensor-app/nxp/README.md +++ b/examples/contact-sensor-app/nxp/README.md @@ -133,7 +133,7 @@ corresponding to data model target. ### Manufacturing data -Use `chip_with_factory_data=1` in the gn build command to enable factory data. +Use `nxp_use_factory_data=true` in the gn build command to enable factory data. For a full guide on manufacturing flow, please see [Guide for writing manufacturing data on NXP devices](../../../docs/platforms/nxp/nxp_manufacturing_flow.md). @@ -181,9 +181,9 @@ will be very low. In order to build with low power support, the following gn args must be used: ``` -chip_with_low_power = 1 +nxp_use_low_power = true chip_openthread_ftd = false -chip_with_ot_cli = 0 +nxp_enable_ot_cli = false chip_logging = false ``` diff --git a/examples/contact-sensor-app/nxp/k32w0/BUILD.gn b/examples/contact-sensor-app/nxp/k32w0/BUILD.gn index f032603d00457b..a691fc87137b66 100644 --- a/examples/contact-sensor-app/nxp/k32w0/BUILD.gn +++ b/examples/contact-sensor-app/nxp/k32w0/BUILD.gn @@ -100,7 +100,7 @@ k32w0_executable("contact_sensor_app") { "main/main.cpp", ] - if (chip_with_factory_data == 1 && use_custom_factory_provider == 1) { + if (nxp_use_factory_data && use_custom_factory_provider == 1) { sources += [ "${k32w0_platform_dir}/common/CustomFactoryDataProvider.cpp", "${k32w0_platform_dir}/common/CustomFactoryDataProvider.h", diff --git a/examples/contact-sensor-app/nxp/k32w0/README.md b/examples/contact-sensor-app/nxp/k32w0/README.md index bc39009afc3cb9..c390bc3ab5215b 100644 --- a/examples/contact-sensor-app/nxp/k32w0/README.md +++ b/examples/contact-sensor-app/nxp/k32w0/README.md @@ -243,8 +243,8 @@ Also, in case the OM15082 Expansion Board is not attached to the DK6 board, the build argument (chip_with_OM15082) inside the gn build instruction should be set to zero. The argument chip_with_OM15082 is set to zero by default. -In case that Openthread CLI is needed, chip_with_ot_cli build argument must be -set to 1. +In case that Openthread CLI is needed, `nxp_enable_ot_cli` build argument must +be set to `true`. In case the board doesn't have 32KHz crystal fitted, one can use the 32KHz free running oscillator as a clock source. In this case one must set the use_fro_32k @@ -371,10 +371,10 @@ CHIPProjectConfig.h. Regarding factory data provider, there are two options: - use the default factory data provider: `FactoryDataProviderImpl` by setting - `chip_with_factory_data=1` in the gn build command. + `nxp_use_factory_data=true` in the gn build command. - use a custom factory data provider: please see [Guide for implementing a custom factory data provider](../../../platform/nxp/k32w0/doc/CustomFactoryDataProvider.md). - This can be enabled when `chip_with_factory_data=1` by setting + This can be enabled when `nxp_use_factory_data=true` by setting `use_custom_factory_provider=1` in the gn build command. ## Flashing and debugging @@ -697,9 +697,9 @@ factory data TLV value. A user can select which default processors to enable: -- `chip_enable_ota_firmware_processor=1` to enable default firmware (app/SSBL) - update processor (enabled by default). -- `chip_enable_ota_factory_data_processor=1` to enable default factory data +- `nxp_enable_ota_firmware_processor=true` to enable default firmware + (app/SSBL) update processor (enabled by default). +- `nxp_enable_ota_factory_data_processor=true` to enable default factory data update processor (disabled by default). The address for storing the custom OTA entry can also be specified: @@ -799,9 +799,9 @@ The example also offers the possibility to run in low power mode. This means that the board will go in a deep power down mode most of the time and the power consumption will be very low. -In order to build with low power support, the _chip_with_low_power=1_ must be +In order to build with low power support, the _nxp_use_low_power=true_ must be provided to the build system. In this case, please note that the GN build -arguments _chip_with_OM15082_ and _chip_with_ot_cli_ must be set to 0 and +arguments _chip_with_OM15082_ and _nxp_enable_ot_cli_ must be set to false and _chip_logging_ must be set to false to disable logging. In order to maintain a low power consumption, the LEDs showing the state of the diff --git a/examples/contact-sensor-app/nxp/k32w0/args.gni b/examples/contact-sensor-app/nxp/k32w0/args.gni index f4b68ae740c40c..1f2e2ef966e4c9 100644 --- a/examples/contact-sensor-app/nxp/k32w0/args.gni +++ b/examples/contact-sensor-app/nxp/k32w0/args.gni @@ -35,6 +35,6 @@ is_debug = false chip_crypto = "platform" chip_crypto_flavor = "NXP-Ultrafast-P256" -chip_with_ot_cli = 0 +nxp_enable_ot_cli = false chip_with_OM15082 = 1 chip_pw_tokenizer_logging = true diff --git a/examples/contact-sensor-app/nxp/k32w0/include/FreeRTOSConfig.h b/examples/contact-sensor-app/nxp/k32w0/include/FreeRTOSConfig.h index 5694c591e51362..78fed95d41c6f9 100644 --- a/examples/contact-sensor-app/nxp/k32w0/include/FreeRTOSConfig.h +++ b/examples/contact-sensor-app/nxp/k32w0/include/FreeRTOSConfig.h @@ -41,7 +41,7 @@ #define configUSE_PREEMPTION 1 -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) #define configUSE_TICKLESS_IDLE 1 #else #define configUSE_TICKLESS_IDLE 0 diff --git a/examples/contact-sensor-app/nxp/k32w0/main/AppTask.cpp b/examples/contact-sensor-app/nxp/k32w0/main/AppTask.cpp index 36cf190adf0b54..40ffd9d8bff252 100644 --- a/examples/contact-sensor-app/nxp/k32w0/main/AppTask.cpp +++ b/examples/contact-sensor-app/nxp/k32w0/main/AppTask.cpp @@ -65,7 +65,7 @@ TimerHandle_t sFunctionTimer; // FreeRTOS app sw timer. static QueueHandle_t sAppEventQueue; -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) +#if !defined(nxp_use_low_power) || (nxp_use_low_power == 0) static LEDWidget sStatusLED; static LEDWidget sContactSensorLED; #endif @@ -225,7 +225,7 @@ CHIP_ERROR AppTask::Init() AppTask::PrintOnboardingInfo(); /* HW init leds */ -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) +#if !defined(nxp_use_low_power) || (nxp_use_low_power == 0) LED_Init(); /* start with all LEDS turnedd off */ @@ -365,7 +365,7 @@ void AppTask::AppTaskMain(void * pvParameter) { TickType_t xTicksToWait = pdMS_TO_TICKS(10); -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) xTicksToWait = portMAX_DELAY; #endif @@ -403,7 +403,7 @@ void AppTask::AppTaskMain(void * pvParameter) // // Otherwise, blink the LED ON for a very short time. -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) +#if !defined(nxp_use_low_power) || (nxp_use_low_power == 0) if (sAppTask.mFunction != Function::kFactoryReset && sAppTask.mFunction != Function::kIdentify) { if (sIsThreadProvisioned) @@ -580,7 +580,7 @@ void AppTask::ResetActionEventHandler(void * aGenericEvent) sAppTask.CancelTimer(); sAppTask.mFunction = Function::kNoneSelected; -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) +#if !defined(nxp_use_low_power) || (nxp_use_low_power == 0) /* restore initial state for the LED indicating contact state */ if (!ContactSensorMgr().IsContactClosed()) { @@ -608,7 +608,7 @@ void AppTask::ResetActionEventHandler(void * aGenericEvent) sAppTask.mFunction = Function::kFactoryReset; /* LEDs will start blinking to signal that a Factory Reset was scheduled */ -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) +#if !defined(nxp_use_low_power) || (nxp_use_low_power == 0) sStatusLED.Set(false); sContactSensorLED.Set(false); @@ -706,7 +706,7 @@ void AppTask::BleStartAdvertising(intptr_t arg) if (ConnectivityMgr().IsBLEAdvertisingEnabled()) { ConnectivityMgr().SetBLEAdvertisingEnabled(false); -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) +#if !defined(nxp_use_low_power) || (nxp_use_low_power == 0) sStatusLED.Set(false); #endif K32W_LOG("Stopped BLE Advertising!"); @@ -717,7 +717,7 @@ void AppTask::BleStartAdvertising(intptr_t arg) if (chip::Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() == CHIP_NO_ERROR) { -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) +#if !defined(nxp_use_low_power) || (nxp_use_low_power == 0) sStatusLED.Set(true); #endif K32W_LOG("Started BLE Advertising!"); @@ -845,14 +845,14 @@ void AppTask::OnStateChanged(ContactSensorManager::State aState) if (ContactSensorManager::State::kContactClosed == aState) { K32W_LOG("Contact state changed to closed.") -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) +#if !defined(nxp_use_low_power) || (nxp_use_low_power == 0) sContactSensorLED.Set(true); #endif } else if (ContactSensorManager::State::kContactOpened == aState) { K32W_LOG("Contact state changed to opened.") -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) +#if !defined(nxp_use_low_power) || (nxp_use_low_power == 0) sContactSensorLED.Set(false); #endif } @@ -876,7 +876,7 @@ void AppTask::OnIdentifyStart(Identify * identify) } K32W_LOG("Identify process has started. Status LED should blink every 0.5 seconds."); sAppTask.mFunction = Function::kIdentify; -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) +#if !defined(nxp_use_low_power) || (nxp_use_low_power == 0) sStatusLED.Set(false); sStatusLED.Blink(500); #endif @@ -926,7 +926,7 @@ void AppTask::PostEvent(const AppEvent * aEvent) void AppTask::DispatchEvent(AppEvent * aEvent) { -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) /* specific processing for events sent from App_PostCallbackMessage (see main.cpp) */ if (aEvent->Type == AppEvent::kEventType_Lp) { @@ -974,7 +974,7 @@ void AppTask::UpdateDeviceStateInternal(intptr_t arg) /* get onoff attribute value */ (void) app::Clusters::BooleanState::Attributes::StateValue::Get(1, &stateValueAttrValue); -#if !defined(chip_with_low_power) || (chip_with_low_power == 0) +#if !defined(nxp_use_low_power) || (nxp_use_low_power == 0) /* set the device state */ sContactSensorLED.Set(stateValueAttrValue); #endif diff --git a/examples/contact-sensor-app/nxp/k32w0/main/include/AppEvent.h b/examples/contact-sensor-app/nxp/k32w0/main/include/AppEvent.h index b8ae7e72540ef8..ce1e4fbbc79b7d 100644 --- a/examples/contact-sensor-app/nxp/k32w0/main/include/AppEvent.h +++ b/examples/contact-sensor-app/nxp/k32w0/main/include/AppEvent.h @@ -29,7 +29,7 @@ struct AppEvent kTimer, kContact, kInstall, -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) kEventType_Lp, #endif kOTAResume, @@ -56,7 +56,7 @@ struct AppEvent EventHandler Handler; -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) void * param; #endif }; diff --git a/examples/contact-sensor-app/nxp/k32w0/main/main.cpp b/examples/contact-sensor-app/nxp/k32w0/main/main.cpp index 9517d7e2cf4309..6d6c3af043bddd 100644 --- a/examples/contact-sensor-app/nxp/k32w0/main/main.cpp +++ b/examples/contact-sensor-app/nxp/k32w0/main/main.cpp @@ -35,7 +35,7 @@ #include #endif -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) #include "fsl_gpio.h" #include "fsl_iocon.h" #include "gpio_pins.h" @@ -86,7 +86,7 @@ void APP_SetMaxTxPower() #endif /* low power requirements */ -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) extern "C" void setThreadInitialized(bool isInitialized); extern "C" bool isThreadInitialized(); #endif @@ -160,7 +160,7 @@ extern "C" void main_task(void const * argument) goto exit; } -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) setThreadInitialized(TRUE); #endif @@ -206,7 +206,7 @@ extern "C" void main_task(void const * argument) extern "C" void otSysEventSignalPending(void) { -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) /* make sure that 15.4 radio is initialized before waking up the Thread task */ if (isThreadInitialized()) #endif @@ -216,7 +216,7 @@ extern "C" void otSysEventSignalPending(void) } } -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) extern "C" void vOptimizeConsumption(void) { /* BUTTON2 change contact, BUTTON4 start adv/factoryreset */ diff --git a/examples/contact-sensor-app/nxp/k32w1/BUILD.gn b/examples/contact-sensor-app/nxp/k32w1/BUILD.gn index 1b57e5f3cf9061..c96f9676b2336a 100644 --- a/examples/contact-sensor-app/nxp/k32w1/BUILD.gn +++ b/examples/contact-sensor-app/nxp/k32w1/BUILD.gn @@ -87,7 +87,7 @@ mcxw71_k32w1_sdk("sdk") { "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setup_discriminator}", ] - if (chip_key_storage == "littlefs") { + if (nxp_nvm_component == "littlefs") { include_dirs += [ "${example_platform_dir}/board" ] sources += [ "${example_platform_dir}/board/peripherals.c", @@ -117,7 +117,7 @@ mcxw71_k32w1_executable("contact_sensor_app") { defines += [ "CONFIG_DIAG_LOGS_DEMO=1" ] } - if (chip_with_low_power == 1) { + if (nxp_use_low_power) { defines += [ "CONFIG_LOW_POWER=1" ] } else { defines += [ @@ -158,11 +158,11 @@ mcxw71_k32w1_executable("contact_sensor_app") { "${example_platform_dir}/factory_data/source/AppFactoryDataExample.cpp", ] - if (chip_with_low_power == 1) { + if (nxp_use_low_power) { sources += [ "${common_example_dir}/low_power/source/LowPower.cpp" ] } - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { include_dirs += [ "${chip_root}/src/platform/nxp/common/factory_data/legacy" ] deps += [ "${chip_root}/src/platform/nxp:nxp_factory_data" ] @@ -216,7 +216,7 @@ mcxw71_k32w1_executable("contact_sensor_app") { "../common/main.cpp", ] - if (chip_with_low_power == 0) { + if (!nxp_use_low_power) { sources += [ "${common_example_dir}/ui_feedback/source/LedManager.cpp", "${example_platform_dir}/util/LedOnOff.cpp", @@ -263,7 +263,7 @@ mcxw71_k32w1_executable("contact_sensor_app") { "-T" + rebase_path(ldscript, root_build_dir), ] - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { ldflags += [ "-Wl,--defsym=gUseFactoryData_d=1" ] } diff --git a/examples/contact-sensor-app/nxp/k32w1/args.gni b/examples/contact-sensor-app/nxp/k32w1/args.gni index e5654bdbc707c6..363718f1a8bbab 100644 --- a/examples/contact-sensor-app/nxp/k32w1/args.gni +++ b/examples/contact-sensor-app/nxp/k32w1/args.gni @@ -39,6 +39,6 @@ is_debug = false chip_crypto = "platform" chip_openthread_ftd = false -chip_with_ot_cli = 0 +nxp_enable_ot_cli = false chip_with_diag_logs_demo = true diff --git a/examples/contact-sensor-app/nxp/mcxw71/BUILD.gn b/examples/contact-sensor-app/nxp/mcxw71/BUILD.gn index 8bba2393f8fc43..48719dbc9bd6e9 100644 --- a/examples/contact-sensor-app/nxp/mcxw71/BUILD.gn +++ b/examples/contact-sensor-app/nxp/mcxw71/BUILD.gn @@ -86,7 +86,7 @@ mcxw71_k32w1_sdk("sdk") { "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setup_discriminator}", ] - if (chip_key_storage == "littlefs") { + if (nxp_nvm_component == "littlefs") { include_dirs += [ "${example_platform_dir}/board" ] sources += [ "${example_platform_dir}/board/peripherals.c", @@ -116,7 +116,7 @@ mcxw71_k32w1_executable("contact_sensor_app") { defines += [ "CONFIG_DIAG_LOGS_DEMO=1" ] } - if (chip_with_low_power == 1) { + if (nxp_use_low_power) { defines += [ "CONFIG_LOW_POWER=1" ] } else { defines += [ @@ -157,11 +157,11 @@ mcxw71_k32w1_executable("contact_sensor_app") { "${example_platform_dir}/factory_data/source/AppFactoryDataExample.cpp", ] - if (chip_with_low_power == 1) { + if (nxp_use_low_power) { sources += [ "${common_example_dir}/low_power/source/LowPower.cpp" ] } - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { include_dirs += [ "${chip_root}/src/platform/nxp/common/factory_data/legacy" ] deps += [ "${chip_root}/src/platform/nxp:nxp_factory_data" ] @@ -215,7 +215,7 @@ mcxw71_k32w1_executable("contact_sensor_app") { "../common/main.cpp", ] - if (chip_with_low_power == 0) { + if (!nxp_use_low_power) { sources += [ "${common_example_dir}/ui_feedback/source/LedManager.cpp", "${example_platform_dir}/util/LedOnOff.cpp", @@ -262,7 +262,7 @@ mcxw71_k32w1_executable("contact_sensor_app") { "-T" + rebase_path(ldscript, root_build_dir), ] - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { ldflags += [ "-Wl,--defsym=gUseFactoryData_d=1" ] } diff --git a/examples/contact-sensor-app/nxp/mcxw71/args.gni b/examples/contact-sensor-app/nxp/mcxw71/args.gni index 6e6015933d6cf2..bf06f4e4948fb3 100644 --- a/examples/contact-sensor-app/nxp/mcxw71/args.gni +++ b/examples/contact-sensor-app/nxp/mcxw71/args.gni @@ -37,6 +37,6 @@ is_debug = false chip_crypto = "platform" chip_openthread_ftd = false -chip_with_ot_cli = 0 +nxp_enable_ot_cli = false chip_with_diag_logs_demo = true diff --git a/examples/laundry-washer-app/nxp/rt/rt1060/BUILD.gn b/examples/laundry-washer-app/nxp/rt/rt1060/BUILD.gn index eb7ea93bbd1d2c..ee1e896987ae9b 100644 --- a/examples/laundry-washer-app/nxp/rt/rt1060/BUILD.gn +++ b/examples/laundry-washer-app/nxp/rt/rt1060/BUILD.gn @@ -170,7 +170,7 @@ rt_executable("laundry-washer") { "../../common/main/operational-state-delegate-impl.cpp", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "ENABLE_CHIP_SHELL" ] deps += [ "${chip_root}/examples/shell/shell_common:shell_common", diff --git a/examples/laundry-washer-app/nxp/rt/rt1170/BUILD.gn b/examples/laundry-washer-app/nxp/rt/rt1170/BUILD.gn index 96b035e8628f5d..90be59719a193d 100644 --- a/examples/laundry-washer-app/nxp/rt/rt1170/BUILD.gn +++ b/examples/laundry-washer-app/nxp/rt/rt1170/BUILD.gn @@ -158,7 +158,7 @@ rt_executable("laundry-washer-app") { "../../common/main/operational-state-delegate-impl.cpp", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "ENABLE_CHIP_SHELL" ] deps += [ "${chip_root}/examples/shell/shell_common:shell_common", diff --git a/examples/laundry-washer-app/nxp/rt/rw61x/BUILD.gn b/examples/laundry-washer-app/nxp/rt/rw61x/BUILD.gn index 7f22eca6b2c085..936f1de4a7d262 100644 --- a/examples/laundry-washer-app/nxp/rt/rw61x/BUILD.gn +++ b/examples/laundry-washer-app/nxp/rt/rw61x/BUILD.gn @@ -57,8 +57,8 @@ rt_sdk("sdk") { defines = [] # To be moved, temporary mbedtls config fix to build app with factory data - if (chip_enable_secure_dac_private_key_storage || - chip_enable_secure_whole_factory_data) { + if (nxp_enable_secure_dac_private_key_storage || + nxp_enable_secure_whole_factory_data) { defines += [ "MBEDTLS_NIST_KW_C", "MBEDTLS_PSA_CRYPTO_CLIENT", @@ -142,10 +142,10 @@ rt_executable("laundry-washer") { "../../common/main/main.cpp", ] - if (chip_enable_secure_dac_private_key_storage || - chip_enable_secure_whole_factory_data) { + if (nxp_enable_secure_dac_private_key_storage || + nxp_enable_secure_whole_factory_data) { sources += [ "${chip_root}/examples/platform/nxp/${nxp_platform}/factory_data/source/AppFactoryDataExample.cpp" ] - if (chip_enable_secure_whole_factory_data) { + if (nxp_enable_secure_whole_factory_data) { defines += [ "ENABLE_SECURE_WHOLE_FACTORY_DATA" ] } } else { @@ -189,7 +189,7 @@ rt_executable("laundry-washer") { "../../common/main/operational-state-delegate-impl.cpp", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "ENABLE_CHIP_SHELL" ] deps += [ "${chip_root}/examples/shell/shell_common:shell_common", diff --git a/examples/lighting-app/nxp/README.md b/examples/lighting-app/nxp/README.md index e0860a021ef30b..43fd85219fef20 100644 --- a/examples/lighting-app/nxp/README.md +++ b/examples/lighting-app/nxp/README.md @@ -128,7 +128,7 @@ corresponding to data model target. ### Manufacturing data -Use `chip_with_factory_data=1` in the gn build command to enable factory data. +Use `nxp_use_factory_data=true` in the gn build command to enable factory data. For a full guide on manufacturing flow, please see [Guide for writing manufacturing data on NXP devices](../../../docs/platforms/nxp/nxp_manufacturing_flow.md). diff --git a/examples/lighting-app/nxp/k32w0/BUILD.gn b/examples/lighting-app/nxp/k32w0/BUILD.gn index 65a62229a7f9cd..b44b45062d8793 100644 --- a/examples/lighting-app/nxp/k32w0/BUILD.gn +++ b/examples/lighting-app/nxp/k32w0/BUILD.gn @@ -99,7 +99,7 @@ k32w0_executable("light_app") { "main/main.cpp", ] - if (chip_with_factory_data == 1 && use_custom_factory_provider == 1) { + if (nxp_use_factory_data && use_custom_factory_provider == 1) { sources += [ "${k32w0_platform_dir}/common/CustomFactoryDataProvider.cpp", "${k32w0_platform_dir}/common/CustomFactoryDataProvider.h", diff --git a/examples/lighting-app/nxp/k32w0/README.md b/examples/lighting-app/nxp/k32w0/README.md index 61f35a3e7116ac..43f25500c10b79 100644 --- a/examples/lighting-app/nxp/k32w0/README.md +++ b/examples/lighting-app/nxp/k32w0/README.md @@ -256,8 +256,8 @@ Also, in case the OM15082 Expansion Board is not attached to the DK6 board, the build argument (chip_with_OM15082) inside the gn build instruction should be set to zero. The argument chip_with_OM15082 is set to zero by default. -In case that Openthread CLI is needed, chip_with_ot_cli build argument must be -set to 1. +In case that Openthread CLI is needed, `nxp_enable_ot_cli` build argument must +be set to true. In case the board doesn't have 32KHz crystal fitted, one can use the 32KHz free running oscillator as a clock source. In this case one must set the use_fro_32k @@ -348,10 +348,10 @@ CHIPProjectConfig.h. Regarding factory data provider, there are two options: - use the default factory data provider: `FactoryDataProviderImpl` by setting - `chip_with_factory_data=1` in the gn build command. + `nxp_use_factory_data=true` in the gn build command. - use a custom factory data provider: please see [Guide for implementing a custom factory data provider](../../../platform/nxp/k32w0/doc/CustomFactoryDataProvider.md). - This can be enabled when `chip_with_factory_data=1` by setting + This can be enabled when `nxp_use_factory_data=true` by setting `use_custom_factory_provider=1` in the gn build command. ## Flashing and debugging @@ -669,9 +669,9 @@ factory data TLV value. A user can select which default processors to enable: -- `chip_enable_ota_firmware_processor=1` to enable default firmware (app/SSBL) - update processor (enabled by default). -- `chip_enable_ota_factory_data_processor=1` to enable default factory data +- `nxp_enable_ota_firmware_processor=true` to enable default firmware + (app/SSBL) update processor (enabled by default). +- `nxp_enable_ota_factory_data_processor=true` to enable default factory data update processor (disabled by default). The address for storing the custom OTA entry can also be specified: diff --git a/examples/lighting-app/nxp/k32w0/args.gni b/examples/lighting-app/nxp/k32w0/args.gni index 7126cf38ad5f3b..da4649ea566184 100644 --- a/examples/lighting-app/nxp/k32w0/args.gni +++ b/examples/lighting-app/nxp/k32w0/args.gni @@ -26,6 +26,6 @@ is_debug = false chip_crypto = "platform" chip_crypto_flavor = "NXP-Ultrafast-P256" -chip_with_ot_cli = 0 +nxp_enable_ot_cli = false chip_with_OM15082 = 1 chip_pw_tokenizer_logging = true diff --git a/examples/lighting-app/nxp/k32w1/BUILD.gn b/examples/lighting-app/nxp/k32w1/BUILD.gn index 57a1b7921fcaf9..91f069732282aa 100644 --- a/examples/lighting-app/nxp/k32w1/BUILD.gn +++ b/examples/lighting-app/nxp/k32w1/BUILD.gn @@ -101,7 +101,7 @@ mcxw71_k32w1_sdk("sdk") { "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setup_discriminator}", ] - if (chip_key_storage == "littlefs") { + if (nxp_nvm_component == "littlefs") { include_dirs += [ "${example_platform_dir}/board" ] sources += [ "${example_platform_dir}/board/peripherals.c", @@ -195,7 +195,7 @@ mcxw71_k32w1_executable("light_app") { sources += [ "${example_platform_dir}/rpc/AppRpc.cpp" ] } - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { include_dirs += [ "${chip_root}/src/platform/nxp/common/factory_data/legacy" ] deps += [ "${chip_root}/src/platform/nxp:nxp_factory_data" ] @@ -218,7 +218,7 @@ mcxw71_k32w1_executable("light_app") { "${chip_root}/src/platform/logging:default", ] - if (chip_config_dimmable_led) { + if (nxp_config_dimmable_led) { defines += [ "LIGHTING_MANAGER_ENABLE_DIMMABLE_LED=1" ] sources += [ "${common_example_dir}/led_widget/include/LedDimmer.h", @@ -246,7 +246,7 @@ mcxw71_k32w1_executable("light_app") { ] } - if (use_smu2_static) { + if (nxp_use_smu2_static) { ldscript = "${example_platform_dir}/app/ldscripts/app.ld" base_ldscript_dir = "${nxp_sdk_root}/middleware/wireless/framework/Common/devices/kw45_k32w1/gcc" } else { @@ -263,11 +263,11 @@ mcxw71_k32w1_executable("light_app") { "-T" + rebase_path(ldscript, root_build_dir), ] - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { ldflags += [ "-Wl,--defsym=gUseFactoryData_d=1" ] } - if (use_smu2_static) { + if (nxp_use_smu2_static) { ldflags += [ "-L" + rebase_path(base_ldscript_dir, root_build_dir) ] } diff --git a/examples/lighting-app/nxp/k32w1/README.md b/examples/lighting-app/nxp/k32w1/README.md index 61cec8077cc99a..0b81a1ac5dfdab 100644 --- a/examples/lighting-app/nxp/k32w1/README.md +++ b/examples/lighting-app/nxp/k32w1/README.md @@ -83,8 +83,8 @@ if changed, the names must be updated in `app.ld`. See `SMU2` memory range size. When compiling the application as an OT Full Thread Device -(`chip_openthread_ftd=true`), using `use_smu2_static=true` gn arg will cause the -following symbols to be moved to `SMU2` area: +(`chip_openthread_ftd=true`), using `nxp_use_smu2_static=true` gn arg will cause +the following symbols to be moved to `SMU2` area: | symbol name | file | | ----------------------------------- | ---------------------------- | @@ -93,19 +93,19 @@ following symbols to be moved to `SMU2` area: | `Server::sServer` | `Server.cpp` | | `ThreadStackManagerImpl::sInstance` | `ThreadStackManagerImpl.cpp` | -Additionally, using `use_smu2_dynamic=true` will cause the OpenThread buffers to -be dynamically allocated from a 13KB `SMU2` range after a successful +Additionally, using `nxp_use_smu2_dynamic=true` will cause the OpenThread +buffers to be dynamically allocated from a 13KB `SMU2` range after a successful commissioning process. -`use_smu2_static` and `use_smu2_dynamic` are set to `true` in the default -example. +`nxp_use_smu2_static` and `nxp_use_smu2_dynamic` are set to `true` in the +default example. ### LED PWM In the default configuration, the onboard RGB LED pins are configured as GPIO pins. In order to enable the dimming feature, the pins need to be configured in PWM mode and synced with channels of the `TPM` (Timer PWM Module). To enable -this feature, compile the application with: `chip_config_dimmable_led=true` +this feature, compile the application with: `nxp_config_dimmable_led=true` If the feature is enabled, the LED brightness can be controlled using `LevelControl` cluster diff --git a/examples/lighting-app/nxp/k32w1/args.gni b/examples/lighting-app/nxp/k32w1/args.gni index 5c854bc1c3c187..3d026f1fb48e9d 100644 --- a/examples/lighting-app/nxp/k32w1/args.gni +++ b/examples/lighting-app/nxp/k32w1/args.gni @@ -19,7 +19,7 @@ import("${chip_root}/config/standalone/args.gni") nxp_sdk_target = get_label_info(":sdk", "label_no_toolchain") nxp_device = "K32W1480" -chip_config_dimmable_led = false +nxp_config_dimmable_led = false chip_enable_ota_requestor = true chip_stack_lock_tracking = "fatal" chip_enable_ble = true @@ -29,11 +29,11 @@ is_debug = false chip_crypto = "platform" chip_openthread_ftd = true -chip_with_ot_cli = 0 +nxp_enable_ot_cli = false chip_system_config_provide_statistics = false chip_system_config_use_open_thread_inet_endpoints = true chip_with_lwip = false -use_smu2_static = true -use_smu2_dynamic = true +nxp_use_smu2_static = true +nxp_use_smu2_dynamic = true diff --git a/examples/lighting-app/nxp/k32w1/with_pw_rpc.gni b/examples/lighting-app/nxp/k32w1/with_pw_rpc.gni index c2dc1950544640..2afd19aeef800a 100644 --- a/examples/lighting-app/nxp/k32w1/with_pw_rpc.gni +++ b/examples/lighting-app/nxp/k32w1/with_pw_rpc.gni @@ -31,7 +31,7 @@ chip_system_config_provide_statistics = false chip_system_config_use_open_thread_inet_endpoints = true chip_with_lwip = false -chip_with_ot_cli = 0 +nxp_enable_ot_cli = false cpp_standard = "gnu++17" is_debug = false diff --git a/examples/lighting-app/nxp/mcxw71/BUILD.gn b/examples/lighting-app/nxp/mcxw71/BUILD.gn index f7e9c42b6e752c..8ee1b50b361ea4 100644 --- a/examples/lighting-app/nxp/mcxw71/BUILD.gn +++ b/examples/lighting-app/nxp/mcxw71/BUILD.gn @@ -101,7 +101,7 @@ mcxw71_k32w1_sdk("sdk") { "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setup_discriminator}", ] - if (chip_key_storage == "littlefs") { + if (nxp_nvm_component == "littlefs") { include_dirs += [ "${example_platform_dir}/board" ] sources += [ "${example_platform_dir}/board/peripherals.c", @@ -198,7 +198,7 @@ mcxw71_k32w1_executable("light_app") { sources += [ "${example_platform_dir}/rpc/AppRpc.cpp" ] } - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { include_dirs += [ "${chip_root}/src/platform/nxp/common/factory_data/legacy" ] deps += [ "${chip_root}/src/platform/nxp:nxp_factory_data" ] @@ -221,7 +221,7 @@ mcxw71_k32w1_executable("light_app") { "${chip_root}/src/platform/logging:default", ] - if (chip_config_dimmable_led) { + if (nxp_config_dimmable_led) { defines += [ "LIGHTING_MANAGER_ENABLE_DIMMABLE_LED=1" ] sources += [ "${common_example_dir}/led_widget/include/LedDimmer.h", @@ -249,7 +249,7 @@ mcxw71_k32w1_executable("light_app") { ] } - if (use_smu2_static) { + if (nxp_use_smu2_static) { ldscript = "${example_platform_dir}/app/ldscripts/app.ld" base_ldscript_dir = "${nxp_sdk_root}/middleware/wireless/framework/Common/devices/kw45_k32w1/gcc" } else { @@ -266,11 +266,11 @@ mcxw71_k32w1_executable("light_app") { "-T" + rebase_path(ldscript, root_build_dir), ] - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { ldflags += [ "-Wl,--defsym=gUseFactoryData_d=1" ] } - if (use_smu2_static) { + if (nxp_use_smu2_static) { ldflags += [ "-L" + rebase_path(base_ldscript_dir, root_build_dir) ] } diff --git a/examples/lighting-app/nxp/mcxw71/README.md b/examples/lighting-app/nxp/mcxw71/README.md index 3cded8b8be9230..c9c4007485889b 100644 --- a/examples/lighting-app/nxp/mcxw71/README.md +++ b/examples/lighting-app/nxp/mcxw71/README.md @@ -83,8 +83,8 @@ if changed, the names must be updated in `app.ld`. See `SMU2` memory range size. When compiling the application as an OT Full Thread Device -(`chip_openthread_ftd=true`), using `use_smu2_static=true` gn arg will cause the -following symbols to be moved to `SMU2` area: +(`chip_openthread_ftd=true`), using `nxp_use_smu2_static=true` gn arg will cause +the following symbols to be moved to `SMU2` area: | symbol name | file | | ----------------------------------- | ---------------------------- | @@ -93,19 +93,19 @@ following symbols to be moved to `SMU2` area: | `Server::sServer` | `Server.cpp` | | `ThreadStackManagerImpl::sInstance` | `ThreadStackManagerImpl.cpp` | -Additionally, using `use_smu2_dynamic=true` will cause the OpenThread buffers to -be dynamically allocated from a 13KB `SMU2` range after a successful +Additionally, using `nxp_use_smu2_dynamic=true` will cause the OpenThread +buffers to be dynamically allocated from a 13KB `SMU2` range after a successful commissioning process. -`use_smu2_static` and `use_smu2_dynamic` are set to `true` in the default -example. +`nxp_use_smu2_static` and `nxp_use_smu2_dynamic` are set to `true` in the +default example. ### LED PWM In the default configuration, the onboard RGB LED pins are configured as GPIO pins. In order to enable the dimming feature, the pins need to be configured in PWM mode and synced with channels of the `TPM` (Timer PWM Module). To enable -this feature, compile the application with: `chip_config_dimmable_led=true` +this feature, compile the application with: `nxp_config_dimmable_led=true` If the feature is enabled, the LED brightness can be controlled using `LevelControl` cluster diff --git a/examples/lighting-app/nxp/mcxw71/args.gni b/examples/lighting-app/nxp/mcxw71/args.gni index 6a27d6605ea2b8..6be04211091da2 100644 --- a/examples/lighting-app/nxp/mcxw71/args.gni +++ b/examples/lighting-app/nxp/mcxw71/args.gni @@ -19,7 +19,7 @@ import("${chip_root}/config/standalone/args.gni") nxp_sdk_target = get_label_info(":sdk", "label_no_toolchain") nxp_device = "MCXW716C" -chip_config_dimmable_led = false +nxp_config_dimmable_led = false chip_enable_ota_requestor = true chip_stack_lock_tracking = "fatal" chip_enable_ble = true @@ -29,11 +29,11 @@ is_debug = false chip_crypto = "platform" chip_openthread_ftd = true -chip_with_ot_cli = 0 +nxp_enable_ot_cli = false chip_system_config_provide_statistics = false chip_system_config_use_open_thread_inet_endpoints = true chip_with_lwip = false -use_smu2_static = true -use_smu2_dynamic = true +nxp_use_smu2_static = true +nxp_use_smu2_dynamic = true diff --git a/examples/lighting-app/nxp/mcxw71/with_pw_rpc.gni b/examples/lighting-app/nxp/mcxw71/with_pw_rpc.gni index c2dc1950544640..2afd19aeef800a 100644 --- a/examples/lighting-app/nxp/mcxw71/with_pw_rpc.gni +++ b/examples/lighting-app/nxp/mcxw71/with_pw_rpc.gni @@ -31,7 +31,7 @@ chip_system_config_provide_statistics = false chip_system_config_use_open_thread_inet_endpoints = true chip_with_lwip = false -chip_with_ot_cli = 0 +nxp_enable_ot_cli = false cpp_standard = "gnu++17" is_debug = false diff --git a/examples/lock-app/nxp/README.md b/examples/lock-app/nxp/README.md index a758ef50d7a348..9bbd88a17ed439 100644 --- a/examples/lock-app/nxp/README.md +++ b/examples/lock-app/nxp/README.md @@ -123,7 +123,7 @@ corresponding to data model target. ### Manufacturing data -Use `chip_with_factory_data=1` in the gn build command to enable factory data. +Use `nxp_use_factory_data=true` in the gn build command to enable factory data. For a full guide on manufacturing flow, please see [Guide for writing manufacturing data on NXP devices](../../../docs/platforms/nxp/nxp_manufacturing_flow.md). diff --git a/examples/lock-app/nxp/k32w1/BUILD.gn b/examples/lock-app/nxp/k32w1/BUILD.gn index c10cc05475ffee..d54a69400bfbf4 100644 --- a/examples/lock-app/nxp/k32w1/BUILD.gn +++ b/examples/lock-app/nxp/k32w1/BUILD.gn @@ -85,7 +85,7 @@ mcxw71_k32w1_sdk("sdk") { "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setup_discriminator}", ] - if (chip_key_storage == "littlefs") { + if (nxp_nvm_component == "littlefs") { include_dirs += [ "${example_platform_dir}/board" ] sources += [ "${example_platform_dir}/board/peripherals.c", @@ -124,7 +124,7 @@ mcxw71_k32w1_executable("lock_app") { defines += [ "CONFIG_DIAG_LOGS_DEMO=1" ] } - if (chip_with_low_power == 1) { + if (nxp_use_low_power) { defines += [ "CONFIG_LOW_POWER=1" ] } else { defines += [ @@ -168,17 +168,17 @@ mcxw71_k32w1_executable("lock_app") { "${example_platform_dir}/factory_data/source/AppFactoryDataExample.cpp", ] - if (chip_with_low_power == 1) { + if (nxp_use_low_power) { sources += [ "${common_example_dir}/low_power/source/LowPower.cpp" ] } - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { include_dirs += [ "${chip_root}/src/platform/nxp/common/factory_data/legacy" ] deps += [ "${chip_root}/src/platform/nxp:nxp_factory_data" ] } - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "ENABLE_CHIP_SHELL" ] deps += [ "${chip_root}/examples/shell/shell_common:shell_common", @@ -248,7 +248,7 @@ mcxw71_k32w1_executable("lock_app") { "../common/main/main.cpp", ] - if (chip_with_low_power == 0) { + if (!nxp_use_low_power) { sources += [ "${common_example_dir}/ui_feedback/source/LedManager.cpp", "${example_platform_dir}/util/LedOnOff.cpp", @@ -291,7 +291,7 @@ mcxw71_k32w1_executable("lock_app") { "-T" + rebase_path(ldscript, root_build_dir), ] - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { ldflags += [ "-Wl,--defsym=gUseFactoryData_d=1" ] } diff --git a/examples/lock-app/nxp/k32w1/args.gni b/examples/lock-app/nxp/k32w1/args.gni index b7a2d790efb3e2..bf46484106ef35 100644 --- a/examples/lock-app/nxp/k32w1/args.gni +++ b/examples/lock-app/nxp/k32w1/args.gni @@ -37,8 +37,8 @@ is_debug = false chip_crypto = "platform" chip_openthread_ftd = false -chip_with_ot_cli = 0 -chip_enable_matter_cli = true +nxp_enable_ot_cli = false +nxp_enable_matter_cli = true chip_with_diag_logs_demo = true -chip_with_low_power = 0 +nxp_use_low_power = false diff --git a/examples/lock-app/nxp/mcxw71/BUILD.gn b/examples/lock-app/nxp/mcxw71/BUILD.gn index 0c34d3d8083a20..57328e2da8f8af 100644 --- a/examples/lock-app/nxp/mcxw71/BUILD.gn +++ b/examples/lock-app/nxp/mcxw71/BUILD.gn @@ -85,7 +85,7 @@ mcxw71_k32w1_sdk("sdk") { "CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR=${setup_discriminator}", ] - if (chip_key_storage == "littlefs") { + if (nxp_nvm_component == "littlefs") { include_dirs += [ "${example_platform_dir}/board" ] sources += [ "${example_platform_dir}/board/peripherals.c", @@ -124,7 +124,7 @@ mcxw71_k32w1_executable("lock_app") { defines += [ "CONFIG_DIAG_LOGS_DEMO=1" ] } - if (chip_with_low_power == 1) { + if (nxp_use_low_power) { defines += [ "CONFIG_LOW_POWER=1" ] } else { defines += [ @@ -168,17 +168,17 @@ mcxw71_k32w1_executable("lock_app") { "${example_platform_dir}/factory_data/source/AppFactoryDataExample.cpp", ] - if (chip_with_low_power == 1) { + if (nxp_use_low_power) { sources += [ "${common_example_dir}/low_power/source/LowPower.cpp" ] } - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { include_dirs += [ "${chip_root}/src/platform/nxp/common/factory_data/legacy" ] deps += [ "${chip_root}/src/platform/nxp:nxp_factory_data" ] } - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "ENABLE_CHIP_SHELL" ] deps += [ "${chip_root}/examples/shell/shell_common:shell_common", @@ -248,7 +248,7 @@ mcxw71_k32w1_executable("lock_app") { "../common/main/main.cpp", ] - if (chip_with_low_power == 0) { + if (!nxp_use_low_power) { sources += [ "${common_example_dir}/ui_feedback/source/LedManager.cpp", "${example_platform_dir}/util/LedOnOff.cpp", @@ -291,7 +291,7 @@ mcxw71_k32w1_executable("lock_app") { "-T" + rebase_path(ldscript, root_build_dir), ] - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { ldflags += [ "-Wl,--defsym=gUseFactoryData_d=1" ] } diff --git a/examples/lock-app/nxp/mcxw71/args.gni b/examples/lock-app/nxp/mcxw71/args.gni index 1a0940c96aabdb..59a25dfb43d9c9 100644 --- a/examples/lock-app/nxp/mcxw71/args.gni +++ b/examples/lock-app/nxp/mcxw71/args.gni @@ -37,8 +37,8 @@ is_debug = false chip_crypto = "platform" chip_openthread_ftd = false -chip_with_ot_cli = 0 -chip_enable_matter_cli = true +nxp_enable_ot_cli = false +nxp_enable_matter_cli = true chip_with_diag_logs_demo = true -chip_with_low_power = 0 +nxp_use_low_power = false diff --git a/examples/platform/nxp/k32w0/doc/CustomFactoryDataProvider.md b/examples/platform/nxp/k32w0/doc/CustomFactoryDataProvider.md index 59347d6bfd205d..b609598132ea4c 100644 --- a/examples/platform/nxp/k32w0/doc/CustomFactoryDataProvider.md +++ b/examples/platform/nxp/k32w0/doc/CustomFactoryDataProvider.md @@ -19,13 +19,13 @@ What **shall** be done to enable usage of a custom factory provider in the reference app: - Set `use_custom_factory_provider=1`. This option is only available when - factory data is used (`chip_with_factory_data=1`). An assert will be raised + factory data is used (`nxp_use_factory_data=true`). An assert will be raised if the condition is not met. - Modify the `BUILD.gn` of the application to take into account the new files where the custom factory provider is implemented: ``` - if (chip_with_factory_data == 1 && use_custom_factory_provider == 1) + if (nxp_use_factory_data && use_custom_factory_provider == 1) { sources += [ "${k32w0_platform_dir}/common/CustomFactoryDataProvider.h", diff --git a/examples/platform/nxp/mcxw71_k32w1/app/project_include/freeRTOS/FreeRTOSConfig.h b/examples/platform/nxp/mcxw71_k32w1/app/project_include/freeRTOS/FreeRTOSConfig.h index 286566a027b6f9..b834ea38b834f1 100644 --- a/examples/platform/nxp/mcxw71_k32w1/app/project_include/freeRTOS/FreeRTOSConfig.h +++ b/examples/platform/nxp/mcxw71_k32w1/app/project_include/freeRTOS/FreeRTOSConfig.h @@ -48,7 +48,7 @@ extern uint32_t SystemCoreClock; #define configUSE_PREEMPTION 1 -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) #define configUSE_TICKLESS_IDLE 1 #else #define configUSE_TICKLESS_IDLE 0 diff --git a/examples/platform/nxp/mcxw71_k32w1/app/support/BUILD.gn b/examples/platform/nxp/mcxw71_k32w1/app/support/BUILD.gn index 96d05e9ba29f13..d49e9e7638c817 100644 --- a/examples/platform/nxp/mcxw71_k32w1/app/support/BUILD.gn +++ b/examples/platform/nxp/mcxw71_k32w1/app/support/BUILD.gn @@ -17,8 +17,6 @@ import("//build_overrides/nxp_sdk.gni") import("${nxp_sdk_matter_support_root}/gn_build/nxp_sdk.gni") -import("${chip_root}/src/platform/nxp/${nxp_platform}/args.gni") - config("support_config") { include_dirs = [ "${chip_root}" ] @@ -53,9 +51,9 @@ source_set("freertos_memory_utils") { cflags = [ "-Wconversion" ] - if (chip_key_storage == "fwk_nvm") { + if (nxp_nvm_component == "fwk_nvm") { defines = [ "CHIP_PLAT_NVM_SUPPORT=1" ] - } else if (chip_key_storage == "littlefs") { + } else if (nxp_nvm_component == "littlefs") { defines = [ "CHIP_PLAT_NVM_SUPPORT=3" ] } diff --git a/examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.c b/examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.c index 72d5f1acc6161e..bc5acf2e88401b 100644 --- a/examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.c +++ b/examples/platform/nxp/mcxw71_k32w1/app/support/FreeRtosHooks.c @@ -134,8 +134,6 @@ void vPortSuppressTicksAndSleep(TickType_t xExpectedIdleTime) } #endif -extern void OTAIdleActivities(void); - void vApplicationIdleHook(void) { // Data queued by PDM will be written to external flash @@ -150,5 +148,8 @@ void vApplicationIdleHook(void) #endif OSA_InterruptEnable(); +#if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR + extern void OTAIdleActivities(void); OTAIdleActivities(); +#endif } diff --git a/examples/thermostat/nxp/rt/rt1060/BUILD.gn b/examples/thermostat/nxp/rt/rt1060/BUILD.gn index 5eba1a328f799f..e57cc01b92b47b 100644 --- a/examples/thermostat/nxp/rt/rt1060/BUILD.gn +++ b/examples/thermostat/nxp/rt/rt1060/BUILD.gn @@ -183,7 +183,7 @@ rt_executable("thermostat") { deps = [ "${chip_root}/examples/${app_common_folder}" ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "ENABLE_CHIP_SHELL" ] deps += [ "${chip_root}/examples/shell/shell_common:shell_common", diff --git a/examples/thermostat/nxp/rt/rt1170/BUILD.gn b/examples/thermostat/nxp/rt/rt1170/BUILD.gn index c89df14eb5fc01..abb7090f962559 100644 --- a/examples/thermostat/nxp/rt/rt1170/BUILD.gn +++ b/examples/thermostat/nxp/rt/rt1170/BUILD.gn @@ -169,7 +169,7 @@ rt_executable("thermostat") { deps = [ "${chip_root}/examples/${app_common_folder}" ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "ENABLE_CHIP_SHELL" ] deps += [ "${chip_root}/examples/shell/shell_common:shell_common", diff --git a/examples/thermostat/nxp/rt/rw61x/BUILD.gn b/examples/thermostat/nxp/rt/rw61x/BUILD.gn index 3e46391d30f8a8..ec0a6d4f0ec379 100644 --- a/examples/thermostat/nxp/rt/rw61x/BUILD.gn +++ b/examples/thermostat/nxp/rt/rw61x/BUILD.gn @@ -59,8 +59,8 @@ rt_sdk("sdk") { defines = [] # To be moved, temporary mbedtls config fix to build app with factory data - if (chip_enable_secure_dac_private_key_storage || - chip_enable_secure_whole_factory_data) { + if (nxp_enable_secure_dac_private_key_storage || + nxp_enable_secure_whole_factory_data) { defines += [ "MBEDTLS_NIST_KW_C", "MBEDTLS_PSA_CRYPTO_CLIENT", @@ -165,10 +165,10 @@ rt_executable("thermostat") { ] } - if (chip_enable_secure_dac_private_key_storage || - chip_enable_secure_whole_factory_data) { + if (nxp_enable_secure_dac_private_key_storage || + nxp_enable_secure_whole_factory_data) { sources += [ "${chip_root}/examples/platform/nxp/${nxp_platform}/factory_data/source/AppFactoryDataExample.cpp" ] - if (chip_enable_secure_whole_factory_data) { + if (nxp_enable_secure_whole_factory_data) { defines += [ "ENABLE_SECURE_WHOLE_FACTORY_DATA" ] } } else { @@ -202,7 +202,7 @@ rt_executable("thermostat") { "${chip_root}/src/platform/logging:default", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "ENABLE_CHIP_SHELL" ] deps += [ "${chip_root}/examples/shell/shell_common:shell_common", diff --git a/scripts/build/builders/nxp.py b/scripts/build/builders/nxp.py index 91155f20c96f7b..0f9ebed42ad18b 100644 --- a/scripts/build/builders/nxp.py +++ b/scripts/build/builders/nxp.py @@ -236,18 +236,18 @@ def GnBuildArgs(self): args = [] if self.low_power: - args.append('chip_with_low_power=1') + args.append('nxp_use_low_power=true') if self.board == NxpBoard.K32W0: args.append('chip_pw_tokenizer_logging=false chip_with_OM15082=0') if self.smu2: - args.append('use_smu2_static=true use_smu2_dynamic=true') + args.append('nxp_use_smu2_static=true nxp_use_smu2_dynamic=true') if self.enable_factory_data: - args.append('chip_with_factory_data=1') + args.append('nxp_use_factory_data=true') if self.convert_dac_pk: - args.append('chip_convert_dac_private_key=1') + args.append('nxp_convert_dac_private_key=true') if self.use_fro32k: args.append('use_fro_32k=1') @@ -298,7 +298,7 @@ def GnBuildArgs(self): args.append('chip_enable_ble=false') if self.enable_shell: - args.append('chip_enable_matter_cli=true') + args.append('nxp_enable_matter_cli=true') if self.enable_thread: # thread is enabled by default on kw32 diff --git a/src/platform/nxp/common/ble/BLEManagerCommon.cpp b/src/platform/nxp/common/ble/BLEManagerCommon.cpp index 6078fa80acb715..e970dab55cc232 100644 --- a/src/platform/nxp/common/ble/BLEManagerCommon.cpp +++ b/src/platform/nxp/common/ble/BLEManagerCommon.cpp @@ -40,7 +40,7 @@ #include "stdio.h" #include "timers.h" -#if defined(CPU_JN518X) && defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(CPU_JN518X) && defined(nxp_use_low_power) && (nxp_use_low_power == 1) #include "PWR_Configuration.h" #endif @@ -54,7 +54,7 @@ *******************************************************************************/ extern "C" bool_t Ble_ConfigureHostStackConfig(void); -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) extern "C" void PWR_DisallowDeviceToSleep(void); extern "C" void PWR_AllowDeviceToSleep(void); #endif @@ -127,7 +127,7 @@ TimerHandle_t connectionTimeout; const uint8_t ShortUUID_CHIPoBLEService[] = { 0xF6, 0xFF }; -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) static bool bleAppStopInProgress; #endif @@ -192,7 +192,7 @@ CHIP_ERROR BLEManagerCommon::_Init() VerifyOrExit(eventBits & CHIP_BLE_KW_EVNT_POWER_LEVEL_SET, err = CHIP_ERROR_INCORRECT_STATE); #endif -#if defined(CPU_JN518X) && defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(CPU_JN518X) && defined(nxp_use_low_power) && (nxp_use_low_power == 1) PWR_ChangeDeepSleepMode(cPWR_PowerDown_RamRet); #endif @@ -516,7 +516,7 @@ BLEManagerCommon::ble_err_t BLEManagerCommon::blekw_start_advertising(gapAdverti return BLE_E_START_ADV; } -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) PWR_DisallowDeviceToSleep(); #endif @@ -524,13 +524,13 @@ BLEManagerCommon::ble_err_t BLEManagerCommon::blekw_start_advertising(gapAdverti CHIP_BLE_KW_EVNT_TIMEOUT); if (!(eventBits & CHIP_BLE_KW_EVNT_ADV_CHANGED)) { -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) PWR_AllowDeviceToSleep(); #endif return BLE_E_START_ADV_FAILED; } -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) PWR_AllowDeviceToSleep(); #endif @@ -927,7 +927,7 @@ void BLEManagerCommon::HandleConnectEvent(blekw_msg_t * msg) uint8_t deviceId = msg->data.u8; ChipLogProgress(DeviceLayer, "BLE is connected with device: %d.\n", deviceId); -#if gClkUseFro32K && defined(chip_with_low_power) && (chip_with_low_power == 1) +#if gClkUseFro32K && defined(nxp_use_low_power) && (nxp_use_low_power == 1) PWR_DisallowDeviceToSleep(); #endif @@ -950,7 +950,7 @@ void BLEManagerCommon::HandleConnectionCloseEvent(blekw_msg_t * msg) uint8_t deviceId = msg->data.u8; ChipLogProgress(DeviceLayer, "BLE is disconnected with device: %d.\n", deviceId); -#if gClkUseFro32K && defined(chip_with_low_power) && (chip_with_low_power == 1) +#if gClkUseFro32K && defined(nxp_use_low_power) && (nxp_use_low_power == 1) PWR_AllowDeviceToSleep(); #endif @@ -1088,7 +1088,7 @@ void BLEManagerCommon::HandleForceDisconnect() } } -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) PWR_AllowDeviceToSleep(); #endif } @@ -1191,7 +1191,7 @@ void BLEManagerCommon::blekw_gap_connection_cb(deviceId_t deviceId, gapConnectio if (pConnectionEvent->eventType == gConnEvtConnected_c) { #if CHIP_DEVICE_K32W1 -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) /* Disallow must be called here for K32W1, otherwise an assert will be reached. * Disclaimer: this is a workaround until a better cross platform solution is found. */ PWR_DisallowDeviceToSleep(); @@ -1207,7 +1207,7 @@ void BLEManagerCommon::blekw_gap_connection_cb(deviceId_t deviceId, gapConnectio /* Notify App Task that the BLE is connected now */ (void) blekw_msg_add_u8(BLE_KW_MSG_CONNECTED, (uint8_t) deviceId); -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) PWR_AllowDeviceToSleep(); #endif } @@ -1218,7 +1218,7 @@ void BLEManagerCommon::blekw_gap_connection_cb(deviceId_t deviceId, gapConnectio /* Notify App Task that the BLE is disconnected now */ (void) blekw_msg_add_u8(BLE_KW_MSG_DISCONNECTED, (uint8_t) deviceId); -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) if (bleAppStopInProgress == TRUE) { bleAppStopInProgress = FALSE; @@ -1454,7 +1454,7 @@ CHIP_ERROR BLEManagerCommon::blekw_stop_connection_internal(BLE_CONNECTION_OBJEC ChipLogProgress(DeviceLayer, "Gap_Disconnect() failed."); return CHIP_ERROR_INTERNAL; } -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) else { bleAppStopInProgress = TRUE; diff --git a/src/platform/nxp/k32w0/BLEManagerImpl.cpp b/src/platform/nxp/k32w0/BLEManagerImpl.cpp index aa56e06a8d5598..8dc8c45bc2cd4d 100644 --- a/src/platform/nxp/k32w0/BLEManagerImpl.cpp +++ b/src/platform/nxp/k32w0/BLEManagerImpl.cpp @@ -19,7 +19,7 @@ /* this file behaves like a config.h, comes first */ #include -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) #include "PWR_Configuration.h" #include "PWR_Interface.h" #endif @@ -79,7 +79,7 @@ CHIP_ERROR BLEManagerImpl::InitHostController(BLECallbackDelegate::GapGenericCal /* Called by BLE when a connect is received */ void BLEManagerImpl::BLE_SignalFromISRCallback(void) { -#if defined(chip_with_low_power) +#if defined(nxp_use_low_power) PWR_DisallowDeviceToSleep(); #endif } diff --git a/src/platform/nxp/k32w0/BUILD.gn b/src/platform/nxp/k32w0/BUILD.gn index 6693acc213e4a1..c7a1c94ddba441 100644 --- a/src/platform/nxp/k32w0/BUILD.gn +++ b/src/platform/nxp/k32w0/BUILD.gn @@ -67,7 +67,7 @@ static_library("nxp_platform") { "${chip_root}/src/platform/nxp/k32w0/BLEManagerImpl.h", ] - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { sources += [ "FactoryDataProvider.cpp", "FactoryDataProviderImpl.cpp", @@ -78,7 +78,7 @@ static_library("nxp_platform") { ] } - if (chip_with_low_power != 0) { + if (nxp_use_low_power) { sources += [ "LowPowerHooks.cpp" ] } @@ -92,15 +92,14 @@ static_library("nxp_platform") { "../common/ota/OTATlvProcessor.h", ] - if (chip_enable_ota_firmware_processor == 1) { + if (nxp_enable_ota_firmware_processor) { sources += [ "OTAFirmwareProcessor.cpp", "OTAFirmwareProcessor.h", "OTAHooks.cpp", ] - if (chip_with_factory_data == 1 && - chip_enable_ota_factory_data_processor == 1) { + if (nxp_use_factory_data && nxp_enable_ota_factory_data_processor) { sources += [ "OTAFactoryDataProcessor.cpp", "OTAFactoryDataProcessor.h", diff --git a/src/platform/nxp/k32w0/LowPowerHooks.cpp b/src/platform/nxp/k32w0/LowPowerHooks.cpp index b01854c964296d..55c05733d2ef29 100644 --- a/src/platform/nxp/k32w0/LowPowerHooks.cpp +++ b/src/platform/nxp/k32w0/LowPowerHooks.cpp @@ -20,7 +20,7 @@ * Provides a glue layer between Matter and NXP-SDK Low Power */ -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) #include #include diff --git a/src/platform/nxp/k32w0/PlatformManagerImpl.cpp b/src/platform/nxp/k32w0/PlatformManagerImpl.cpp index 1a98552cb7e0d9..b79de9635abd01 100644 --- a/src/platform/nxp/k32w0/PlatformManagerImpl.cpp +++ b/src/platform/nxp/k32w0/PlatformManagerImpl.cpp @@ -56,7 +56,7 @@ namespace DeviceLayer { PlatformManagerImpl PlatformManagerImpl::sInstance; -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) extern "C" void InitLowPower(); #endif @@ -97,7 +97,7 @@ CHIP_ERROR PlatformManagerImpl::InitBoardFwk(void) BOARD_ADCWakeupInit(); #endif -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) /* Low Power Init */ InitLowPower(); #endif diff --git a/src/platform/nxp/k32w0/ThreadStackManagerImpl.cpp b/src/platform/nxp/k32w0/ThreadStackManagerImpl.cpp index c74c2a9af4d907..36c27a15160617 100644 --- a/src/platform/nxp/k32w0/ThreadStackManagerImpl.cpp +++ b/src/platform/nxp/k32w0/ThreadStackManagerImpl.cpp @@ -36,7 +36,7 @@ #include -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) extern "C" bool isThreadInitialized(); #endif @@ -75,7 +75,7 @@ void ThreadStackManagerImpl::ProcessThreadActivity() auto * bleManager = &chip::DeviceLayer::Internal::BLEMgrImpl(); bleManager->DoBleProcessing(); -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) if (isThreadInitialized()) #endif { diff --git a/src/platform/nxp/mcxw71_k32w1/BUILD.gn b/src/platform/nxp/mcxw71_k32w1/BUILD.gn index 6b399a1c1dbf27..9de3c0e5b3c7e0 100644 --- a/src/platform/nxp/mcxw71_k32w1/BUILD.gn +++ b/src/platform/nxp/mcxw71_k32w1/BUILD.gn @@ -26,8 +26,7 @@ import("${nxp_sdk_build_root}/${nxp_sdk_name}/${nxp_sdk_name}.gni") assert(chip_device_platform == "nxp") assert(nxp_platform == "mcxw71_k32w1") -assert(chip_with_low_power == 0 || - (chip_with_low_power == 1 && chip_with_ot_cli == 0), +assert(!nxp_use_low_power || (nxp_use_low_power && !nxp_enable_ot_cli), "Please disable low power if openthread CLI is needed!") source_set("nxp_factory_data") { @@ -64,8 +63,7 @@ source_set("nxp_ota") { "../common/ota/OTATlvProcessor.h", ] - if (chip_with_factory_data == 1 && - chip_enable_ota_factory_data_processor == 1) { + if (nxp_use_factory_data && nxp_enable_ota_factory_data_processor) { sources += [ "../common/ota/OTAFactoryDataProcessor.cpp", "../common/ota/OTAFactoryDataProcessor.h", @@ -114,7 +112,7 @@ static_library("nxp_platform") { "SystemTimeSupport.cpp", ] - if (chip_key_storage == "fwk_nvm") { + if (nxp_nvm_component == "fwk_nvm") { defines += [ "CHIP_PLAT_NVM_SUPPORT=1" ] sources += [ @@ -125,7 +123,7 @@ static_library("nxp_platform") { "ram_storage.c", "ram_storage.h", ] - } else if (chip_key_storage == "littlefs") { + } else if (nxp_nvm_component == "littlefs") { defines += [ "CHIP_PLAT_NVM_SUPPORT=3", "EXTERNAL_KEYVALUESTOREMANAGERIMPL_HEADER=\"platform/nxp/common/KeyValueStoreManagerImpl.h\"", @@ -137,7 +135,7 @@ static_library("nxp_platform") { "../common/NXPConfig.h", "../common/NXPConfigKS.cpp", ] - } else if (chip_key_storage == "nvs") { + } else if (nxp_nvm_component == "nvs") { defines += [ "gAppNvsExternalFlash_c=0", "gAppNvsInternalFlash_c=1", @@ -152,7 +150,7 @@ static_library("nxp_platform") { ] } - if (chip_use_plain_dac_key) { + if (nxp_use_plain_dac_key) { defines += [ "CHIP_USE_PLAIN_DAC_KEY=1" ] } else { defines += [ "CHIP_USE_PLAIN_DAC_KEY=0" ] @@ -170,7 +168,7 @@ static_library("nxp_platform") { public_deps = [ "${chip_root}/src/platform:platform_base" ] - if (chip_with_low_power != 0) { + if (nxp_use_low_power) { sources += [ "LowPowerHooks.cpp" ] } @@ -181,7 +179,7 @@ static_library("nxp_platform") { "../common/crypto/PersistentStorageOpKeystoreS200.h", ] - if (chip_with_ot_cli == 1) { + if (nxp_enable_ot_cli) { defines += [ "CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI=1" ] } } @@ -205,7 +203,7 @@ static_library("nxp_platform") { deps += [ "${chip_root}/src/lib/dnssd:platform_header" ] } - if (use_smu2_dynamic) { + if (nxp_use_smu2_dynamic) { sources += [ "SMU2Manager.cpp", "SMU2Manager.h", diff --git a/src/platform/nxp/mcxw71_k32w1/LowPowerHooks.cpp b/src/platform/nxp/mcxw71_k32w1/LowPowerHooks.cpp index bc849b476e57af..acec00b4adf52e 100644 --- a/src/platform/nxp/mcxw71_k32w1/LowPowerHooks.cpp +++ b/src/platform/nxp/mcxw71_k32w1/LowPowerHooks.cpp @@ -20,7 +20,7 @@ * Provides a glue layer between Matter and NXP-SDK Low Power */ -#if defined(chip_with_low_power) && (chip_with_low_power == 1) +#if defined(nxp_use_low_power) && (nxp_use_low_power == 1) #include #include diff --git a/src/platform/nxp/mcxw71_k32w1/args.gni b/src/platform/nxp/mcxw71_k32w1/args.gni index 68e1cdeeec672e..7ec8fdf3d56e57 100644 --- a/src/platform/nxp/mcxw71_k32w1/args.gni +++ b/src/platform/nxp/mcxw71_k32w1/args.gni @@ -16,22 +16,12 @@ import("//build_overrides/chip.gni") import("//build_overrides/nxp_sdk.gni") import("//build_overrides/openthread.gni") -declare_args() { - chip_with_ot_cli = 0 - chip_with_low_power = 0 - - # The key storage solution. Developers can select between "littlefs", "nvs" - # and the older "fwk_nvm". - chip_key_storage = "nvs" - - chip_use_plain_dac_key = false -} - openthread_root = "//third_party/connectedhomeip/third_party/openthread/ot-nxp/openthread" nxp_platform = "mcxw71_k32w1" nxp_sdk_name = "mcxw71_k32w1_sdk" nxp_device_layer = "nxp/${nxp_platform}" +nxp_nvm_component = "nvs" nxp_use_lwip = false # ARM architecture flags will be set based on NXP board. diff --git a/src/platform/nxp/rt/rt1060/BUILD.gn b/src/platform/nxp/rt/rt1060/BUILD.gn index 1e3d8f1e1e6ba9..36db65910322f7 100644 --- a/src/platform/nxp/rt/rt1060/BUILD.gn +++ b/src/platform/nxp/rt/rt1060/BUILD.gn @@ -38,7 +38,7 @@ config("nxp_platform_config") { ".", "../../common", ] - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { include_dirs += [ ".", "../../common/factory_data", @@ -165,7 +165,7 @@ static_library("nxp_platform") { } } - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { sources += [ "../../common/factory_data/FactoryDataProvider.cpp", "../../common/factory_data/FactoryDataProvider.h", diff --git a/src/platform/nxp/rt/rt1170/BUILD.gn b/src/platform/nxp/rt/rt1170/BUILD.gn index 4bfd1034a78f21..0017fc44eb32de 100644 --- a/src/platform/nxp/rt/rt1170/BUILD.gn +++ b/src/platform/nxp/rt/rt1170/BUILD.gn @@ -38,7 +38,7 @@ config("nxp_platform_config") { ".", "../../common", ] - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { include_dirs += [ ".", "../../common/factory_data", @@ -168,7 +168,7 @@ static_library("nxp_platform") { } } - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { sources += [ "../../common/factory_data/FactoryDataProvider.cpp", "../../common/factory_data/FactoryDataProvider.h", diff --git a/src/platform/nxp/rt/rw61x/BUILD.gn b/src/platform/nxp/rt/rw61x/BUILD.gn index 7ac204e92c55e9..13c2b3c2ffc591 100644 --- a/src/platform/nxp/rt/rw61x/BUILD.gn +++ b/src/platform/nxp/rt/rw61x/BUILD.gn @@ -42,7 +42,7 @@ config("nxp_platform_config") { ".", "../../common", ] - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { include_dirs += [ ".", "../../common/factory_data", @@ -52,14 +52,14 @@ config("nxp_platform_config") { "CONFIG_CHIP_ENCRYPTED_FACTORY_DATA=1", ] - if (chip_enable_secure_dac_private_key_storage) { - assert(chip_enable_secure_dac_private_key_storage && - !chip_enable_secure_whole_factory_data, + if (nxp_enable_secure_dac_private_key_storage) { + assert(nxp_enable_secure_dac_private_key_storage && + !nxp_enable_secure_whole_factory_data, "please select only one protection solution") defines += [ "EXTERNAL_FACTORY_DATA_PROVIDER_IMPL_HEADER=\"platform/nxp/rt/rw61x/FactoryDataProviderImpl.h\"" ] - } else if (chip_enable_secure_whole_factory_data) { - assert(chip_enable_secure_whole_factory_data && - !chip_enable_secure_dac_private_key_storage, + } else if (nxp_enable_secure_whole_factory_data) { + assert(nxp_enable_secure_whole_factory_data && + !nxp_enable_secure_dac_private_key_storage, "please select only one protection solution") defines += [ "EXTERNAL_FACTORY_DATA_PROVIDER_IMPL_HEADER=\"platform/nxp/rt/rw61x/FactoryDataProviderEncImpl.h\"" ] } else { @@ -196,17 +196,17 @@ static_library("nxp_platform") { } } - if (chip_with_factory_data == 1) { + if (nxp_use_factory_data) { sources += [ "../../common/factory_data/FactoryDataProvider.cpp", "../../common/factory_data/FactoryDataProvider.h", ] - if (chip_enable_secure_dac_private_key_storage) { + if (nxp_enable_secure_dac_private_key_storage) { sources += [ "FactoryDataProviderImpl.cpp", "FactoryDataProviderImpl.h", ] - } else if (chip_enable_secure_whole_factory_data) { + } else if (nxp_enable_secure_whole_factory_data) { sources += [ "FactoryDataProviderEncImpl.cpp", "FactoryDataProviderEncImpl.h", diff --git a/third_party/nxp/nxp_matter_support b/third_party/nxp/nxp_matter_support index 41e38b6593b687..69f40517ca5f27 160000 --- a/third_party/nxp/nxp_matter_support +++ b/third_party/nxp/nxp_matter_support @@ -1 +1 @@ -Subproject commit 41e38b6593b68741f2c107d3c5296bfea5b3c1c7 +Subproject commit 69f40517ca5f27fdf3026f695c0d0607b604dc0e diff --git a/third_party/openthread/platforms/nxp/k32w0/BUILD.gn b/third_party/openthread/platforms/nxp/k32w0/BUILD.gn index bf9ed42e894965..9725e59acff800 100644 --- a/third_party/openthread/platforms/nxp/k32w0/BUILD.gn +++ b/third_party/openthread/platforms/nxp/k32w0/BUILD.gn @@ -86,7 +86,7 @@ source_set("libopenthread-k32w0") { ] } - if (chip_with_ot_cli == 1) { + if (nxp_enable_ot_cli) { sources += [ "${openthread_root}/examples/apps/cli/cli_uart.cpp" ] } diff --git a/third_party/openthread/platforms/nxp/mcxw71_k32w1/BUILD.gn b/third_party/openthread/platforms/nxp/mcxw71_k32w1/BUILD.gn index b7dc6d35983c40..5d583fdd898bef 100644 --- a/third_party/openthread/platforms/nxp/mcxw71_k32w1/BUILD.gn +++ b/third_party/openthread/platforms/nxp/mcxw71_k32w1/BUILD.gn @@ -16,9 +16,10 @@ import("//build_overrides/chip.gni") import("//build_overrides/nxp_sdk.gni") import("//build_overrides/openthread.gni") -import("${nxp_sdk_build_root}/nxp_sdk.gni") +import("${chip_root}/src/crypto/crypto.gni") +import("${chip_root}/src/platform/device.gni") -import("${nxp_sdk_build_root}/${nxp_sdk_name}/${nxp_sdk_name}.gni") +import("${nxp_sdk_build_root}/nxp_sdk.gni") openthread_nxp_root = "${chip_root}/third_party/openthread/ot-nxp" @@ -42,16 +43,16 @@ config("openthread_k32w1_config") { ] } - if (use_smu2_dynamic) { + if (nxp_use_smu2_dynamic) { defines += [ "OPENTHREAD_CONFIG_MESSAGE_USE_HEAP_ENABLE=1", "OPENTHREAD_CONFIG_ENABLE_BUILTIN_MBEDTLS_MANAGEMENT=0", ] } - if (chip_key_storage == "littlefs") { + if (nxp_nvm_component == "littlefs") { defines += [ "OT_PLAT_SAVE_NVM_DATA_ON_IDLE=0" ] - } else if (chip_key_storage == "nvs") { + } else if (nxp_nvm_component == "nvs") { defines += [ "CONFIG_SETTINGS_RUNTIME=1" ] } } @@ -63,7 +64,9 @@ source_set("openthread_core_config_k32w1") { ] public_configs = [ ":openthread_k32w1_config" ] - public_deps = [ nxp_sdk_target ] + if (!nxp_external_sdk) { + public_deps = [ nxp_sdk_target ] + } } source_set("libopenthread-k32w1") { @@ -82,31 +85,36 @@ source_set("libopenthread-k32w1") { if (chip_crypto == "platform") { sources += [ "${openthread_nxp_root}/src/common/crypto/ecdsa_sss.cpp" ] - if (use_hw_sha256) { + if (nxp_use_hw_sha256) { sources += [ "${openthread_nxp_root}/src/common/crypto/sha256_sss.cpp" ] } - if (use_hw_aes) { + if (nxp_use_hw_aes) { sources += [ "${openthread_nxp_root}/src/common/crypto/aes_sss.cpp" ] } - if (chip_key_storage == "fwk_nvm") { + if (nxp_nvm_component == "fwk_nvm") { sources += [ "${openthread_nxp_root}/src/common/flash_nvm.c" ] - } else if (chip_key_storage == "littlefs") { + } else if (nxp_nvm_component == "littlefs") { sources += [ "${openthread_nxp_root}/src/common/flash_fsa.c" ] - } else if (chip_key_storage == "nvs") { + } else if (nxp_nvm_component == "nvs") { sources += [ "${openthread_nxp_root}/src/common/flash_nvs.c" ] } } - if (chip_with_ot_cli == 1) { + if (nxp_enable_ot_cli) { sources += [ "${openthread_root}/examples/apps/cli/cli_uart.cpp" ] } public_deps = [ - "${nxp_sdk_build_root}:nxp_mbedtls", "../..:libopenthread-platform", "../..:libopenthread-platform-utils", - nxp_sdk_target, ] + + if (!nxp_external_sdk) { + public_deps += [ + "${nxp_sdk_build_root}:nxp_mbedtls", + nxp_sdk_target, + ] + } } diff --git a/third_party/openthread/platforms/nxp/rt/rt1060/BUILD.gn b/third_party/openthread/platforms/nxp/rt/rt1060/BUILD.gn index ef44f9048e2d25..66640702f6d709 100644 --- a/third_party/openthread/platforms/nxp/rt/rt1060/BUILD.gn +++ b/third_party/openthread/platforms/nxp/rt/rt1060/BUILD.gn @@ -57,7 +57,7 @@ config("openthread_rt1060_config") { "OT_APP_BR_LWIP_HOOKS_EN=1", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "OPENTHREAD_CONFIG_BORDER_AGENT_EPHEMERAL_KEY_ENABLE=1", "OT_APP_CLI_EPHEMERAL_KEY_ADDON=1", @@ -103,7 +103,7 @@ source_set("libopenthread-rt1060") { "${openthread_nxp_root}/src/common/br/utils.c", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { sources += [ "${openthread_nxp_root}/examples/utils/cli_addons/addons_cli.c", "${openthread_nxp_root}/examples/utils/cli_addons/ephemeral_key/ephemeral_key_cli.c", diff --git a/third_party/openthread/platforms/nxp/rt/rt1170/BUILD.gn b/third_party/openthread/platforms/nxp/rt/rt1170/BUILD.gn index 039c911e51fa60..228f9e0814ec96 100644 --- a/third_party/openthread/platforms/nxp/rt/rt1170/BUILD.gn +++ b/third_party/openthread/platforms/nxp/rt/rt1170/BUILD.gn @@ -56,7 +56,7 @@ config("openthread_rt1170_config") { "OT_APP_BR_LWIP_HOOKS_EN=1", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "OPENTHREAD_CONFIG_BORDER_AGENT_EPHEMERAL_KEY_ENABLE=1", "OT_APP_CLI_EPHEMERAL_KEY_ADDON=1", @@ -101,7 +101,7 @@ source_set("libopenthread-rt1170") { "${openthread_nxp_root}/src/common/br/utils.c", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { sources += [ "${openthread_nxp_root}/examples/utils/cli_addons/addons_cli.c", "${openthread_nxp_root}/examples/utils/cli_addons/ephemeral_key/ephemeral_key_cli.c", diff --git a/third_party/openthread/platforms/nxp/rt/rw61x/BUILD.gn b/third_party/openthread/platforms/nxp/rt/rw61x/BUILD.gn index 6c00f94b3a077e..1dbfe5e5a5f2c6 100644 --- a/third_party/openthread/platforms/nxp/rt/rw61x/BUILD.gn +++ b/third_party/openthread/platforms/nxp/rt/rw61x/BUILD.gn @@ -59,7 +59,7 @@ config("openthread_rw61x_config") { "OT_APP_BR_LWIP_HOOKS_EN=1", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { defines += [ "OPENTHREAD_CONFIG_BORDER_AGENT_EPHEMERAL_KEY_ENABLE=1", "OT_APP_CLI_EPHEMERAL_KEY_ADDON=1", @@ -99,7 +99,7 @@ source_set("libopenthread-rw61x") { "${openthread_nxp_root}/src/common/br/utils.c", ] - if (chip_enable_matter_cli) { + if (nxp_enable_matter_cli) { sources += [ "${openthread_nxp_root}/examples/utils/cli_addons/addons_cli.c", "${openthread_nxp_root}/examples/utils/cli_addons/ephemeral_key/ephemeral_key_cli.c", From c0071eb67552cae7d12ef47b4f42f57e7b881b20 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Wed, 30 Oct 2024 17:58:33 +0100 Subject: [PATCH 014/121] [darwin-framework-tool] Add a command to initialize a MTRDevice such the the initial subscription is setted up without having to issue an additional command (e.g read or write) (#36287) --- .../commands/common/CHIPCommandBridge.h | 2 - .../commands/common/CHIPCommandBridge.mm | 5 -- .../commands/common/DeviceDelegate.h | 1 + .../commands/common/DeviceDelegate.mm | 12 +++ .../commands/configuration/Commands.h | 2 + .../configuration/SetUpDeviceCommand.h | 82 +++++++++++++++++++ 6 files changed, 97 insertions(+), 7 deletions(-) create mode 100644 examples/darwin-framework-tool/commands/configuration/SetUpDeviceCommand.h diff --git a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h index 2f53c0dd7bc4db..90f3a6c56415f6 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h +++ b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h @@ -52,7 +52,6 @@ class CHIPCommandBridge : public Command { AddArgument("commissioner-vendor-id", 0, UINT16_MAX, &mCommissionerVendorId, "The vendor id to use for darwin-framework-tool. If not provided, chip::VendorId::TestVendor1 (65521, 0xFFF1) will be " "used."); - AddArgument("pretend-thread-enabled", 0, 1, &mPretendThreadEnabled, "When the command is issued using an MTRDevice (via -use-mtr-device), instructs the MTRDevice to treat the target device as a Thread device."); } /////////// Command Interface ///////// @@ -165,5 +164,4 @@ class CHIPCommandBridge : public Command { chip::Optional mPaaTrustStorePath; chip::Optional mCommissionerVendorId; std::string mCurrentIdentity; - chip::Optional mPretendThreadEnabled; }; diff --git a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm index 2eba24c84ad44c..6472d2cae77f5e 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm +++ b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm @@ -306,14 +306,9 @@ VerifyOrReturnValue(nil != device, nil); // The device delegate is initialized only once, when the first MTRDevice is created. - // As a result, subsequent commands using --use-mtr-device don’t need to specify the - // `--pretend-thread-enabled 1` argument again. Any further attempts to set it to `0` will also be ignored. if (sDeviceDelegate == nil) { sDeviceDelegate = [[DeviceDelegate alloc] init]; sDeviceDelegateDispatchQueue = dispatch_queue_create("com.chip.devicedelegate", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - if (mPretendThreadEnabled.ValueOr(false)) { - [sDeviceDelegate setPretendThreadEnabled:YES]; - } } [device addDelegate:sDeviceDelegate queue:sDeviceDelegateDispatchQueue]; diff --git a/examples/darwin-framework-tool/commands/common/DeviceDelegate.h b/examples/darwin-framework-tool/commands/common/DeviceDelegate.h index a3f5cf427f191c..97ab5574295728 100644 --- a/examples/darwin-framework-tool/commands/common/DeviceDelegate.h +++ b/examples/darwin-framework-tool/commands/common/DeviceDelegate.h @@ -19,5 +19,6 @@ #import @interface DeviceDelegate : NSObject +- (void)setMaxIntervalForSubscription:(NSNumber *)maxInterval; - (void)setPretendThreadEnabled:(BOOL)threadEnabled; @end diff --git a/examples/darwin-framework-tool/commands/common/DeviceDelegate.mm b/examples/darwin-framework-tool/commands/common/DeviceDelegate.mm index ecf8e708e26ff3..1a7c82b46e631d 100644 --- a/examples/darwin-framework-tool/commands/common/DeviceDelegate.mm +++ b/examples/darwin-framework-tool/commands/common/DeviceDelegate.mm @@ -23,6 +23,7 @@ NS_ASSUME_NONNULL_BEGIN @interface DeviceDelegate () +@property (nonatomic, readwrite) NSNumber * maxIntervalForSubscription; @property (nonatomic, readwrite) BOOL threadEnabled; @end @@ -30,6 +31,7 @@ @implementation DeviceDelegate - (instancetype)init { if (self = [super init]) { + _maxIntervalForSubscription = nil; _threadEnabled = NO; } return self; @@ -55,6 +57,16 @@ - (void)deviceConfigurationChanged:(MTRDevice *)device { } +- (void)setMaxIntervalForSubscription:(NSNumber *)maxInterval +{ + _maxIntervalForSubscription = maxInterval; +} + +- (NSNumber *)unitTestMaxIntervalOverrideForSubscription:(MTRDevice *)device +{ + return _maxIntervalForSubscription; +} + - (void)setPretendThreadEnabled:(BOOL)threadEnabled { _threadEnabled = threadEnabled; diff --git a/examples/darwin-framework-tool/commands/configuration/Commands.h b/examples/darwin-framework-tool/commands/configuration/Commands.h index 8ee148e63b8f8b..1466f1fd93d9c3 100644 --- a/examples/darwin-framework-tool/commands/configuration/Commands.h +++ b/examples/darwin-framework-tool/commands/configuration/Commands.h @@ -22,12 +22,14 @@ #include "ResetMRPParametersCommand.h" #include "SetMRPParametersCommand.h" +#include "SetUpDeviceCommand.h" void registerCommandsConfiguration(Commands & commands) { const char * clusterName = "Configuration"; commands_list clusterCommands = { + make_unique(), make_unique(), make_unique(), }; diff --git a/examples/darwin-framework-tool/commands/configuration/SetUpDeviceCommand.h b/examples/darwin-framework-tool/commands/configuration/SetUpDeviceCommand.h new file mode 100644 index 00000000000000..8df842cf5769ae --- /dev/null +++ b/examples/darwin-framework-tool/commands/configuration/SetUpDeviceCommand.h @@ -0,0 +1,82 @@ +/* + * 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. + */ + +#pragma once + +#import "../common/DeviceDelegate.h" +#import + +#include + +class SetUpDeviceCommand : public CHIPCommandBridge { +public: + SetUpDeviceCommand() + : CHIPCommandBridge("device", "Creates and configures an instance of a device.") + { + AddArgument("node-id", 0, UINT64_MAX, &mNodeId, "The Node ID of the device instance to create."); + AddArgument("pretend-thread-enabled", 0, 1, &mPretendThreadEnabled, + "When the device is configured using an MTRDevice (via -use-mtr-device), instructs the MTRDevice to treat the " + "target device as a Thread device."); + AddArgument("max-interval", 0, UINT32_MAX, &mMaxIntervalForSubscription, + "When the device is configured using an MTRDevice (via --use-mtr-device), configure the maximum interval for the " + "delegate subscription."); + } + +protected: + /////////// CHIPCommandBridge Interface ///////// + CHIP_ERROR RunCommand() override + { + __auto_type * controller = CurrentCommissioner(); + VerifyOrReturnError(nil != controller, CHIP_ERROR_INCORRECT_STATE); + + __auto_type * device = [MTRDevice deviceWithNodeID:@(mNodeId) controller:controller]; + VerifyOrReturnError(nil != device, CHIP_ERROR_INCORRECT_STATE); + + __auto_type * delegate = ConfigureDelegate(); + __auto_type queue = dispatch_queue_create("com.chip.devicedelegate", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + [device addDelegate:delegate queue:queue]; + + mDelegate = delegate; + SetCommandExitStatus(CHIP_NO_ERROR); + return CHIP_NO_ERROR; + } + + // Our command is synchronous, so no need to wait. + chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::kZero; } + +private: + DeviceDelegate * ConfigureDelegate() + { + __auto_type * delegate = [[DeviceDelegate alloc] init]; + + if (mPretendThreadEnabled.ValueOr(false)) { + [delegate setPretendThreadEnabled:YES]; + } + + if (mMaxIntervalForSubscription.HasValue()) { + [delegate setMaxIntervalForSubscription:@(mMaxIntervalForSubscription.Value())]; + } + + return delegate; + } + + DeviceDelegate * mDelegate; + + chip::NodeId mNodeId; + chip::Optional mPretendThreadEnabled; + chip::Optional mMaxIntervalForSubscription; +}; From f985d72f6b6d81b66060e095e788209514d7a3a1 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Wed, 30 Oct 2024 19:28:15 +0100 Subject: [PATCH 015/121] [Matter.framework] Invalidate the CASE session if something calls TriggerResubscriptionWithReason and it has not been established yet (#36298) --- src/app/CASESessionManager.cpp | 6 ++++++ src/app/CASESessionManager.h | 1 + src/controller/CHIPDeviceController.h | 10 ++++++++++ .../Framework/CHIP/MTRDeviceController_Concrete.h | 6 ++++++ .../Framework/CHIP/MTRDeviceController_Concrete.mm | 11 +++++++++++ src/darwin/Framework/CHIP/MTRDevice_Concrete.mm | 6 ++++++ 6 files changed, 40 insertions(+) diff --git a/src/app/CASESessionManager.cpp b/src/app/CASESessionManager.cpp index 766e60115df829..42224215ae79d0 100644 --- a/src/app/CASESessionManager.cpp +++ b/src/app/CASESessionManager.cpp @@ -188,6 +188,12 @@ Optional CASESessionManager::FindExistingSession(const ScopedNode peerId, MakeOptional(Transport::SecureSession::Type::kCASE), transportPayloadCapability); } +void CASESessionManager::ReleaseSession(const ScopedNodeId & peerId) +{ + auto * session = mConfig.sessionSetupPool->FindSessionSetup(peerId, false); + ReleaseSession(session); +} + void CASESessionManager::ReleaseSession(OperationalSessionSetup * session) { if (session != nullptr) diff --git a/src/app/CASESessionManager.h b/src/app/CASESessionManager.h index e536a62cf80908..c6d0a8c56f3c02 100644 --- a/src/app/CASESessionManager.h +++ b/src/app/CASESessionManager.h @@ -142,6 +142,7 @@ class CASESessionManager : public OperationalSessionReleaseDelegate, public Sess #endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES TransportPayloadCapability transportPayloadCapability = TransportPayloadCapability::kMRPPayload); + void ReleaseSession(const ScopedNodeId & peerId); void ReleaseSessionsForFabric(FabricIndex fabricIndex); void ReleaseAllSessions(); diff --git a/src/controller/CHIPDeviceController.h b/src/controller/CHIPDeviceController.h index 2ec020340ee98d..05368564685bd3 100644 --- a/src/controller/CHIPDeviceController.h +++ b/src/controller/CHIPDeviceController.h @@ -204,6 +204,16 @@ class DLL_EXPORT DeviceController : public AbstractDnssdDiscoveryController return nullptr; } + CASESessionManager * CASESessionMgr() + { + if (mSystemState) + { + return mSystemState->CASESessionMgr(); + } + + return nullptr; + } + Messaging::ExchangeManager * ExchangeMgr() { if (mSystemState != nullptr) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h index 0cfb25f4944fc9..f9f1e9d19aa1fe 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h @@ -178,6 +178,12 @@ NS_ASSUME_NONNULL_BEGIN */ - (void)invalidateCASESessionForNode:(NSNumber *)nodeID; +/** + * Invalidate the CASE session establishment for the specified node ID. + * Must not be called on the Matter event queue. + */ +- (void)invalidateCASESessionEstablishmentForNode:(NSNumber *)nodeID; + /** * Download log of the desired type from the device. */ diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm index 1a164e50b14b5c..74e3437caf807f 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm @@ -1619,6 +1619,17 @@ - (void)invalidateCASESessionForNode:(NSNumber *)nodeID; [self syncRunOnWorkQueue:block error:nil]; } +- (void)invalidateCASESessionEstablishmentForNode:(NSNumber *)nodeID; +{ + auto block = ^{ + auto caseSessionMgr = self->_cppCommissioner->CASESessionMgr(); + VerifyOrDie(caseSessionMgr != nullptr); + caseSessionMgr->ReleaseSession(self->_cppCommissioner->GetPeerScopedId(nodeID.unsignedLongLongValue)); + }; + + [self syncRunOnWorkQueue:block error:nil]; +} + - (void)operationalInstanceAdded:(NSNumber *)nodeID { // Don't use deviceForNodeID here, because we don't want to create the diff --git a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm index a7b5d255f8772d..5668f61d0fd224 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm @@ -898,6 +898,12 @@ - (void)_triggerResubscribeWithReason:(NSString *)reason nodeLikelyReachable:(BO subscriptionCallback->ResetResubscriptionBackoff(); } readClientToResubscribe->TriggerResubscribeIfScheduled(reason.UTF8String); + } else if (_internalDeviceState == MTRInternalDeviceStateSubscribing && nodeLikelyReachable) { + // If we have reason to suspect that the node is now reachable and we haven’t established a + // CASE session yet, let’s consider it to be stalled and invalidate the pairing session. + dispatch_async(self.queue, ^{ + [[self _concreteController] invalidateCASESessionEstablishmentForNode:self->_nodeID]; + }); } } From e57dedfb862af38c41f2a11f4becadbc54c740f9 Mon Sep 17 00:00:00 2001 From: Erwin Pan Date: Thu, 31 Oct 2024 04:06:32 +0800 Subject: [PATCH 016/121] Fix Chef unable to set audio-output through RPC (#36295) * Fix Chef unable to set audio-output through RPC * Fix restyle issue --- .../audio-output/AudioOutputManager.cpp | 36 ++++++++++++++++--- .../audio-output/AudioOutputManager.h | 4 +-- examples/chef/common/stubs.cpp | 11 ------ 3 files changed, 33 insertions(+), 18 deletions(-) diff --git a/examples/chef/common/clusters/audio-output/AudioOutputManager.cpp b/examples/chef/common/clusters/audio-output/AudioOutputManager.cpp index 65df8db9ff0bb2..776baf5ea1f7b0 100644 --- a/examples/chef/common/clusters/audio-output/AudioOutputManager.cpp +++ b/examples/chef/common/clusters/audio-output/AudioOutputManager.cpp @@ -16,15 +16,21 @@ * limitations under the License. */ +#include +#include #include +#include + #ifdef MATTER_DM_PLUGIN_AUDIO_OUTPUT_SERVER #include "AudioOutputManager.h" +using namespace chip; using namespace chip::app; using namespace chip::app::Clusters::AudioOutput; using chip::app::AttributeValueEncoder; +using chip::Protocols::InteractionModel::Status; -AudioOutputManager::AudioOutputManager() +AudioOutputManager::AudioOutputManager(chip::EndpointId endpoint) : mEndpoint(endpoint) { struct OutputData outputData1(1, chip::app::Clusters::AudioOutput::OutputTypeEnum::kHdmi, "HDMI 1"); mOutputs.push_back(outputData1); @@ -32,13 +38,17 @@ AudioOutputManager::AudioOutputManager() mOutputs.push_back(outputData2); struct OutputData outputData3(3, chip::app::Clusters::AudioOutput::OutputTypeEnum::kHdmi, "HDMI 3"); mOutputs.push_back(outputData3); - - mCurrentOutput = 1; } uint8_t AudioOutputManager::HandleGetCurrentOutput() { - return mCurrentOutput; + uint8_t currentOutput = 1; + Status status = Attributes::CurrentOutput::Get(mEndpoint, ¤tOutput); + if (Status::Success != status) + { + ChipLogError(Zcl, "Unable to get CurrentOutput attribute, err:0x%x", to_underlying(status)); + } + return currentOutput; } CHIP_ERROR AudioOutputManager::HandleGetOutputList(AttributeValueEncoder & aEncoder) @@ -72,11 +82,27 @@ bool AudioOutputManager::HandleSelectOutput(const uint8_t & index) { if (outputData.index == index) { - mCurrentOutput = index; + // Sync the CurrentOutput to attribute storage while reporting changes + Status status = Attributes::CurrentOutput::Set(mEndpoint, index); + if (Status::Success != status) + { + ChipLogError(Zcl, "CurrentOutput is not stored successfully, err:0x%x", to_underlying(status)); + } return true; } } return false; } + +static std::map> gAudioOutputManagerInstance{}; + +void emberAfAudioOutputClusterInitCallback(EndpointId endpoint) +{ + ChipLogProgress(Zcl, "TV Linux App: AudioOutput::SetDefaultDelegate, endpoint=%x", endpoint); + + gAudioOutputManagerInstance[endpoint] = std::make_unique(endpoint); + + SetDefaultDelegate(endpoint, gAudioOutputManagerInstance[endpoint].get()); +} #endif // MATTER_DM_PLUGIN_AUDIO_OUTPUT_SERVER diff --git a/examples/chef/common/clusters/audio-output/AudioOutputManager.h b/examples/chef/common/clusters/audio-output/AudioOutputManager.h index ad64b7c9c96d5d..93c94d6f7ee347 100644 --- a/examples/chef/common/clusters/audio-output/AudioOutputManager.h +++ b/examples/chef/common/clusters/audio-output/AudioOutputManager.h @@ -27,7 +27,7 @@ class AudioOutputManager : public chip::app::Clusters::AudioOutput::Delegate using OutputInfoType = chip::app::Clusters::AudioOutput::Structs::OutputInfoStruct::Type; public: - AudioOutputManager(); + AudioOutputManager(chip::EndpointId endpoint); uint8_t HandleGetCurrentOutput() override; CHIP_ERROR HandleGetOutputList(chip::app::AttributeValueEncoder & aEncoder) override; @@ -54,6 +54,6 @@ class AudioOutputManager : public chip::app::Clusters::AudioOutput::Delegate }; protected: - uint8_t mCurrentOutput = 1; + chip::EndpointId mEndpoint; std::vector mOutputs; }; diff --git a/examples/chef/common/stubs.cpp b/examples/chef/common/stubs.cpp index 513bb412920d74..5cbe80aa83f162 100644 --- a/examples/chef/common/stubs.cpp +++ b/examples/chef/common/stubs.cpp @@ -270,17 +270,6 @@ void MatterPostAttributeChangeCallback(const chip::app::ConcreteAttributePath & */ void emberAfOnOffClusterInitCallback(EndpointId endpoint) {} -#ifdef MATTER_DM_PLUGIN_AUDIO_OUTPUT_SERVER -#include "audio-output/AudioOutputManager.h" -static AudioOutputManager audioOutputManager; - -void emberAfAudioOutputClusterInitCallback(EndpointId endpoint) -{ - ChipLogProgress(Zcl, "TV Linux App: AudioOutput::SetDefaultDelegate"); - AudioOutput::SetDefaultDelegate(endpoint, &audioOutputManager); -} -#endif - #ifdef MATTER_DM_PLUGIN_CHANNEL_SERVER #include "channel/ChannelManager.h" static ChannelManager channelManager; From 79a3224645fc79db730a591982c45884cfa6257f Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Wed, 30 Oct 2024 17:02:25 -0400 Subject: [PATCH 017/121] Scenes-cluster: move non-template things into non-template functions to save flash (#36288) * Move non-template things into non-template functions * Add back comment referencing bug * Add a comment regarding status ... I did not update the logic but it does seem wrong --------- Co-authored-by: Andrei Litvin --- .../clusters/scenes-server/scenes-server.cpp | 60 ++++++++++--------- 1 file changed, 33 insertions(+), 27 deletions(-) diff --git a/src/app/clusters/scenes-server/scenes-server.cpp b/src/app/clusters/scenes-server/scenes-server.cpp index ae10a3dd7ce11d..e7e6821731d477 100644 --- a/src/app/clusters/scenes-server/scenes-server.cpp +++ b/src/app/clusters/scenes-server/scenes-server.cpp @@ -54,6 +54,25 @@ namespace ScenesManagement { namespace { +Protocols::InteractionModel::Status ResponseStatus(CHIP_ERROR err) +{ + // TODO : Properly fix mapping between error types (issue https://github.com/project-chip/connectedhomeip/issues/26885) + if (CHIP_ERROR_NOT_FOUND == err) + { + return Protocols::InteractionModel::Status::NotFound; + } + if (CHIP_ERROR_NO_MEMORY == err) + { + return Protocols::InteractionModel::Status::ResourceExhausted; + } + if (CHIP_IM_GLOBAL_STATUS(UnsupportedAttribute) == err) + { + // TODO: Confirm if we need to add UnsupportedAttribute status as a return for Scene Commands + return Protocols::InteractionModel::Status::InvalidCommand; + } + return StatusIB(err).mStatus; +} + /// @brief Generate and add a response to a command handler context if err parameter is not CHIP_NO_ERROR /// @tparam ResponseType Type of response, depends on the command /// @param ctx Command Handler context where to add reponse @@ -65,24 +84,7 @@ CHIP_ERROR AddResponseOnError(CommandHandlerInterface::HandlerContext & ctx, Res { if (CHIP_NO_ERROR != err) { - // TODO : Properly fix mapping between error types (issue https://github.com/project-chip/connectedhomeip/issues/26885) - if (CHIP_ERROR_NOT_FOUND == err) - { - resp.status = to_underlying(Protocols::InteractionModel::Status::NotFound); - } - else if (CHIP_ERROR_NO_MEMORY == err) - { - resp.status = to_underlying(Protocols::InteractionModel::Status::ResourceExhausted); - } - else if (CHIP_IM_GLOBAL_STATUS(UnsupportedAttribute) == err) - { - // TODO: Confirm if we need to add UnsupportedAttribute status as a return for Scene Commands - resp.status = to_underlying(Protocols::InteractionModel::Status::InvalidCommand); - } - else - { - resp.status = to_underlying(StatusIB(err).mStatus); - } + resp.status = to_underlying(ResponseStatus(err)); ctx.mCommandHandler.AddResponse(ctx.mRequestPath, resp); } return err; @@ -97,24 +99,28 @@ CHIP_ERROR AddResponseOnError(CommandHandlerInterface::HandlerContext & ctx, Res template CHIP_ERROR AddResponseOnError(CommandHandlerInterface::HandlerContext & ctx, ResponseType & resp, Status status) { + // TODO: this seems odd: we convert `status` to a CHIP_ERROR and then back to status. This seems + // potentially lossy and not ideal. return AddResponseOnError(ctx, resp, StatusIB(status).ToChipError()); } -template -CHIP_ERROR UpdateLastConfiguredBy(HandlerContext & ctx, ResponseType resp) +Status SetLastConfiguredBy(HandlerContext & ctx) { - Access::SubjectDescriptor descriptor = ctx.mCommandHandler.GetSubjectDescriptor(); - Status status = Status::Success; + const Access::SubjectDescriptor descriptor = ctx.mCommandHandler.GetSubjectDescriptor(); if (AuthMode::kCase == descriptor.authMode) { - status = Attributes::LastConfiguredBy::Set(ctx.mRequestPath.mEndpointId, descriptor.subject); - } - else - { - status = Attributes::LastConfiguredBy::SetNull(ctx.mRequestPath.mEndpointId); + return Attributes::LastConfiguredBy::Set(ctx.mRequestPath.mEndpointId, descriptor.subject); } + return Attributes::LastConfiguredBy::SetNull(ctx.mRequestPath.mEndpointId); +} + +template +CHIP_ERROR UpdateLastConfiguredBy(HandlerContext & ctx, ResponseType resp) +{ + Status status = SetLastConfiguredBy(ctx); + // LastConfiguredBy is optional, so we don't want to fail the command if it fails to update VerifyOrReturnValue(!(Status::Success == status || Status::UnsupportedAttribute == status), CHIP_NO_ERROR); return AddResponseOnError(ctx, resp, status); From f59ec3818b6d838fba71762182e82959c74b449a Mon Sep 17 00:00:00 2001 From: lpbeliveau-silabs <112982107+lpbeliveau-silabs@users.noreply.github.com> Date: Wed, 30 Oct 2024 17:09:32 -0400 Subject: [PATCH 018/121] [Silabs] Bugfix/silabs lock app aliro fix (#36300) * [SL-UP] 917 static variable retention fix (#79) * [SL-UP] Doorlock featuremap Aliro Removal (#80) --- .../silabs/data_model/lock-app.matter | 2 +- .../lock-app/silabs/data_model/lock-app.zap | 2 +- .../lock-app/silabs/include/LockManager.h | 22 +++++++++++++------ examples/lock-app/silabs/src/LockManager.cpp | 16 ++++++++++---- 4 files changed, 29 insertions(+), 13 deletions(-) diff --git a/examples/lock-app/silabs/data_model/lock-app.matter b/examples/lock-app/silabs/data_model/lock-app.matter index 512435d9989b24..8a7695c75d6c87 100644 --- a/examples/lock-app/silabs/data_model/lock-app.matter +++ b/examples/lock-app/silabs/data_model/lock-app.matter @@ -3261,7 +3261,7 @@ endpoint 1 { callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute attributeList; - ram attribute featureMap default = 0x7DB3; + ram attribute featureMap default = 0x1DB3; ram attribute clusterRevision default = 7; handle command LockDoor; diff --git a/examples/lock-app/silabs/data_model/lock-app.zap b/examples/lock-app/silabs/data_model/lock-app.zap index a10a27ee9ad9a4..e3488a663bc5d9 100644 --- a/examples/lock-app/silabs/data_model/lock-app.zap +++ b/examples/lock-app/silabs/data_model/lock-app.zap @@ -6188,7 +6188,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0x7DB3", + "defaultValue": "0x1DB3", "reportable": 1, "minInterval": 1, "maxInterval": 65534, diff --git a/examples/lock-app/silabs/include/LockManager.h b/examples/lock-app/silabs/include/LockManager.h index 7345782d695194..00a4407c349e39 100644 --- a/examples/lock-app/silabs/include/LockManager.h +++ b/examples/lock-app/silabs/include/LockManager.h @@ -199,10 +199,12 @@ class LockManager private: struct UnlatchContext { + static constexpr uint8_t kMaxPinLength = UINT8_MAX; + uint8_t mPinBuffer[kMaxPinLength]; + uint8_t mPinLength; chip::EndpointId mEndpointId; Nullable mFabricIdx; Nullable mNodeId; - Optional mPin; OperationErrorEnum mErr; void Update(chip::EndpointId endpointId, const Nullable & fabricIdx, @@ -211,8 +213,18 @@ class LockManager mEndpointId = endpointId; mFabricIdx = fabricIdx; mNodeId = nodeId; - mPin = pin; mErr = err; + + if (pin.HasValue()) + { + memcpy(mPinBuffer, pin.Value().data(), pin.Value().size()); + mPinLength = static_cast(pin.Value().size()); + } + else + { + memset(mPinBuffer, 0, kMaxPinLength); + mPinLength = 0; + } } }; UnlatchContext mUnlatchContext; @@ -242,11 +254,7 @@ class LockManager uint8_t mCredentialData[kNumCredentialTypes][kMaxCredentials][kMaxCredentialSize]; CredentialStruct mCredentials[kMaxUsers][kMaxCredentials]; - static LockManager sLock; EFR32DoorLock::LockInitParams::LockParam LockParams; }; -inline LockManager & LockMgr() -{ - return LockManager::sLock; -} +LockManager & LockMgr(); diff --git a/examples/lock-app/silabs/src/LockManager.cpp b/examples/lock-app/silabs/src/LockManager.cpp index 04527e53ac7ab1..1a4fd934631707 100644 --- a/examples/lock-app/silabs/src/LockManager.cpp +++ b/examples/lock-app/silabs/src/LockManager.cpp @@ -25,11 +25,18 @@ #include #include -LockManager LockManager::sLock; - using namespace ::chip::DeviceLayer::Internal; using namespace EFR32DoorLock::LockInitParams; +namespace { +LockManager sLock; +} // namespace + +LockManager & LockMgr() +{ + return sLock; +} + CHIP_ERROR LockManager::Init(chip::app::DataModel::Nullable state, LockParam lockParam) { @@ -257,8 +264,9 @@ void LockManager::UnlockAfterUnlatch() bool succes = false; if (mUnlatchContext.mEndpointId != kInvalidEndpointId) { - succes = setLockState(mUnlatchContext.mEndpointId, mUnlatchContext.mFabricIdx, mUnlatchContext.mNodeId, - DlLockState::kUnlocked, mUnlatchContext.mPin, mUnlatchContext.mErr); + succes = setLockState( + mUnlatchContext.mEndpointId, mUnlatchContext.mFabricIdx, mUnlatchContext.mNodeId, DlLockState::kUnlocked, + MakeOptional(chip::ByteSpan(mUnlatchContext.mPinBuffer, mUnlatchContext.mPinLength)), mUnlatchContext.mErr); } if (!succes) From 554c5781a802b65b58d16a97567fb045be444b92 Mon Sep 17 00:00:00 2001 From: Mathieu Kardous <84793247+mkardous-silabs@users.noreply.github.com> Date: Wed, 30 Oct 2024 17:23:37 -0400 Subject: [PATCH 019/121] [Silabs] First Refactor of the SiWx917 Wi-Fi Interface (#36305) * Rename efr32_sdk_build_root to silabs_sdk_build_root * Remove wifi_config.h and move standard to C++ * Refactor SiW917 Wi-Fi application implementation * remove commented source file * fix ICD build issues * rename file * continue clean up * Set working wifi_sdk hash * Finish clean up * Update submodules * update comment * Adress review comments --- build_overrides/efr32_sdk.gni | 2 +- .../air-quality-sensor-app/silabs/BUILD.gn | 4 +- examples/build_overrides/efr32_sdk.gni | 2 +- examples/chef/silabs/BUILD.gn | 4 +- examples/dishwasher-app/silabs/BUILD.gn | 4 +- .../energy-management-app/silabs/BUILD.gn | 4 +- examples/light-switch-app/silabs/BUILD.gn | 4 +- examples/lighting-app/silabs/BUILD.gn | 4 +- examples/lit-icd-app/silabs/BUILD.gn | 4 +- examples/lock-app/silabs/BUILD.gn | 4 +- examples/platform/silabs/FreeRTOSConfig.h | 2 - examples/platform/silabs/MatterConfig.cpp | 39 +- examples/platform/silabs/MatterConfig.h | 1 + examples/platform/silabs/SiWx917/BUILD.gn | 17 +- .../silabs/SiWx917/SiWx917/sl_wlan_config.h | 110 --- .../sl_wifi_if.cpp => SiWxWifiInterface.cpp} | 883 +++++++++--------- examples/platform/silabs/efr32/BUILD.gn | 10 +- .../platform/silabs/efr32/rs911x/rs9117.gni | 7 +- .../platform/silabs/efr32/rs911x/rs911x.gni | 2 +- .../platform/silabs/efr32/rs911x/rsi_if.cpp | 85 +- .../silabs/efr32/rs911x/sl_wifi_if.cpp | 1 - .../silabs/efr32/rs911x/sl_wlan_config.h | 109 --- .../platform/silabs/efr32/wf200/host_if.cpp | 8 +- .../platform/silabs/efr32/wf200/wf200.gni | 2 +- examples/platform/silabs/provision/BUILD.gn | 6 +- examples/platform/silabs/wfx_rsi.h | 32 +- examples/platform/silabs/wifi/wfx_notify.cpp | 4 +- .../platform/silabs/wifi/wfx_rsi_host.cpp | 18 +- examples/pump-app/silabs/BUILD.gn | 4 +- examples/smoke-co-alarm-app/silabs/BUILD.gn | 4 +- examples/thermostat/silabs/BUILD.gn | 4 +- examples/window-app/silabs/BUILD.gn | 4 +- src/lwip/BUILD.gn | 2 +- .../silabs/ConfigurationManagerImpl.cpp | 4 +- .../silabs/ConnectivityManagerImpl_WIFI.cpp | 2 +- .../silabs/NetworkCommissioningWiFiDriver.cpp | 2 +- src/platform/silabs/PlatformManagerImpl.cpp | 4 +- src/platform/silabs/SiWx917/BUILD.gn | 1 - .../silabs/SiWx917/wifi/ethernetif.cpp | 269 ------ src/platform/silabs/SiWx917/wifi/ethernetif.h | 49 - .../silabs/SiWx917/wifi/lwip_netif.cpp | 149 --- .../silabs/SiWx917/wifi/wifi_config.h | 71 -- src/platform/silabs/efr32/BUILD.gn | 3 +- src/platform/silabs/efr32/args.gni | 4 +- src/platform/silabs/efr32/wifi/ethernetif.cpp | 1 - src/platform/silabs/efr32/wifi/lwip_netif.cpp | 5 +- src/platform/silabs/efr32/wifi/wifi_config.h | 53 -- src/platform/silabs/provision/BUILD.gn | 2 +- src/platform/silabs/wifi/dhcp_client.cpp | 1 - src/platform/silabs/wifi/wfx_host_events.h | 8 +- src/platform/silabs/wifi_args.gni | 6 +- src/system/BUILD.gn | 2 +- src/test_driver/efr32/BUILD.gn | 2 +- src/test_driver/efr32/args.gni | 2 +- .../openthread/platforms/efr32/BUILD.gn | 6 +- third_party/silabs/BUILD.gn | 12 +- third_party/silabs/SiWx917_sdk.gni | 6 +- third_party/silabs/lwip.gni | 2 +- third_party/silabs/matter_support | 2 +- third_party/silabs/silabs_lwip/BUILD.gn | 2 +- 60 files changed, 612 insertions(+), 1448 deletions(-) delete mode 100644 examples/platform/silabs/SiWx917/SiWx917/sl_wlan_config.h rename examples/platform/silabs/SiWx917/{SiWx917/sl_wifi_if.cpp => SiWxWifiInterface.cpp} (56%) delete mode 120000 examples/platform/silabs/efr32/rs911x/sl_wifi_if.cpp delete mode 100644 examples/platform/silabs/efr32/rs911x/sl_wlan_config.h delete mode 100644 src/platform/silabs/SiWx917/wifi/ethernetif.cpp delete mode 100644 src/platform/silabs/SiWx917/wifi/ethernetif.h delete mode 100644 src/platform/silabs/SiWx917/wifi/lwip_netif.cpp delete mode 100644 src/platform/silabs/SiWx917/wifi/wifi_config.h delete mode 100644 src/platform/silabs/efr32/wifi/wifi_config.h diff --git a/build_overrides/efr32_sdk.gni b/build_overrides/efr32_sdk.gni index 4a7344b4c7ebed..fd5e7ce094bc65 100644 --- a/build_overrides/efr32_sdk.gni +++ b/build_overrides/efr32_sdk.gni @@ -14,5 +14,5 @@ declare_args() { # Root directory for efr32 SDK build files. - efr32_sdk_build_root = "//third_party/silabs" + silabs_sdk_build_root = "//third_party/silabs" } diff --git a/examples/air-quality-sensor-app/silabs/BUILD.gn b/examples/air-quality-sensor-app/silabs/BUILD.gn index ed3077a3f16c65..958918e0d504c1 100644 --- a/examples/air-quality-sensor-app/silabs/BUILD.gn +++ b/examples/air-quality-sensor-app/silabs/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -38,7 +38,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/examples/build_overrides/efr32_sdk.gni b/examples/build_overrides/efr32_sdk.gni index d5a35449d9ffd0..ece2fd94e957ff 100644 --- a/examples/build_overrides/efr32_sdk.gni +++ b/examples/build_overrides/efr32_sdk.gni @@ -14,5 +14,5 @@ declare_args() { # Root directory for erf32 SDK. - efr32_sdk_build_root = "//third_party/connectedhomeip/third_party/silabs" + silabs_sdk_build_root = "//third_party/connectedhomeip/third_party/silabs" } diff --git a/examples/chef/silabs/BUILD.gn b/examples/chef/silabs/BUILD.gn index f7192457588b26..34dba76cc343db 100644 --- a/examples/chef/silabs/BUILD.gn +++ b/examples/chef/silabs/BUILD.gn @@ -18,8 +18,8 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/efr32_sdk.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/efr32_sdk.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") diff --git a/examples/dishwasher-app/silabs/BUILD.gn b/examples/dishwasher-app/silabs/BUILD.gn index d024a5da954b9d..c596a8a77e381f 100644 --- a/examples/dishwasher-app/silabs/BUILD.gn +++ b/examples/dishwasher-app/silabs/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -39,7 +39,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/examples/energy-management-app/silabs/BUILD.gn b/examples/energy-management-app/silabs/BUILD.gn index 624cfff6250a85..d4a4887ceec3a7 100644 --- a/examples/energy-management-app/silabs/BUILD.gn +++ b/examples/energy-management-app/silabs/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -38,7 +38,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/examples/light-switch-app/silabs/BUILD.gn b/examples/light-switch-app/silabs/BUILD.gn index 2602842edf4d83..cbe8a512f822eb 100644 --- a/examples/light-switch-app/silabs/BUILD.gn +++ b/examples/light-switch-app/silabs/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -38,7 +38,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/examples/lighting-app/silabs/BUILD.gn b/examples/lighting-app/silabs/BUILD.gn index 55d7d4100946f2..00aa6d9028a2ef 100644 --- a/examples/lighting-app/silabs/BUILD.gn +++ b/examples/lighting-app/silabs/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -38,7 +38,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/examples/lit-icd-app/silabs/BUILD.gn b/examples/lit-icd-app/silabs/BUILD.gn index eb7fa7a09a6d95..8dfa759c2b909a 100644 --- a/examples/lit-icd-app/silabs/BUILD.gn +++ b/examples/lit-icd-app/silabs/BUILD.gn @@ -19,7 +19,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -39,7 +39,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/examples/lock-app/silabs/BUILD.gn b/examples/lock-app/silabs/BUILD.gn index a20a4ad66fedc7..81640548c32d5b 100644 --- a/examples/lock-app/silabs/BUILD.gn +++ b/examples/lock-app/silabs/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -38,7 +38,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/examples/platform/silabs/FreeRTOSConfig.h b/examples/platform/silabs/FreeRTOSConfig.h index 1c2db9621f61ee..24a1408a47a077 100644 --- a/examples/platform/silabs/FreeRTOSConfig.h +++ b/examples/platform/silabs/FreeRTOSConfig.h @@ -103,8 +103,6 @@ extern "C" { #endif -#include - #include #include diff --git a/examples/platform/silabs/MatterConfig.cpp b/examples/platform/silabs/MatterConfig.cpp index 4440fcf58444ca..44c60ca0f101e7 100644 --- a/examples/platform/silabs/MatterConfig.cpp +++ b/examples/platform/silabs/MatterConfig.cpp @@ -40,9 +40,9 @@ #include "MemMonitoring.h" #endif -#ifdef SLI_SI91X_MCU_INTERFACE +#if defined(SLI_SI91X_MCU_INTERFACE) && SLI_SI91X_MCU_INTERFACE == 1 #include "wfx_rsi.h" -#endif /* SLI_SI91X_MCU_INTERFACE */ +#endif // SLI_SI91X_MCU_INTERFACE #include // If building with the EFR32-provided crypto backend, we can use the @@ -121,7 +121,7 @@ void UnlockOpenThreadTask(void) CHIP_ERROR SilabsMatterConfig::InitOpenThread(void) { - SILABS_LOG("Initializing OpenThread stack"); + ChipLogProgress(DeviceLayer, "Initializing OpenThread stack"); ReturnErrorOnFailure(ThreadStackMgr().InitThreadStack()); #if CHIP_DEVICE_CONFIG_THREAD_FTD @@ -138,7 +138,7 @@ CHIP_ERROR SilabsMatterConfig::InitOpenThread(void) #endif // CHIP_CONFIG_ENABLE_ICD_SERVER #endif // CHIP_DEVICE_CONFIG_THREAD_FTD - SILABS_LOG("Starting OpenThread task"); + ChipLogProgress(DeviceLayer, "Starting OpenThread task"); return ThreadStackMgrImpl().StartThreadTask(); } #endif // CHIP_ENABLE_OPENTHREAD @@ -171,7 +171,7 @@ void ApplicationStart(void * unused) SetDeviceAttestationCredentialsProvider(&Provision::Manager::GetInstance().GetStorage()); chip::DeviceLayer::PlatformMgr().UnlockChipStack(); - SILABS_LOG("Starting App Task"); + ChipLogProgress(DeviceLayer, "Starting App Task"); err = AppTask::GetAppTask().StartAppTask(); if (err != CHIP_NO_ERROR) appError(err); @@ -185,13 +185,13 @@ void SilabsMatterConfig::AppInit() { GetPlatform().Init(); sMainTaskHandle = osThreadNew(ApplicationStart, nullptr, &kMainTaskAttr); - SILABS_LOG("Starting scheduler"); + ChipLogProgress(DeviceLayer, "Starting scheduler"); VerifyOrDie(sMainTaskHandle); // We can't proceed if the Main Task creation failed. GetPlatform().StartScheduler(); // Should never get here. chip::Platform::MemoryShutdown(); - SILABS_LOG("Start Scheduler Failed"); + ChipLogProgress(DeviceLayer, "Start Scheduler Failed"); appError(CHIP_ERROR_INTERNAL); } @@ -204,9 +204,9 @@ CHIP_ERROR SilabsMatterConfig::InitMatter(const char * appName) // initialization. mbedtls_platform_set_calloc_free(CHIPPlatformMemoryCalloc, CHIPPlatformMemoryFree); #endif - SILABS_LOG("=================================================="); - SILABS_LOG("%s starting", appName); - SILABS_LOG("=================================================="); + ChipLogProgress(DeviceLayer, "=================================================="); + ChipLogProgress(DeviceLayer, "%s starting", appName); + ChipLogProgress(DeviceLayer, "=================================================="); #if PW_RPC_ENABLED chip::rpc::Init(); @@ -219,7 +219,7 @@ CHIP_ERROR SilabsMatterConfig::InitMatter(const char * appName) //============================================== // Init Matter Stack //============================================== - SILABS_LOG("Init CHIP Stack"); + ChipLogProgress(DeviceLayer, "Init CHIP Stack"); #ifdef SL_WIFI // Init Chip memory management before the stack @@ -309,16 +309,13 @@ CHIP_ERROR SilabsMatterConfig::InitWiFi(void) // Start wfx bus communication task. wfx_bus_start(); #ifdef SL_WFX_USE_SECURE_LINK - wfx_securelink_task_start(); // start securelink key renegotiation task -#endif // SL_WFX_USE_SECURE_LINK -#endif /* WF200_WIFI */ - -#ifdef SLI_SI91X_MCU_INTERFACE - sl_status_t status; - if ((status = wfx_wifi_rsi_init()) != SL_STATUS_OK) - { - ReturnErrorOnFailure((CHIP_ERROR) status); - } + // start securelink key renegotiation task + wfx_securelink_task_start(); +#endif // SL_WFX_USE_SECURE_LINK +#endif // WF200_WIFI + +#if defined(SLI_SI91X_MCU_INTERFACE) && SLI_SI91X_MCU_INTERFACE == 1 + VerifyOrReturnError(sl_matter_wifi_platform_init() == SL_STATUS_OK, CHIP_ERROR_INTERNAL); #endif // SLI_SI91X_MCU_INTERFACE return CHIP_NO_ERROR; diff --git a/examples/platform/silabs/MatterConfig.h b/examples/platform/silabs/MatterConfig.h index b6abcc1726f7ac..0f951c36f8b477 100644 --- a/examples/platform/silabs/MatterConfig.h +++ b/examples/platform/silabs/MatterConfig.h @@ -16,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#pragma once #include #include diff --git a/examples/platform/silabs/SiWx917/BUILD.gn b/examples/platform/silabs/SiWx917/BUILD.gn index 6756cc28c726ce..2abc3bc9d27c9a 100644 --- a/examples/platform/silabs/SiWx917/BUILD.gn +++ b/examples/platform/silabs/SiWx917/BUILD.gn @@ -19,7 +19,7 @@ import("${chip_root}/src/lib/lib.gni") import("${chip_root}/src/platform/device.gni") import("${chip_root}/src/platform/silabs/wifi_args.gni") import("${chip_root}/third_party/silabs/silabs_board.gni") -import("${efr32_sdk_build_root}/SiWx917_sdk.gni") +import("${silabs_sdk_build_root}/SiWx917_sdk.gni") declare_args() { enable_heap_monitoring = false @@ -167,18 +167,17 @@ config("silabs-wifi-config") { source_set("siwx917-common") { deps = [ "${silabs_common_plat_dir}/provision:storage" ] defines = [] - public_deps = [] + public_deps = [ "${lwip_root}:lwip" ] public_configs = [ ":siwx917-common-config", - "${efr32_sdk_build_root}:silabs_config", + "${silabs_sdk_build_root}:silabs_config", ":chip_examples_project_config", ] include_dirs = [ - ".", - "SiWx917/", "${silabs_plat_dir}/wifi", "${silabs_plat_si91x_wifi_dir}", + "${silabs_common_plat_dir}", ] #TO-DO Cleanup to be done for all the wifi files into common folder @@ -191,10 +190,10 @@ source_set("siwx917-common") { "${silabs_common_plat_dir}/syscalls_stubs.cpp", "${silabs_common_plat_dir}/wifi/wfx_notify.cpp", "${silabs_common_plat_dir}/wifi/wfx_rsi_host.cpp", - "${silabs_plat_dir}/wifi/dhcp_client.cpp", - "${silabs_plat_si91x_wifi_dir}/ethernetif.cpp", - "${silabs_plat_si91x_wifi_dir}/lwip_netif.cpp", - "SiWx917/sl_wifi_if.cpp", + "SiWxWifiInterface.cpp", + + # Wi-Fi Config - Using the file sdk support until the wiseconnect file is fixed + "${sdk_support_root}/components/service/network_manager/src/sl_net_for_lwip.c", ] if (chip_enable_pw_rpc || chip_build_libshell || sl_uart_log_output) { diff --git a/examples/platform/silabs/SiWx917/SiWx917/sl_wlan_config.h b/examples/platform/silabs/SiWx917/SiWx917/sl_wlan_config.h deleted file mode 100644 index 21ee4a5555f514..00000000000000 --- a/examples/platform/silabs/SiWx917/SiWx917/sl_wlan_config.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * - * Copyright (c) 2022 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. - */ - -#ifndef RSI_CONFIG_H -#define RSI_CONFIG_H - -#include "ble_config.h" -#if SLI_SI91X_MCU_INTERFACE -#include "rsi_wisemcu_hardware_setup.h" -#endif // SLI_SI91X_MCU_INTERFACE -#include "sl_wifi_device.h" - -//! Enable feature -#define RSI_ENABLE 1 -//! Disable feature -#define RSI_DISABLE 0 - -// Temmporary work-around for wifi-init failure in ACX modules with WiseConnect v3.3.3. This can be removed after integrating with -// WiseConnect v3.4.0 -#if (SL_SI91X_ACX_MODULE == 1) -#define REGION_CODE IGNORE_REGION -#else -#define REGION_CODE US -#endif - -static const sl_wifi_device_configuration_t config = { - .boot_option = LOAD_NWP_FW, - .mac_address = NULL, - .band = SL_SI91X_WIFI_BAND_2_4GHZ, - .region_code = REGION_CODE, - .boot_config = { .oper_mode = SL_SI91X_CLIENT_MODE, - .coex_mode = SL_SI91X_WLAN_BLE_MODE, - .feature_bit_map = -#ifdef SLI_SI91X_MCU_INTERFACE - (SL_SI91X_FEAT_SECURITY_OPEN | SL_SI91X_FEAT_WPS_DISABLE), -#else - (SL_SI91X_FEAT_SECURITY_OPEN | SL_SI91X_FEAT_AGGREGATION), -#endif - .tcp_ip_feature_bit_map = (SL_SI91X_TCP_IP_FEAT_DHCPV4_CLIENT | SL_SI91X_TCP_IP_FEAT_DNS_CLIENT | - SL_SI91X_TCP_IP_FEAT_SSL | SL_SI91X_TCP_IP_FEAT_BYPASS -#ifdef ipv6_FEATURE_REQUIRED - | SL_SI91X_TCP_IP_FEAT_DHCPV6_CLIENT | SL_SI91X_TCP_IP_FEAT_IPV6 -#endif - | SL_SI91X_TCP_IP_FEAT_ICMP | SL_SI91X_TCP_IP_FEAT_EXTENSION_VALID), - .custom_feature_bit_map = (SL_SI91X_CUSTOM_FEAT_EXTENTION_VALID | RSI_CUSTOM_FEATURE_BIT_MAP), - .ext_custom_feature_bit_map = (RSI_EXT_CUSTOM_FEATURE_BIT_MAP | (SL_SI91X_EXT_FEAT_BT_CUSTOM_FEAT_ENABLE) -#if (defined A2DP_POWER_SAVE_ENABLE) - | SL_SI91X_EXT_FEAT_XTAL_CLK_ENABLE(2) -#endif - ), - .bt_feature_bit_map = (RSI_BT_FEATURE_BITMAP -#if (RSI_BT_GATT_ON_CLASSIC) - | SL_SI91X_BT_ATT_OVER_CLASSIC_ACL /* to support att over classic acl link */ -#endif - ), -#ifdef RSI_PROCESS_MAX_RX_DATA - .ext_tcp_ip_feature_bit_map = - (RSI_EXT_TCPIP_FEATURE_BITMAP | SL_SI91X_CONFIG_FEAT_EXTENTION_VALID | SL_SI91X_EXT_TCP_MAX_RECV_LENGTH), -#else - .ext_tcp_ip_feature_bit_map = (RSI_EXT_TCPIP_FEATURE_BITMAP | SL_SI91X_CONFIG_FEAT_EXTENTION_VALID), -#endif - //! ENABLE_BLE_PROTOCOL in bt_feature_bit_map - .ble_feature_bit_map = - ((SL_SI91X_BLE_MAX_NBR_PERIPHERALS(RSI_BLE_MAX_NBR_PERIPHERALS) | - SL_SI91X_BLE_MAX_NBR_CENTRALS(RSI_BLE_MAX_NBR_CENTRALS) | - SL_SI91X_BLE_MAX_NBR_ATT_SERV(RSI_BLE_MAX_NBR_ATT_SERV) | - SL_SI91X_BLE_MAX_NBR_ATT_REC(RSI_BLE_MAX_NBR_ATT_REC)) | - SL_SI91X_FEAT_BLE_CUSTOM_FEAT_EXTENTION_VALID | SL_SI91X_BLE_PWR_INX(RSI_BLE_PWR_INX) | - SL_SI91X_BLE_PWR_SAVE_OPTIONS(RSI_BLE_PWR_SAVE_OPTIONS) | SL_SI91X_916_BLE_COMPATIBLE_FEAT_ENABLE -#if RSI_BLE_GATT_ASYNC_ENABLE - | SL_SI91X_BLE_GATT_ASYNC_ENABLE -#endif - ), - - .ble_ext_feature_bit_map = ((SL_SI91X_BLE_NUM_CONN_EVENTS(RSI_BLE_NUM_CONN_EVENTS) | - SL_SI91X_BLE_NUM_REC_BYTES(RSI_BLE_NUM_REC_BYTES)) -#if RSI_BLE_INDICATE_CONFIRMATION_FROM_HOST - | SL_SI91X_BLE_INDICATE_CONFIRMATION_FROM_HOST // indication response from app -#endif -#if RSI_BLE_MTU_EXCHANGE_FROM_HOST - | SL_SI91X_BLE_MTU_EXCHANGE_FROM_HOST // MTU Exchange request initiation from app -#endif -#if RSI_BLE_SET_SCAN_RESP_DATA_FROM_HOST - | (SL_SI91X_BLE_SET_SCAN_RESP_DATA_FROM_HOST) // Set SCAN Resp Data from app -#endif -#if RSI_BLE_DISABLE_CODED_PHY_FROM_HOST - | (SL_SI91X_BLE_DISABLE_CODED_PHY_FROM_HOST) // Disable Coded PHY from app -#endif -#if BLE_SIMPLE_GATT - | SL_SI91X_BLE_GATT_INIT -#endif - ), - .config_feature_bit_map = (SL_SI91X_FEAT_SLEEP_GPIO_SEL_BITMAP | RSI_CONFIG_FEATURE_BITMAP) } -}; - -#endif diff --git a/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp b/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp similarity index 56% rename from examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp rename to examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp index d3572289eb7f30..1e573ed5941784 100644 --- a/examples/platform/silabs/SiWx917/SiWx917/sl_wifi_if.cpp +++ b/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp @@ -33,10 +33,10 @@ #include "event_groups.h" #include "sl_board_configuration.h" #include "sl_status.h" +#include "sl_wifi_device.h" #include "task.h" #include "wfx_host_events.h" #include "wfx_rsi.h" - #include #include #include @@ -53,14 +53,22 @@ extern "C" { #include "sl_wifi_callback_framework.h" #include "sl_wifi_constants.h" #include "sl_wifi_types.h" -#include "sl_wlan_config.h" #include "wfx_host_events.h" #if SL_MBEDTLS_USE_TINYCRYPT #include "sl_si91x_constants.h" #include "sl_si91x_trng.h" #endif // SL_MBEDTLS_USE_TINYCRYPT + +#include +#include +#include +#include } +#if SLI_SI91X_MCU_INTERFACE +#include "rsi_wisemcu_hardware_setup.h" +#endif // SLI_SI91X_MCU_INTERFACE + #if (EXP_BOARD) #include "rsi_bt_common_apis.h" #endif @@ -69,89 +77,366 @@ extern "C" { #include "rsi_rom_power_save.h" #include "sl_si91x_button_pin_config.h" #include "sl_si91x_power_manager.h" +#endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE + +// Temmporary work-around for wifi-init failure in ACX modules with WiseConnect v3.3.3. This can be removed after integrating with +// WiseConnect v3.4.0 +#if (SL_SI91X_ACX_MODULE == 1) +#define REGION_CODE IGNORE_REGION +#else +#define REGION_CODE US +#endif + +WfxRsi_t wfx_rsi; +extern osSemaphoreId_t sl_rs_ble_init_sem; namespace { + +#if CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE // TODO: should be removed once we are getting the press interrupt for button 0 with sleep -#define BUTTON_PRESSED 1 bool btn0_pressed = false; - #ifdef ENABLE_CHIP_SHELL bool ps_requirement_added = false; #endif // ENABLE_CHIP_SHELL -} // namespace #endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE -#define ADV_SCAN_THRESHOLD -40 -#define ADV_RSSI_TOLERANCE_THRESHOLD 5 -#define ADV_ACTIVE_SCAN_DURATION 15 -#define ADV_PASSIVE_SCAN_DURATION 20 -#define ADV_MULTIPROBE 1 -#define ADV_SCAN_PERIODICITY 10 +bool hasNotifiedWifiConnectivity = false; +bool hasNotifiedIPV6 = false; +#if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) +bool hasNotifiedIPV4 = false; +#endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ + +wfx_wifi_scan_ext_t temp_reset; + +osSemaphoreId_t sScanCompleteSemaphore; +osSemaphoreId_t sScanInProgressSemaphore; +osTimerId_t sDHCPTimer; +osMessageQueueId_t sWifiEventQueue = nullptr; + +sl_net_wifi_lwip_context_t wifi_client_context; +sl_wifi_security_t security = SL_WIFI_SECURITY_UNKNOWN; + +const sl_wifi_device_configuration_t config = { + .boot_option = LOAD_NWP_FW, + .mac_address = NULL, + .band = SL_SI91X_WIFI_BAND_2_4GHZ, + .region_code = REGION_CODE, + .boot_config = { .oper_mode = SL_SI91X_CLIENT_MODE, + .coex_mode = SL_SI91X_WLAN_BLE_MODE, + .feature_bit_map = +#ifdef SLI_SI91X_MCU_INTERFACE + (SL_SI91X_FEAT_SECURITY_OPEN | SL_SI91X_FEAT_WPS_DISABLE), +#else + (SL_SI91X_FEAT_SECURITY_OPEN | SL_SI91X_FEAT_AGGREGATION), +#endif + .tcp_ip_feature_bit_map = (SL_SI91X_TCP_IP_FEAT_DHCPV4_CLIENT | SL_SI91X_TCP_IP_FEAT_DNS_CLIENT | + SL_SI91X_TCP_IP_FEAT_SSL | SL_SI91X_TCP_IP_FEAT_BYPASS +#ifdef ipv6_FEATURE_REQUIRED + | SL_SI91X_TCP_IP_FEAT_DHCPV6_CLIENT | SL_SI91X_TCP_IP_FEAT_IPV6 +#endif + | SL_SI91X_TCP_IP_FEAT_ICMP | SL_SI91X_TCP_IP_FEAT_EXTENSION_VALID), + .custom_feature_bit_map = (SL_SI91X_CUSTOM_FEAT_EXTENTION_VALID | RSI_CUSTOM_FEATURE_BIT_MAP), + .ext_custom_feature_bit_map = (RSI_EXT_CUSTOM_FEATURE_BIT_MAP | (SL_SI91X_EXT_FEAT_BT_CUSTOM_FEAT_ENABLE) +#if (defined A2DP_POWER_SAVE_ENABLE) + | SL_SI91X_EXT_FEAT_XTAL_CLK_ENABLE(2) +#endif + ), + .bt_feature_bit_map = (RSI_BT_FEATURE_BITMAP +#if (RSI_BT_GATT_ON_CLASSIC) + | SL_SI91X_BT_ATT_OVER_CLASSIC_ACL /* to support att over classic acl link */ +#endif + ), +#ifdef RSI_PROCESS_MAX_RX_DATA + .ext_tcp_ip_feature_bit_map = + (RSI_EXT_TCPIP_FEATURE_BITMAP | SL_SI91X_CONFIG_FEAT_EXTENTION_VALID | SL_SI91X_EXT_TCP_MAX_RECV_LENGTH), +#else + .ext_tcp_ip_feature_bit_map = (RSI_EXT_TCPIP_FEATURE_BITMAP | SL_SI91X_CONFIG_FEAT_EXTENTION_VALID), +#endif + //! ENABLE_BLE_PROTOCOL in bt_feature_bit_map + .ble_feature_bit_map = + ((SL_SI91X_BLE_MAX_NBR_PERIPHERALS(RSI_BLE_MAX_NBR_PERIPHERALS) | + SL_SI91X_BLE_MAX_NBR_CENTRALS(RSI_BLE_MAX_NBR_CENTRALS) | + SL_SI91X_BLE_MAX_NBR_ATT_SERV(RSI_BLE_MAX_NBR_ATT_SERV) | + SL_SI91X_BLE_MAX_NBR_ATT_REC(RSI_BLE_MAX_NBR_ATT_REC)) | + SL_SI91X_FEAT_BLE_CUSTOM_FEAT_EXTENTION_VALID | SL_SI91X_BLE_PWR_INX(RSI_BLE_PWR_INX) | + SL_SI91X_BLE_PWR_SAVE_OPTIONS(RSI_BLE_PWR_SAVE_OPTIONS) | SL_SI91X_916_BLE_COMPATIBLE_FEAT_ENABLE +#if RSI_BLE_GATT_ASYNC_ENABLE + | SL_SI91X_BLE_GATT_ASYNC_ENABLE +#endif + ), + + .ble_ext_feature_bit_map = ((SL_SI91X_BLE_NUM_CONN_EVENTS(RSI_BLE_NUM_CONN_EVENTS) | + SL_SI91X_BLE_NUM_REC_BYTES(RSI_BLE_NUM_REC_BYTES)) +#if RSI_BLE_INDICATE_CONFIRMATION_FROM_HOST + | SL_SI91X_BLE_INDICATE_CONFIRMATION_FROM_HOST // indication response from app +#endif +#if RSI_BLE_MTU_EXCHANGE_FROM_HOST + | SL_SI91X_BLE_MTU_EXCHANGE_FROM_HOST // MTU Exchange request initiation from app +#endif +#if RSI_BLE_SET_SCAN_RESP_DATA_FROM_HOST + | (SL_SI91X_BLE_SET_SCAN_RESP_DATA_FROM_HOST) // Set SCAN Resp Data from app +#endif +#if RSI_BLE_DISABLE_CODED_PHY_FROM_HOST + | (SL_SI91X_BLE_DISABLE_CODED_PHY_FROM_HOST) // Disable Coded PHY from app +#endif +#if BLE_SIMPLE_GATT + | SL_SI91X_BLE_GATT_INIT +#endif + ), + .config_feature_bit_map = (SL_SI91X_FEAT_SLEEP_GPIO_SEL_BITMAP | RSI_CONFIG_FEATURE_BITMAP) } +}; + +constexpr int8_t kAdvScanThreshold = -40; +constexpr uint8_t kAdvRssiToleranceThreshold = 5; +constexpr uint8_t kAdvActiveScanDuration = 15; +constexpr uint8_t kAdvPassiveScanDuration = 20; +constexpr uint8_t kAdvMultiProbe = 1; +constexpr uint8_t kAdvScanPeriodicity = 10; // TODO: Confirm that this value works for size and timing -#define WFX_QUEUE_SIZE 10 +constexpr uint8_t kWfxQueueSize = 10; // TODO: Figure out why we actually need this, we are already handling failure and retries somewhere else. -#define WIFI_SCAN_TIMEOUT_TICK 10000 +constexpr uint16_t kWifiScanTimeoutTicks = 10000; -WfxRsi_t wfx_rsi; +void DHCPTimerEventHandler(void * arg) +{ + WfxEvent_t event = { .eventType = WFX_EVT_DHCP_POLL }; + sl_matter_wifi_post_event(&event); +} -bool hasNotifiedIPV6 = false; -#if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) -bool hasNotifiedIPV4 = false; -#endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ -bool hasNotifiedWifiConnectivity = false; +void CancelDHCPTimer(void) +{ + VerifyOrReturn(osTimerIsRunning(sDHCPTimer), ChipLogDetail(DeviceLayer, "CancelDHCPTimer: timer not running")); + VerifyOrReturn(osTimerStop(sDHCPTimer) == osOK, ChipLogError(DeviceLayer, "CancelDHCPTimer: failed to stop timer")); +} -volatile bool scan_results_complete = false; -volatile bool bg_scan_results_complete = false; -extern osSemaphoreId_t sl_rs_ble_init_sem; -static wfx_wifi_scan_ext_t temp_reset; -volatile sl_status_t callback_status = SL_STATUS_OK; -// Scan semaphore -static osSemaphoreId_t sScanSemaphore; -// DHCP Poll timer -static osTimerId_t sDHCPTimer; -static osMessageQueueId_t sWifiEventQueue = NULL; - -static void DHCPTimerEventHandler(void * arg) +void StartDHCPTimer(uint32_t timeout) { - WfxEvent_t event; - event.eventType = WFX_EVT_DHCP_POLL; - WfxPostEvent(&event); + // Cancel timer if already started + CancelDHCPTimer(); + + VerifyOrReturn(osTimerStart(sDHCPTimer, pdMS_TO_TICKS(timeout)) == osOK, + ChipLogError(DeviceLayer, "StartDHCPTimer: failed to start timer")); } -static void CancelDHCPTimer(void) +sl_status_t sl_wifi_siwx917_init(void) { - osStatus_t status; + sl_status_t status = SL_STATUS_OK; + +#ifdef SLI_SI91X_MCU_INTERFACE + // SoC Configurations + uint8_t xtal_enable = 1; + status = sl_si91x_m4_ta_secure_handshake(SL_SI91X_ENABLE_XTAL, 1, &xtal_enable, 0, nullptr); + VerifyOrReturnError(status == SL_STATUS_OK, status, + ChipLogError(DeviceLayer, "sl_si91x_m4_ta_secure_handshake failed: 0x%lx", static_cast(status))); + +#if CHIP_CONFIG_ENABLE_ICD_SERVER +#ifdef ENABLE_CHIP_SHELL + // While using the matter shell with a Low Power Build, GPIO 1 is used to check the UULP PIN 1 status + // since UART doesn't act as a wakeup source in the UULP mode. + + // Configuring the NPS GPIO 1 + RSI_NPSSGPIO_SetPinMux(RTE_UULP_GPIO_1_PIN, 0); + + // Configure the NPSS GPIO direction to input + RSI_NPSSGPIO_SetDir(RTE_UULP_GPIO_1_PIN, 1); + + // Enable the REN + RSI_NPSSGPIO_InputBufferEn(RTE_UULP_GPIO_1_PIN, 1); +#endif // ENABLE_CHIP_SHELL +#endif // CHIP_CONFIG_ENABLE_ICD_SERVER + +#else + // NCP Configurations + status = sl_matter_wifi_platform_init(); + VerifyOrReturnError(status == SL_STATUS_OK, status, + ChipLogError(DeviceLayer, "sl_matter_wifi_platform_init failed: 0x%lx", static_cast(status))); +#endif // SLI_SI91X_MCU_INTERFACE + + sl_wifi_firmware_version_t version = { 0 }; + status = sl_wifi_get_firmware_version(&version); + VerifyOrReturnError(status == SL_STATUS_OK, status, + ChipLogError(DeviceLayer, "sl_wifi_get_firmware_version failed: 0x%lx", static_cast(status))); + + ChipLogDetail(DeviceLayer, "Firmware version is: %x%x.%d.%d.%d.%d.%d.%d", version.chip_id, version.rom_id, version.major, + version.minor, version.security_version, version.patch_num, version.customer_id, version.build_num); + + status = sl_wifi_get_mac_address(SL_WIFI_CLIENT_INTERFACE, (sl_mac_address_t *) &wfx_rsi.sta_mac.octet[0]); + VerifyOrReturnError(status == SL_STATUS_OK, status, + ChipLogError(DeviceLayer, "sl_wifi_get_mac_address failed: 0x%lx", static_cast(status))); + +#ifdef SL_MBEDTLS_USE_TINYCRYPT + constexpr uint32_t trngKey[TRNG_KEY_SIZE] = { 0x16157E2B, 0xA6D2AE28, 0x8815F7AB, 0x3C4FCF09 }; + + // To check the Entropy of TRNG and verify TRNG functioning. + status = sl_si91x_trng_entropy(); + VerifyOrReturnError(status == SL_STATUS_OK, status, + ChipLogError(DeviceLayer, "sl_si91x_trng_entropy failed: 0x%lx", static_cast(status))); + + // Initiate and program the key required for TRNG hardware engine + status = sl_si91x_trng_program_key((uint32_t *) trngKey, TRNG_KEY_SIZE); + VerifyOrReturnError(status == SL_STATUS_OK, status, + ChipLogError(DeviceLayer, "sl_si91x_trng_program_key failed: 0x%lx", static_cast(status))); +#endif // SL_MBEDTLS_USE_TINYCRYPT + + wfx_rsi.dev_state |= WFX_RSI_ST_DEV_READY; + osSemaphoreRelease(sl_rs_ble_init_sem); + return status; +} + +// TODO: this changes will be reverted back after the Silabs WiFi SDK team fix the scan API +#ifndef EXP_BOARD +sl_status_t ScanCallback(sl_wifi_event_t event, sl_wifi_scan_result_t * scan_result, uint32_t result_length, void * arg) +{ + sl_status_t status = SL_STATUS_OK; + if (SL_WIFI_CHECK_IF_EVENT_FAILED(event)) + { + ChipLogError(DeviceLayer, "Scan Netwrok Failed: 0x%lx", *reinterpret_cast(status)); +#if WIFI_ENABLE_SECURITY_WPA3_TRANSITION + security = SL_WIFI_WPA3; +#else + security = SL_WIFI_WPA_WPA2_MIXED; +#endif /* WIFI_ENABLE_SECURITY_WPA3_TRANSITION */ - // Check if timer started - if (!osTimerIsRunning(sDHCPTimer)) + status = SL_STATUS_FAIL; + } + else { - ChipLogDetail(DeviceLayer, "CancelDHCPTimer: timer not running"); - return; + security = static_cast(scan_result->scan_info[0].security_mode); + wfx_rsi.ap_chan = scan_result->scan_info[0].rf_channel; + memcpy(&wfx_rsi.ap_mac.octet, scan_result->scan_info[0].bssid, BSSID_LEN); } - status = osTimerStop(sDHCPTimer); - if (status != osOK) + osSemaphoreRelease(sScanCompleteSemaphore); + return status; +} +#endif + +sl_status_t InitiateScan() +{ + sl_status_t status = SL_STATUS_OK; + +// TODO: this changes will be reverted back after the Silabs WiFi SDK team fix the scan API +#ifndef EXP_BOARD + sl_wifi_ssid_t ssid = { 0 }; + + // TODO: this changes will be reverted back after the Silabs WiFi SDK team fix the scan API + sl_wifi_scan_configuration_t wifi_scan_configuration = default_wifi_scan_configuration; + + ssid.length = wfx_rsi.sec.ssid_length; + + // TODO: workaround because the string management with the null termination is flawed + chip::Platform::CopyString((char *) &ssid.value[0], ssid.length + 1, wfx_rsi.sec.ssid); + sl_wifi_set_scan_callback(ScanCallback, NULL); + + osSemaphoreAcquire(sScanInProgressSemaphore, osWaitForever); + + // This is an odd success code? + status = sl_wifi_start_scan(SL_WIFI_CLIENT_2_4GHZ_INTERFACE, &ssid, &wifi_scan_configuration); + if (status == SL_STATUS_IN_PROGRESS) { - ChipLogError(DeviceLayer, "CancelDHCPTimer: failed to stop timer: %d", status); + osSemaphoreAcquire(sScanCompleteSemaphore, kWifiScanTimeoutTicks); + status = SL_STATUS_OK; } + + osSemaphoreRelease(sScanInProgressSemaphore); +#endif + + return status; } -static void StartDHCPTimer(uint32_t timeout) +sl_status_t SetWifiConfigurations() { - osStatus_t status; + sl_status_t status = SL_STATUS_OK; - // Cancel timer if already started - CancelDHCPTimer(); +#if CHIP_CONFIG_ENABLE_ICD_SERVER + // Setting the listen interval to 0 which will set it to DTIM interval + sl_wifi_listen_interval_t sleep_interval = { .listen_interval = 0 }; + status = sl_wifi_set_listen_interval(SL_WIFI_CLIENT_INTERFACE, sleep_interval); + VerifyOrReturnError(status == SL_STATUS_OK, status); + + sl_wifi_advanced_client_configuration_t client_config = { .max_retry_attempts = 5 }; + status = sl_wifi_set_advanced_client_configuration(SL_WIFI_CLIENT_INTERFACE, &client_config); + VerifyOrReturnError(status == SL_STATUS_OK, status); +#endif // CHIP_CONFIG_ENABLE_ICD_SERVER + + status = sl_net_set_credential(SL_NET_DEFAULT_WIFI_CLIENT_CREDENTIAL_ID, SL_NET_WIFI_PSK, &wfx_rsi.sec.passkey[0], + wfx_rsi.sec.passkey_length); + VerifyOrReturnError(status == SL_STATUS_OK, status); + + sl_net_wifi_client_profile_t profile = { + .config = { + .ssid = { + //static cast because the types dont match + .length = static_cast(wfx_rsi.sec.ssid_length), + }, + .channel = { + .channel = SL_WIFI_AUTO_CHANNEL, + .band = SL_WIFI_AUTO_BAND, + .bandwidth = SL_WIFI_AUTO_BANDWIDTH + }, + .bssid = {{0}}, + .bss_type = SL_WIFI_BSS_TYPE_INFRASTRUCTURE, + .security = security, + .encryption = SL_WIFI_NO_ENCRYPTION, + .client_options = SL_WIFI_JOIN_WITH_SCAN, + .credential_id = SL_NET_DEFAULT_WIFI_CLIENT_CREDENTIAL_ID, + }, + .ip = { + .mode = SL_IP_MANAGEMENT_DHCP, + .type = SL_IPV6, + .host_name = NULL, + .ip = {{{0}}}, + } + }; + // TODO: memcpy for now since the types dont match + memcpy((char *) &profile.config.ssid.value, wfx_rsi.sec.ssid, wfx_rsi.sec.ssid_length); + + status = sl_net_set_profile((sl_net_interface_t) SL_NET_WIFI_CLIENT_INTERFACE, SL_NET_DEFAULT_WIFI_CLIENT_PROFILE_ID, &profile); + VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogError(DeviceLayer, "sl_net_set_profile Failed")); + + return status; +} + +sl_status_t JoinWifiNetwork(void) +{ + VerifyOrReturnError(!(wfx_rsi.dev_state & (WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED)), SL_STATUS_IN_PROGRESS); + sl_status_t status = SL_STATUS_OK; + + // Start Join Network + wfx_rsi.dev_state |= WFX_RSI_ST_STA_CONNECTING; - status = osTimerStart(sDHCPTimer, pdMS_TO_TICKS(timeout)); - if (status != osOK) + status = SetWifiConfigurations(); + VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogError(DeviceLayer, "Failure to set the Wifi Configurations!")); + + status = sl_net_up((sl_net_interface_t) SL_NET_WIFI_CLIENT_INTERFACE, SL_NET_DEFAULT_WIFI_CLIENT_PROFILE_ID); + + if (status == SL_STATUS_OK || status == SL_STATUS_IN_PROGRESS) { - ChipLogError(DeviceLayer, "StartDHCPTimer: failed to start timer: %d", status); + WfxEvent_t event; + event.eventType = WFX_EVT_STA_CONN; + sl_matter_wifi_post_event(&event); + return status; } + + // failure only happens when the firmware returns an error + ChipLogError(DeviceLayer, "sl_wifi_connect failed: 0x%lx", static_cast(status)); + VerifyOrReturnError((wfx_rsi.join_retries <= MAX_JOIN_RETRIES_COUNT), status); + + wfx_rsi.dev_state &= ~(WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED); + ChipLogProgress(DeviceLayer, "Connection retry attempt %d", wfx_rsi.join_retries); + wfx_retry_connection(++wfx_rsi.join_retries); + + WfxEvent_t event; + event.eventType = WFX_EVT_STA_START_JOIN; + sl_matter_wifi_post_event(&event); + + return status; } +} // namespace + /****************************************************************** * @fn int32_t wfx_rsi_get_ap_info(wfx_wifi_scan_result_t *ap) * @brief @@ -223,41 +508,16 @@ int32_t wfx_rsi_reset_count(void) } /****************************************************************** - * @fn wfx_rsi_disconnect(void) + * @fn sl_wifi_platform_disconnect(void) * @brief * Getting the driver disconnect status * @param[in] None * @return * status *********************************************************************/ -int32_t wfx_rsi_disconnect(void) +int32_t sl_wifi_platform_disconnect(void) { - return sl_wifi_disconnect(SL_WIFI_CLIENT_INTERFACE); -} - -sl_status_t join_callback_handler(sl_wifi_event_t event, char * result, uint32_t result_length, void * arg) -{ - WfxEvent_t WfxEvent; - - wfx_rsi.dev_state &= ~(WFX_RSI_ST_STA_CONNECTING); - if (SL_WIFI_CHECK_IF_EVENT_FAILED(event)) - { - callback_status = *(sl_status_t *) result; - ChipLogError(DeviceLayer, "join_callback_handler: failed: 0x%lx", static_cast(callback_status)); - wfx_rsi.dev_state &= ~(WFX_RSI_ST_STA_CONNECTED); - wfx_retry_connection(++wfx_rsi.join_retries); - return SL_STATUS_FAIL; - } - /* - * Join was complete - Do the DHCP - */ - ChipLogDetail(DeviceLayer, "join_callback_handler: success"); - memset(&temp_reset, 0, sizeof(temp_reset)); - wfx_rsi.join_retries = 0; - callback_status = SL_STATUS_OK; - WfxEvent.eventType = WFX_EVT_STA_CONN; - WfxPostEvent(&WfxEvent); - return SL_STATUS_OK; + return sl_net_down((sl_net_interface_t) SL_NET_WIFI_CLIENT_INTERFACE); } #if CHIP_CONFIG_ENABLE_ICD_SERVER @@ -268,7 +528,7 @@ void sl_si91x_invoke_btn_press_event(void) // TODO: should be removed once we are getting the press interrupt for button 0 with sleep if (!RSI_NPSSGPIO_GetPin(SL_BUTTON_BTN0_PIN) && !btn0_pressed) { - sl_button_on_change(SL_BUTTON_BTN0_NUMBER, BUTTON_PRESSED); + sl_button_on_change(SL_BUTTON_BTN0_NUMBER, 1 /* Button Pressed */); btn0_pressed = true; } if (RSI_NPSSGPIO_GetPin(SL_BUTTON_BTN0_PIN)) @@ -330,206 +590,10 @@ int32_t wfx_rsi_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_ } #endif /* CHIP_CONFIG_ENABLE_ICD_SERVER */ -/************************************************************************************* - * @fn static int32_t wfx_wifi_rsi_init(void) - * @brief - * Wifi initialization called from app main - * @param[in] None - * @return - * None - *****************************************************************************************/ -int32_t wfx_wifi_rsi_init(void) -{ - ChipLogDetail(DeviceLayer, "wfx_wifi_rsi_init: started"); - sl_status_t status; - status = sl_wifi_init(&config, NULL, sl_wifi_default_event_handler); - VerifyOrReturnError(status == SL_STATUS_OK, status); - - // Create Sempaphore for scan - sScanSemaphore = osSemaphoreNew(1, 0, NULL); - VerifyOrReturnError(sScanSemaphore != NULL, SL_STATUS_ALLOCATION_FAILED); - - // Create the message queue - sWifiEventQueue = osMessageQueueNew(WFX_QUEUE_SIZE, sizeof(WfxEvent_t), NULL); - VerifyOrReturnError(sWifiEventQueue != NULL, SL_STATUS_ALLOCATION_FAILED); - - // Create timer for DHCP polling - // TODO: Use LWIP timer instead of creating a new one here - sDHCPTimer = osTimerNew(DHCPTimerEventHandler, osTimerPeriodic, NULL, NULL); - VerifyOrReturnError(sDHCPTimer != NULL, SL_STATUS_ALLOCATION_FAILED); - - return status; -} - -/************************************************************************************* - * @fn static void sl_print_firmware_version(sl_wifi_firmware_version_t*) - * @brief - * To print the firmware version - * @param[in] sl_wifi_firmware_version_t* - * @return - * None - *****************************************************************************************/ -static void sl_print_firmware_version(sl_wifi_firmware_version_t * firmware_version) -{ - ChipLogDetail(DeviceLayer, "Firmware version is: %x%x.%d.%d.%d.%d.%d.%d", firmware_version->chip_id, firmware_version->rom_id, - firmware_version->major, firmware_version->minor, firmware_version->security_version, firmware_version->patch_num, - firmware_version->customer_id, firmware_version->build_num); -} - -/************************************************************************************* - * @fn static int32_t wfx_rsi_init(void) - * @brief - * driver initialization - * @param[in] None - * @return - * None - *****************************************************************************************/ -static sl_status_t wfx_rsi_init(void) -{ - sl_status_t status; - -#ifndef SLI_SI91X_MCU_INTERFACE - status = wfx_wifi_rsi_init(); - if (status != SL_STATUS_OK) - { - ChipLogError(DeviceLayer, "wfx_rsi_init failed: 0x%lx", static_cast(status)); - return status; - } -#else // For SoC -#if CHIP_CONFIG_ENABLE_ICD_SERVER - uint8_t xtal_enable = 1; - status = sl_si91x_m4_ta_secure_handshake(SL_SI91X_ENABLE_XTAL, 1, &xtal_enable, 0, NULL); - if (status != SL_STATUS_OK) - { - ChipLogError(DeviceLayer, "sl_si91x_m4_ta_secure_handshake failed: 0x%lx", static_cast(status)); - return status; - } -#ifdef ENABLE_CHIP_SHELL - // While using the matter shell with the ICD server, the GPIO 1 is used to check the UULP PIN 1 status - // since UART doesn't act as a wakeup source in the UULP mode - /*Configuring the NPS GPIO 1*/ - RSI_NPSSGPIO_SetPinMux(RTE_UULP_GPIO_1_PIN, 0); - /*Configure the NPSS GPIO direction to input */ - RSI_NPSSGPIO_SetDir(RTE_UULP_GPIO_1_PIN, 1); - /*Enable the REN*/ - RSI_NPSSGPIO_InputBufferEn(RTE_UULP_GPIO_1_PIN, 1); -#endif // ENABLE_CHIP_SHELL -#endif /* CHIP_CONFIG_ENABLE_ICD_SERVER */ -#endif /* SLI_SI91X_MCU_INTERFACE */ - - sl_wifi_firmware_version_t version = { 0 }; - status = sl_wifi_get_firmware_version(&version); - if (status != SL_STATUS_OK) - { - ChipLogError(DeviceLayer, "sl_wifi_get_firmware_version failed: 0x%lx", static_cast(status)); - return status; - } - sl_print_firmware_version(&version); - - status = sl_wifi_get_mac_address(SL_WIFI_CLIENT_INTERFACE, (sl_mac_address_t *) &wfx_rsi.sta_mac.octet[0]); - if (status != SL_STATUS_OK) - { - ChipLogDetail(DeviceLayer, "sl_wifi_get_mac_address failed: 0x%lx", static_cast(status)); - return status; - } - -#ifdef SL_MBEDTLS_USE_TINYCRYPT - const uint32_t trngKey[TRNG_KEY_SIZE] = { 0x16157E2B, 0xA6D2AE28, 0x8815F7AB, 0x3C4FCF09 }; - - // To check the Entropy of TRNG and verify TRNG functioning. - status = sl_si91x_trng_entropy(); - if (status != SL_STATUS_OK) - { - ChipLogError(DeviceLayer, "sl_si91x_trng_entropy failed: 0x%lx", static_cast(status)); - return status; - } - - // Initiate and program the key required for TRNG hardware engine - status = sl_si91x_trng_program_key((uint32_t *) trngKey, TRNG_KEY_SIZE); - if (status != SL_STATUS_OK) - { - ChipLogError(DeviceLayer, "sl_si91x_trng_program_key failed: 0x%lx", static_cast(status)); - return status; - } -#endif // SL_MBEDTLS_USE_TINYCRYPT - - wfx_rsi.dev_state |= WFX_RSI_ST_DEV_READY; - osSemaphoreRelease(sl_rs_ble_init_sem); - return status; -} - -/************************************************************************************* - * @fn void wfx_show_err(char *msg) - * @brief - * driver shows error message - * @param[in] msg - * @return - * None - *****************************************************************************************/ -void wfx_show_err(char * msg) -{ - ChipLogError(DeviceLayer, "wfx_show_err: message: %s", msg); -} - -sl_status_t scan_callback_handler(sl_wifi_event_t event, sl_wifi_scan_result_t * scan_result, uint32_t result_length, void * arg) -{ - if (SL_WIFI_CHECK_IF_EVENT_FAILED(event)) - { - callback_status = *(sl_status_t *) scan_result; - ChipLogError(DeviceLayer, "scan_callback_handler: failed: 0x%lx", static_cast(callback_status)); - scan_results_complete = true; -#if WIFI_ENABLE_SECURITY_WPA3_TRANSITION - wfx_rsi.sec.security = WFX_SEC_WPA3; -#else - wfx_rsi.sec.security = WFX_SEC_WPA2; -#endif /* WIFI_ENABLE_SECURITY_WPA3_TRANSITION */ - - osSemaphoreRelease(sScanSemaphore); - return SL_STATUS_FAIL; - } - wfx_rsi.sec.security = WFX_SEC_UNSPECIFIED; - wfx_rsi.ap_chan = scan_result->scan_info[0].rf_channel; - memcpy(&wfx_rsi.ap_mac.octet, scan_result->scan_info[0].bssid, BSSID_LEN); - switch (scan_result->scan_info[0].security_mode) - { - case SL_WIFI_OPEN: - wfx_rsi.sec.security = WFX_SEC_NONE; - break; - case SL_WIFI_WPA: - case SL_WIFI_WPA_ENTERPRISE: - wfx_rsi.sec.security = WFX_SEC_WPA; - break; - case SL_WIFI_WPA_WPA2_MIXED: - case SL_WIFI_WPA2: - case SL_WIFI_WPA2_ENTERPRISE: - wfx_rsi.sec.security = WFX_SEC_WPA2; - break; - case SL_WIFI_WEP: - wfx_rsi.sec.security = WFX_SEC_WEP; - break; - case SL_WIFI_WPA3_TRANSITION: -#if WIFI_ENABLE_SECURITY_WPA3_TRANSITION - case SL_WIFI_WPA3: - wfx_rsi.sec.security = WFX_SEC_WPA3; -#else - wfx_rsi.sec.security = WFX_SEC_WPA2; -#endif /* WIFI_ENABLE_SECURITY_WPA3_TRANSITION */ - break; - default: - wfx_rsi.sec.security = WFX_SEC_UNSPECIFIED; - break; - } - wfx_rsi.dev_state &= ~WFX_RSI_ST_SCANSTARTED; - scan_results_complete = true; - - osSemaphoreRelease(sScanSemaphore); - return SL_STATUS_OK; -} - sl_status_t show_scan_results(sl_wifi_scan_result_t * scan_result) { SL_WIFI_ARGS_CHECK_NULL_POINTER(scan_result); - VerifyOrReturnError(wfx_rsi.scan_cb != NULL, SL_STATUS_INVALID_HANDLE); + VerifyOrReturnError(wfx_rsi.scan_cb != nullptr, SL_STATUS_INVALID_HANDLE); wfx_wifi_scan_result_t cur_scan_result; for (int idx = 0; idx < (int) scan_result->scan_count; idx++) @@ -541,7 +605,7 @@ sl_status_t show_scan_results(sl_wifi_scan_result_t * scan_result) chip::Platform::CopyString(cur_scan_result.ssid, cur_scan_result.ssid_length, (char *) scan_result->scan_info[idx].ssid); // if user has provided ssid, then check if the current scan result ssid matches the user provided ssid - if (wfx_rsi.scan_ssid != NULL && + if (wfx_rsi.scan_ssid != nullptr && (strncmp(wfx_rsi.scan_ssid, cur_scan_result.ssid, std::min(strlen(wfx_rsi.scan_ssid), strlen(cur_scan_result.ssid))) == CMP_SUCCESS)) { @@ -553,7 +617,7 @@ sl_status_t show_scan_results(sl_wifi_scan_result_t * scan_result) wfx_rsi.scan_cb(&cur_scan_result); // if user has not provided the ssid, then call the callback for each scan result - if (wfx_rsi.scan_ssid == NULL) + if (wfx_rsi.scan_ssid == nullptr) { continue; } @@ -567,135 +631,17 @@ sl_status_t show_scan_results(sl_wifi_scan_result_t * scan_result) if (wfx_rsi.scan_ssid) { chip::Platform::MemoryFree(wfx_rsi.scan_ssid); - wfx_rsi.scan_ssid = NULL; + wfx_rsi.scan_ssid = nullptr; } return SL_STATUS_OK; } sl_status_t bg_scan_callback_handler(sl_wifi_event_t event, sl_wifi_scan_result_t * result, uint32_t result_length, void * arg) { - callback_status = show_scan_results(result); - bg_scan_results_complete = true; - osSemaphoreRelease(sScanSemaphore); + show_scan_results(result); // To do Check error + osSemaphoreRelease(sScanCompleteSemaphore); return SL_STATUS_OK; } -/*************************************************************************************** - * @fn static void wfx_rsi_save_ap_info(void) - * @brief - * Saving the details of the AP - * @param[in] None - * @return - * None - *******************************************************************************************/ -static void wfx_rsi_save_ap_info(void) // translation -{ - sl_status_t status = SL_STATUS_OK; -#ifndef EXP_BOARD - // TODO: this changes will be reverted back after the Silabs WiFi SDK team fix the scan API - sl_wifi_scan_configuration_t wifi_scan_configuration = default_wifi_scan_configuration; -#endif - sl_wifi_ssid_t ssid_arg; - memset(&ssid_arg, 0, sizeof(ssid_arg)); - ssid_arg.length = wfx_rsi.sec.ssid_length; - chip::Platform::CopyString((char *) &ssid_arg.value[0], ssid_arg.length, wfx_rsi.sec.ssid); - sl_wifi_set_scan_callback(scan_callback_handler, NULL); - scan_results_complete = false; -#ifndef EXP_BOARD - // TODO: this changes will be reverted back after the Silabs WiFi SDK team fix the scan API - status = sl_wifi_start_scan(SL_WIFI_CLIENT_2_4GHZ_INTERFACE, &ssid_arg, &wifi_scan_configuration); -#endif - if (SL_STATUS_IN_PROGRESS == status) - { - osSemaphoreAcquire(sScanSemaphore, WIFI_SCAN_TIMEOUT_TICK); - } -} - -/******************************************************************************************** - * @fn static void wfx_rsi_do_join(void) - * @brief - * Start an async Join command - * @return - * None - **********************************************************************************************/ -static sl_status_t wfx_rsi_do_join(void) -{ - VerifyOrReturnError(!(wfx_rsi.dev_state & (WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED)), SL_STATUS_IN_PROGRESS); - sl_status_t status = SL_STATUS_OK; - sl_wifi_client_configuration_t ap; - memset(&ap, 0, sizeof(ap)); - - switch (wfx_rsi.sec.security) - { - case WFX_SEC_WEP: - ap.security = SL_WIFI_WEP; - break; - case WFX_SEC_WPA: - ap.security = SL_WIFI_WPA_WPA2_MIXED; - break; - case WFX_SEC_WPA2: -#if WIFI_ENABLE_SECURITY_WPA3_TRANSITION - ap.security = SL_WIFI_WPA3_TRANSITION; - break; - case WFX_SEC_WPA3: - ap.security = SL_WIFI_WPA3_TRANSITION; -#else - ap.security = SL_WIFI_WPA_WPA2_MIXED; -#endif // WIFI_ENABLE_SECURITY_WPA3_TRANSITION - break; - case WFX_SEC_NONE: - ap.security = SL_WIFI_OPEN; - break; - default: - ChipLogError(DeviceLayer, "wfx_rsi_do_join: unknown security type."); - return status; - } - /* - * Join the network - */ - wfx_rsi.dev_state |= WFX_RSI_ST_STA_CONNECTING; - status = sl_wifi_set_join_callback(join_callback_handler, NULL); - VerifyOrReturnError(status == SL_STATUS_OK, status); - -#if CHIP_CONFIG_ENABLE_ICD_SERVER - // Setting the listen interval to 0 which will set it to DTIM interval - sl_wifi_listen_interval_t sleep_interval = { .listen_interval = 0 }; - status = sl_wifi_set_listen_interval(SL_WIFI_CLIENT_INTERFACE, sleep_interval); - VerifyOrReturnError(status == SL_STATUS_OK, status); - - sl_wifi_advanced_client_configuration_t client_config = { .max_retry_attempts = 5 }; - status = sl_wifi_set_advanced_client_configuration(SL_WIFI_CLIENT_INTERFACE, &client_config); - VerifyOrReturnError(status == SL_STATUS_OK, status); -#endif // CHIP_CONFIG_ENABLE_ICD_SERVER - sl_net_credential_id_t id = SL_NET_DEFAULT_WIFI_CLIENT_CREDENTIAL_ID; - status = sl_net_set_credential(id, SL_NET_WIFI_PSK, &wfx_rsi.sec.passkey[0], wfx_rsi.sec.passkey_length); - VerifyOrReturnError(status == SL_STATUS_OK, status); - - uint32_t timeout_ms = 0; - ap.ssid.length = wfx_rsi.sec.ssid_length; - ap.encryption = SL_WIFI_NO_ENCRYPTION; - ap.credential_id = id; - memcpy((char *) &ap.ssid.value[0], wfx_rsi.sec.ssid, wfx_rsi.sec.ssid_length); - ChipLogDetail(DeviceLayer, "wfx_rsi_do_join: SSID: %s, SECURITY: %d(%d)", ap.ssid.value, ap.security, wfx_rsi.sec.security); - - status = sl_wifi_connect(SL_WIFI_CLIENT_INTERFACE, &ap, timeout_ms); - // sl_wifi_connect returns SL_STATUS_IN_PROGRESS if join is in progress - // after the initial scan is done, the scan does not check for SSID - VerifyOrReturnError(status != SL_STATUS_OK && status != SL_STATUS_IN_PROGRESS, status); - - // failure only happens when the firmware returns an error - ChipLogError(DeviceLayer, "wfx_rsi_do_join: sl_wifi_connect failed: 0x%lx", static_cast(status)); - VerifyOrReturnError((wfx_rsi.join_retries <= MAX_JOIN_RETRIES_COUNT), status); - - wfx_rsi.dev_state &= ~(WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED); - ChipLogProgress(DeviceLayer, "wfx_rsi_do_join: retry attempt %d", wfx_rsi.join_retries); - wfx_retry_connection(++wfx_rsi.join_retries); - - WfxEvent_t event; - event.eventType = WFX_EVT_STA_START_JOIN; - WfxPostEvent(&event); - - return status; -} /// NotifyConnectivity /// @brief Notify the application about the connectivity status if it has not been notified yet. @@ -709,16 +655,12 @@ void NotifyConnectivity(void) void HandleDHCPPolling(void) { - struct netif * sta_netif; WfxEvent_t event; - sta_netif = wfx_get_netif(SL_WFX_STA_INTERFACE); - if (sta_netif == NULL) - { - // TODO: Notify the application that the interface is not set up or Chipdie here because we are in an unkonwn state - ChipLogError(DeviceLayer, "HandleDHCPPolling: failed to get STA netif"); - return; - } + // TODO: Notify the application that the interface is not set up or Chipdie here because we are in an unkonwn state + struct netif * sta_netif = &wifi_client_context.netif; + VerifyOrReturn(sta_netif != nullptr, ChipLogError(DeviceLayer, "HandleDHCPPolling: failed to get STA netif")); + #if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) uint8_t dhcp_state = dhcpclient_poll(sta_netif); if (dhcp_state == DHCP_ADDRESS_ASSIGNED && !hasNotifiedIPV4) @@ -726,7 +668,7 @@ void HandleDHCPPolling(void) wfx_dhcp_got_ipv4((uint32_t) sta_netif->ip_addr.u_addr.ip4.addr); hasNotifiedIPV4 = true; event.eventType = WFX_EVT_STA_DHCP_DONE; - WfxPostEvent(&event); + sl_matter_wifi_post_event(&event); NotifyConnectivity(); } else if (dhcp_state == DHCP_OFF) @@ -741,23 +683,21 @@ void HandleDHCPPolling(void) if ((ip6_addr_ispreferred(netif_ip6_addr_state(sta_netif, 0))) && !hasNotifiedIPV6) { char addrStr[chip::Inet::IPAddress::kMaxStringLength] = { 0 }; - VerifyOrReturn(ip6addr_ntoa_r(netif_ip6_addr(sta_netif, 0), addrStr, sizeof(addrStr)) != NULL); + VerifyOrReturn(ip6addr_ntoa_r(netif_ip6_addr(sta_netif, 0), addrStr, sizeof(addrStr)) != nullptr); ChipLogProgress(DeviceLayer, "SLAAC OK: linklocal addr: %s", addrStr); wfx_ipv6_notify(GET_IPV6_SUCCESS); hasNotifiedIPV6 = true; event.eventType = WFX_EVT_STA_DHCP_DONE; - WfxPostEvent(&event); + sl_matter_wifi_post_event(&event); NotifyConnectivity(); } } -void WfxPostEvent(WfxEvent_t * event) +void sl_matter_wifi_post_event(WfxEvent_t * event) { - sl_status_t status = osMessageQueuePut(sWifiEventQueue, event, 0, 0); - - if (status != osOK) + if (osMessageQueuePut(sWifiEventQueue, event, 0, 0) != osOK) { - ChipLogError(DeviceLayer, "WfxPostEvent: failed to post event: 0x%lx", static_cast(status)); + ChipLogError(DeviceLayer, "sl_matter_wifi_post_event: failed to post event.") // TODO: Handle error, requeue event depending on queue size or notify relevant task, Chipdie, etc. } } @@ -776,7 +716,7 @@ void ResetDHCPNotificationFlags(void) hasNotifiedWifiConnectivity = false; outEvent.eventType = WFX_EVT_STA_DO_DHCP; - WfxPostEvent(&outEvent); + sl_matter_wifi_post_event(&outEvent); } void ProcessEvent(WfxEvent_t inEvent) @@ -788,13 +728,9 @@ void ProcessEvent(WfxEvent_t inEvent) ChipLogDetail(DeviceLayer, "WFX_EVT_STA_CONN"); wfx_rsi.dev_state |= WFX_RSI_ST_STA_CONNECTED; ResetDHCPNotificationFlags(); - wfx_lwip_set_sta_link_up(); - /* We need to get AP Mac - TODO */ - // Uncomment once the hook into MATTER is moved to IP connectivty instead - // of AP connectivity. - // wfx_connected_notify(0, &wfx_rsi.ap_mac); // This - // is independant of IP connectivity. + break; + case WFX_EVT_STA_DISCONN: ChipLogDetail(DeviceLayer, "WFX_EVT_STA_DISCONN"); // TODO: This event is not being posted anywhere, seems to be a dead code or we are missing something @@ -802,20 +738,23 @@ void ProcessEvent(WfxEvent_t inEvent) ~(WFX_RSI_ST_STA_READY | WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED | WFX_RSI_ST_STA_DHCP_DONE); /* TODO: Implement disconnect notify */ ResetDHCPNotificationFlags(); - wfx_lwip_set_sta_link_down(); // Internally dhcpclient_poll(netif) -> - // wfx_ip_changed_notify(0) for IPV4 #if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) + wfx_ip_changed_notify(0); // for IPV4 wfx_ip_changed_notify(IP_STATUS_FAIL); #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ wfx_ipv6_notify(GET_IPV6_FAIL); break; + case WFX_EVT_AP_START: // TODO: Currently unimplemented break; case WFX_EVT_AP_STOP: // TODO: Currently unimplemented break; + case WFX_EVT_SCAN: + ChipLogDetail(DeviceLayer, "WFX_EVT_SCAN"); + #ifdef SL_WFX_CONFIG_SCAN if (!(wfx_rsi.dev_state & WFX_RSI_ST_SCANSTARTED)) { @@ -826,11 +765,11 @@ void ProcessEvent(WfxEvent_t inEvent) // TODO: Add scan logic sl_wifi_advanced_scan_configuration_t advanced_scan_configuration = { 0 }; int32_t status; - advanced_scan_configuration.active_channel_time = ADV_ACTIVE_SCAN_DURATION; - advanced_scan_configuration.passive_channel_time = ADV_PASSIVE_SCAN_DURATION; - advanced_scan_configuration.trigger_level = ADV_SCAN_THRESHOLD; - advanced_scan_configuration.trigger_level_change = ADV_RSSI_TOLERANCE_THRESHOLD; - advanced_scan_configuration.enable_multi_probe = ADV_MULTIPROBE; + advanced_scan_configuration.active_channel_time = kAdvActiveScanDuration; + advanced_scan_configuration.passive_channel_time = kAdvPassiveScanDuration; + advanced_scan_configuration.trigger_level = kAdvScanThreshold; + advanced_scan_configuration.trigger_level_change = kAdvRssiToleranceThreshold; + advanced_scan_configuration.enable_multi_probe = kAdvMultiProbe; status = sl_wifi_set_advanced_scan_configuration(&advanced_scan_configuration); if (SL_STATUS_OK != status) { @@ -843,44 +782,86 @@ void ProcessEvent(WfxEvent_t inEvent) { /* Terminate with end of scan which is no ap sent back */ wifi_scan_configuration.type = SL_WIFI_SCAN_TYPE_ADV_SCAN; - wifi_scan_configuration.periodic_scan_interval = ADV_SCAN_PERIODICITY; + wifi_scan_configuration.periodic_scan_interval = kAdvScanPeriodicity; } else { wifi_scan_configuration = default_wifi_scan_configuration; } - sl_wifi_set_scan_callback(bg_scan_callback_handler, NULL); - scan_results_complete = false; + sl_wifi_set_scan_callback(bg_scan_callback_handler, nullptr); wfx_rsi.dev_state |= WFX_RSI_ST_SCANSTARTED; - status = sl_wifi_start_scan(SL_WIFI_CLIENT_2_4GHZ_INTERFACE, NULL, &wifi_scan_configuration); + + osSemaphoreAcquire(sScanInProgressSemaphore, osWaitForever); + status = sl_wifi_start_scan(SL_WIFI_CLIENT_2_4GHZ_INTERFACE, nullptr, &wifi_scan_configuration); if (SL_STATUS_IN_PROGRESS == status) { - osSemaphoreAcquire(sScanSemaphore, WIFI_SCAN_TIMEOUT_TICK); + osSemaphoreAcquire(sScanCompleteSemaphore, kWifiScanTimeoutTicks); } + + osSemaphoreRelease(sScanInProgressSemaphore); } break; #endif /* SL_WFX_CONFIG_SCAN */ case WFX_EVT_STA_START_JOIN: - // saving the AP related info - wfx_rsi_save_ap_info(); + ChipLogDetail(DeviceLayer, "WFX_EVT_STA_START_JOIN"); + + // Trigger Netwrok scan + InitiateScan(); + // Joining to the network - wfx_rsi_do_join(); + JoinWifiNetwork(); break; + case WFX_EVT_STA_DO_DHCP: + ChipLogDetail(DeviceLayer, "WFX_EVT_STA_DO_DHCP"); StartDHCPTimer(WFX_RSI_DHCP_POLL_INTERVAL); break; case WFX_EVT_STA_DHCP_DONE: + ChipLogDetail(DeviceLayer, "WFX_EVT_STA_DHCP_DONE"); CancelDHCPTimer(); break; case WFX_EVT_DHCP_POLL: + ChipLogDetail(DeviceLayer, "WFX_EVT_DHCP_POLL"); HandleDHCPPolling(); default: break; } } +/** + * @brief Wifi initialization called from app main + * + * @return sl_status_t Returns underlying Wi-Fi initialization error + */ +sl_status_t sl_matter_wifi_platform_init(void) +{ + sl_status_t status = SL_STATUS_OK; + + status = sl_net_init((sl_net_interface_t) SL_NET_WIFI_CLIENT_INTERFACE, &config, &wifi_client_context, nullptr); + VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogError(DeviceLayer, "sl_net_init failed: %lx", status)); + + // Create Sempaphore for scan completion + sScanCompleteSemaphore = osSemaphoreNew(1, 0, nullptr); + VerifyOrReturnError(sScanCompleteSemaphore != nullptr, SL_STATUS_ALLOCATION_FAILED); + + // Create Semaphore for scan in-progress protection + sScanInProgressSemaphore = osSemaphoreNew(1, 1, nullptr); + VerifyOrReturnError(sScanCompleteSemaphore != nullptr, SL_STATUS_ALLOCATION_FAILED); + + // Create the message queue + sWifiEventQueue = osMessageQueueNew(kWfxQueueSize, sizeof(WfxEvent_t), nullptr); + VerifyOrReturnError(sWifiEventQueue != nullptr, SL_STATUS_ALLOCATION_FAILED); + + // Create timer for DHCP polling + // TODO: Use LWIP timer instead of creating a new one here + sDHCPTimer = osTimerNew(DHCPTimerEventHandler, osTimerPeriodic, nullptr, nullptr); + VerifyOrReturnError(sDHCPTimer != nullptr, SL_STATUS_ALLOCATION_FAILED); + + return status; +} + /********************************************************************************* - * @fn void wfx_rsi_task(void *arg) + * @fn void sl_matter_wifi_task(void *arg) * @brief * The main WLAN task - started by wfx_wifi_start() that interfaces with RSI. * The rest of RSI stuff come in call-backs. @@ -890,31 +871,29 @@ void ProcessEvent(WfxEvent_t inEvent) * None **********************************************************************************/ /* ARGSUSED */ -void wfx_rsi_task(void * arg) +void sl_matter_wifi_task(void * arg) { (void) arg; - sl_status_t status = wfx_rsi_init(); - WfxEvent_t wfxEvent; - if (status != RSI_SUCCESS) - { - ChipLogError(DeviceLayer, "wfx_rsi_task: wfx_rsi_init failed: 0x%lx", static_cast(status)); - return; - } - wfx_lwip_start(); - wfx_started_notify(); + sl_status_t status = SL_STATUS_OK; + + status = sl_wifi_siwx917_init(); + VerifyOrReturn( + status == SL_STATUS_OK, + ChipLogError(DeviceLayer, "sl_matter_wifi_task: sl_wifi_siwx917_init failed: 0x%lx", static_cast(status))); + + sl_matter_wifi_task_started(); - ChipLogDetail(DeviceLayer, "wfx_rsi_task: starting event loop"); + ChipLogDetail(DeviceLayer, "sl_matter_wifi_task: starting event loop"); for (;;) { - status = osMessageQueueGet(sWifiEventQueue, &wfxEvent, NULL, osWaitForever); - if (status == osOK) + if (osMessageQueueGet(sWifiEventQueue, &wfxEvent, nullptr, osWaitForever) == osOK) { ProcessEvent(wfxEvent); } else { - ChipLogError(DeviceLayer, "wfx_rsi_task: get event failed: 0x%lx", static_cast(status)); + ChipLogError(DeviceLayer, "sl_matter_wifi_task: get event failed: 0x%lx", static_cast(status)); } } } diff --git a/examples/platform/silabs/efr32/BUILD.gn b/examples/platform/silabs/efr32/BUILD.gn index 2d417c22c1a641..9e6b700cfde727 100644 --- a/examples/platform/silabs/efr32/BUILD.gn +++ b/examples/platform/silabs/efr32/BUILD.gn @@ -18,8 +18,8 @@ import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/icd/icd.gni") import("${chip_root}/src/lib/lib.gni") import("${chip_root}/src/platform/device.gni") -import("${efr32_sdk_build_root}/efr32_sdk.gni") -import("${efr32_sdk_build_root}/silabs_board.gni") +import("${silabs_sdk_build_root}/efr32_sdk.gni") +import("${silabs_sdk_build_root}/silabs_board.gni") declare_args() { enable_heap_monitoring = false @@ -111,10 +111,10 @@ source_set("openthread_core_config_efr32_chip_examples") { if (chip_enable_openthread) { sources = [ "project_include/OpenThreadConfig.h" ] - public_deps = [ "${efr32_sdk_build_root}:efr32_sdk" ] + public_deps = [ "${silabs_sdk_build_root}:silabs_sdk" ] if (use_silabs_thread_lib) { - public_deps += [ "${efr32_sdk_build_root}:openthread_core_config_efr32" ] + public_deps += [ "${silabs_sdk_build_root}:openthread_core_config_efr32" ] } else { public_deps += [ "${chip_root}/third_party/openthread/platforms/efr32:openthread_core_config_efr32" ] } @@ -207,7 +207,7 @@ source_set("efr32-common") { public_deps = [] public_configs = [ ":efr32-common-config", - "${efr32_sdk_build_root}:silabs_config", + "${silabs_sdk_build_root}:silabs_config", ":chip_examples_project_config", ] diff --git a/examples/platform/silabs/efr32/rs911x/rs9117.gni b/examples/platform/silabs/efr32/rs911x/rs9117.gni index cff3e3da1fea8c..1adf21a6168d58 100644 --- a/examples/platform/silabs/efr32/rs911x/rs9117.gni +++ b/examples/platform/silabs/efr32/rs911x/rs9117.gni @@ -1,9 +1,9 @@ import("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") -import("${efr32_sdk_build_root}/efr32_sdk.gni") +import("${silabs_sdk_build_root}/efr32_sdk.gni") rs911x_src_plat = [ - "${examples_plat_dir}/rs911x/sl_wifi_if.cpp", + "${chip_root}/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp", "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_interrupt.c", "${examples_plat_dir}/rs911x/hal/sl_si91x_ncp_utility.c", "${examples_plat_dir}/rs911x/hal/efx32_ncp_host.c", @@ -30,6 +30,9 @@ rs9117_src_sapi = [ "${wifi_sdk_root}/components/device/silabs/si91x/wireless/ncp_interface/spi/sl_si91x_spi.c", "${wifi_sdk_root}/components/device/silabs/si91x/wireless/ncp_interface/sl_si91x_ncp_driver.c", + # Wi-Fi Config - Using the file sdk support until the wiseconnect file is fixed + "${sdk_support_root}/components/service/network_manager/src/sl_net_for_lwip.c", + # wifi component "${wifi_sdk_root}/components/protocol/wifi/src/sl_wifi_callback_framework.c", "${wifi_sdk_root}/components/protocol/wifi/si91x/sl_wifi.c", diff --git a/examples/platform/silabs/efr32/rs911x/rs911x.gni b/examples/platform/silabs/efr32/rs911x/rs911x.gni index b25fbefc8e43b6..c2a20607cc67bd 100644 --- a/examples/platform/silabs/efr32/rs911x/rs911x.gni +++ b/examples/platform/silabs/efr32/rs911x/rs911x.gni @@ -1,6 +1,6 @@ import("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") -import("${efr32_sdk_build_root}/efr32_sdk.gni") +import("${silabs_sdk_build_root}/efr32_sdk.gni") rs911x_src_plat = [ "${examples_plat_dir}/rs911x/rsi_if.cpp", diff --git a/examples/platform/silabs/efr32/rs911x/rsi_if.cpp b/examples/platform/silabs/efr32/rs911x/rsi_if.cpp index 78d13498efa5ab..7c727e013e235c 100644 --- a/examples/platform/silabs/efr32/rs911x/rsi_if.cpp +++ b/examples/platform/silabs/efr32/rs911x/rsi_if.cpp @@ -50,6 +50,7 @@ extern "C" { #endif #include "dhcp_client.h" +#include "ethernetif.h" #include "lwip/nd6.h" #include "silabs_utils.h" #include "wfx_rsi.h" @@ -109,7 +110,7 @@ static void DHCPTimerEventHandler(void * arg) { WfxEvent_t event; event.eventType = WFX_EVT_DHCP_POLL; - WfxPostEvent(&event); + sl_matter_wifi_post_event(&event); } static void CancelDHCPTimer(void) @@ -226,14 +227,14 @@ int32_t wfx_rsi_reset_count(void) } /****************************************************************** - * @fn wfx_rsi_disconnect(void) + * @fn sl_wifi_platform_disconnect(void) * @brief * Getting the driver disconnect status * @param[in] None * @return * status *********************************************************************/ -int32_t wfx_rsi_disconnect(void) +int32_t sl_wifi_platform_disconnect(void) { return rsi_wlan_disconnect(); } @@ -301,7 +302,7 @@ static void wfx_rsi_join_cb(uint16_t status, const uint8_t * buf, const uint16_t ChipLogProgress(DeviceLayer, "wfx_rsi_join_cb: success"); memset(&temp_reset, 0, sizeof(wfx_wifi_scan_ext_t)); WfxEvent.eventType = WFX_EVT_STA_CONN; - WfxPostEvent(&WfxEvent); + sl_matter_wifi_post_event(&WfxEvent); wfx_rsi.join_retries = 0; } @@ -322,7 +323,7 @@ static void wfx_rsi_join_fail_cb(uint16_t status, uint8_t * buf, uint32_t len) wfx_rsi.join_retries += 1; wfx_rsi.dev_state &= ~(WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED); WfxEvent.eventType = WFX_EVT_STA_START_JOIN; - WfxPostEvent(&WfxEvent); + sl_matter_wifi_post_event(&WfxEvent); } /************************************************************************************* * @fn wfx_rsi_wlan_pkt_cb(uint16_t status, uint8_t *buf, uint32_t len) @@ -344,31 +345,30 @@ static void wfx_rsi_wlan_pkt_cb(uint16_t status, uint8_t * buf, uint32_t len) } /************************************************************************************* - * @fn static int32_t wfx_rsi_init(void) + * @fn static int32_t sl_matter_wifi_init(void) * @brief * driver initialization * @param[in] None * @return * None *****************************************************************************************/ -static int32_t wfx_rsi_init(void) +static int32_t sl_matter_wifi_init(void) { int32_t status; uint8_t buf[RSI_RESPONSE_HOLD_BUFF_SIZE]; extern void rsi_hal_board_init(void); - ChipLogProgress(DeviceLayer, "wfx_rsi_init: starting(HEAP_SZ = %d)", SL_HEAP_SIZE); //! Driver initialization status = rsi_driver_init(wfx_rsi_drv_buf, WFX_RSI_BUF_SZ); if ((status < RSI_DRIVER_STATUS) || (status > WFX_RSI_BUF_SZ)) { - ChipLogError(DeviceLayer, "wfx_rsi_init: rsi_driver_init failed: %ld", status); + ChipLogError(DeviceLayer, "rsi_driver_init failed: %ld", status); return status; } /* ! Redpine module intialisation */ if ((status = rsi_device_init(LOAD_NWP_FW)) != RSI_SUCCESS) { - ChipLogError(DeviceLayer, "wfx_rsi_init: rsi_device_init failed: %ld", status); + ChipLogError(DeviceLayer, "rsi_device_init failed: %ld", status); return status; } /* @@ -377,7 +377,7 @@ static int32_t wfx_rsi_init(void) sDrvThread = osThreadNew(rsi_wireless_driver_task_wrapper, NULL, &kDrvTaskAttr); if (NULL == sDrvThread) { - ChipLogError(DeviceLayer, "wfx_rsi_init: failed to create task"); + ChipLogError(DeviceLayer, "failed to create task"); return RSI_ERROR_INVALID_PARAM; } @@ -388,7 +388,7 @@ static int32_t wfx_rsi_init(void) if ((status = rsi_wireless_init(OPER_MODE_0, COEX_MODE_0)) != RSI_SUCCESS) { #endif - ChipLogError(DeviceLayer, "wfx_rsi_init: rsi_wireless_init failed: %ld", status); + ChipLogError(DeviceLayer, "rsi_wireless_init failed: %ld", status); return status; } @@ -397,7 +397,7 @@ static int32_t wfx_rsi_init(void) */ if (rsi_wlan_get(RSI_FW_VERSION, buf, sizeof(buf)) != RSI_SUCCESS) { - ChipLogError(DeviceLayer, "wfx_rsi_init: rsi_wlan_get(RSI_FW_VERSION) failed: %ld", status); + ChipLogError(DeviceLayer, "rsi_wlan_get(RSI_FW_VERSION) failed: %ld", status); return status; } @@ -415,13 +415,12 @@ static int32_t wfx_rsi_init(void) (void) rsi_wlan_radio_init(); /* Required so we can get MAC address */ if ((status = rsi_wlan_get(RSI_MAC_ADDRESS, &wfx_rsi.sta_mac.octet[0], RESP_BUFF_SIZE)) != RSI_SUCCESS) { - ChipLogError(DeviceLayer, "wfx_rsi_init: rsi_wlan_get(RSI_MAC_ADDRESS) failed: %ld", status); + ChipLogError(DeviceLayer, "rsi_wlan_get(RSI_MAC_ADDRESS) failed: %ld", status); return status; } - ChipLogDetail(DeviceLayer, "wfx_rsi_init: MAC: %02x:%02x:%02x %02x:%02x:%02x", wfx_rsi.sta_mac.octet[0], - wfx_rsi.sta_mac.octet[1], wfx_rsi.sta_mac.octet[2], wfx_rsi.sta_mac.octet[3], wfx_rsi.sta_mac.octet[4], - wfx_rsi.sta_mac.octet[5]); + ChipLogDetail(DeviceLayer, "MAC: %02x:%02x:%02x %02x:%02x:%02x", wfx_rsi.sta_mac.octet[0], wfx_rsi.sta_mac.octet[1], + wfx_rsi.sta_mac.octet[2], wfx_rsi.sta_mac.octet[3], wfx_rsi.sta_mac.octet[4], wfx_rsi.sta_mac.octet[5]); // Create the message queue sWifiEventQueue = osMessageQueueNew(WFX_QUEUE_SIZE, sizeof(WfxEvent_t), NULL); @@ -443,12 +442,12 @@ static int32_t wfx_rsi_init(void) */ if ((status = rsi_wlan_register_callbacks(RSI_JOIN_FAIL_CB, wfx_rsi_join_fail_cb)) != RSI_SUCCESS) { - ChipLogError(DeviceLayer, "wfx_rsi_init: rsi_wlan_register_callbacks failed: %ld", status); + ChipLogError(DeviceLayer, "rsi_wlan_register_callbacks failed: %ld", status); return status; } if ((status = rsi_wlan_register_callbacks(RSI_WLAN_DATA_RECEIVE_NOTIFY_CB, wfx_rsi_wlan_pkt_cb)) != RSI_SUCCESS) { - ChipLogError(DeviceLayer, "wfx_rsi_init: rsi_wlan_register_callbacks failed: %ld", status); + ChipLogError(DeviceLayer, "rsi_wlan_register_callbacks failed: %ld", status); return status; } @@ -457,7 +456,6 @@ static int32_t wfx_rsi_init(void) #endif wfx_rsi.dev_state |= WFX_RSI_ST_DEV_READY; - ChipLogProgress(DeviceLayer, "wfx_rsi_init: success"); return RSI_SUCCESS; } @@ -530,20 +528,20 @@ static void wfx_rsi_save_ap_info(void) // translation } /******************************************************************************************** - * @fn static void wfx_rsi_do_join(void) + * @fn static void sl_wifi_platform_join_network(void) * @brief * Start an async Join command * @return * None **********************************************************************************************/ -static void wfx_rsi_do_join(void) +static void sl_wifi_platform_join_network(void) { - int32_t status; + int32_t status = SL_STATUS_OK; rsi_security_mode_t connect_security_mode; if (wfx_rsi.dev_state & (WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED)) { - ChipLogProgress(DeviceLayer, "wfx_rsi_do_join: already in progress"); + ChipLogProgress(DeviceLayer, "sl_wifi_platform_join_network: already in progress"); return; } @@ -566,11 +564,12 @@ static void wfx_rsi_do_join(void) connect_security_mode = RSI_OPEN; break; default: - ChipLogError(DeviceLayer, "wfx_rsi_do_join: error: unknown security type."); + ChipLogError(DeviceLayer, "sl_wifi_platform_join_network: error: unknown security type."); return; } - ChipLogProgress(DeviceLayer, "wfx_rsi_do_join: connecting to %s, sec=%d", &wfx_rsi.sec.ssid[0], wfx_rsi.sec.security); + ChipLogProgress(DeviceLayer, "sl_wifi_platform_join_network: connecting to %s, sec=%d", &wfx_rsi.sec.ssid[0], + wfx_rsi.sec.security); /* * Join the network @@ -582,7 +581,7 @@ static void wfx_rsi_do_join(void) if ((status = rsi_wlan_register_callbacks(RSI_JOIN_FAIL_CB, wfx_rsi_join_fail_cb)) != RSI_SUCCESS) { - ChipLogError(DeviceLayer, "wfx_rsi_do_join: rsi_wlan_register_callbacks failed: %ld", status); + ChipLogError(DeviceLayer, "sl_wifi_platform_join_network: rsi_wlan_register_callbacks failed: %ld", status); } /* Try to connect Wifi with given Credentials @@ -592,7 +591,8 @@ static void wfx_rsi_do_join(void) wfx_rsi_join_cb)) != RSI_SUCCESS) { wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_CONNECTING; - ChipLogProgress(DeviceLayer, "wfx_rsi_do_join: rsi_wlan_connect_async failed: %ld on try %d", status, wfx_rsi.join_retries); + ChipLogProgress(DeviceLayer, "sl_wifi_platform_join_network: rsi_wlan_connect_async failed: %ld on try %d", status, + wfx_rsi.join_retries); wfx_retry_connection(++wfx_rsi.join_retries); } } @@ -645,7 +645,7 @@ void HandleDHCPPolling(void) wfx_ipv6_notify(GET_IPV6_SUCCESS); hasNotifiedIPV6 = true; event.eventType = WFX_EVT_STA_DHCP_DONE; - WfxPostEvent(&event); + sl_matter_wifi_post_event(&event); NotifyConnectivity(); } } @@ -665,19 +665,16 @@ void ResetDHCPNotificationFlags(void) hasNotifiedWifiConnectivity = false; outEvent.eventType = WFX_EVT_STA_DO_DHCP; - WfxPostEvent(&outEvent); + sl_matter_wifi_post_event(&outEvent); } -/** - * @brief Post the WfxEvent to tue WiFiEventQueue to be process by the wfx_rsi_task - */ -void WfxPostEvent(WfxEvent_t * event) +void sl_matter_wifi_post_event(WfxEvent_t * event) { sl_status_t status = osMessageQueuePut(sWifiEventQueue, event, 0, 0); if (status != osOK) { - ChipLogError(DeviceLayer, "WfxPostEvent: failed to post event with status: %ld", status); + ChipLogError(DeviceLayer, "sl_matter_wifi_post_event: failed to post event with status: %ld", status); // TODO: Handle error, requeue event depending on queue size or notify relevant task, // Chipdie, etc. } @@ -798,7 +795,7 @@ void ProcessEvent(WfxEvent_t inEvent) // saving the AP related info wfx_rsi_save_ap_info(); // Joining to the network - wfx_rsi_do_join(); + sl_wifi_platform_join_network(); } break; case WFX_EVT_STA_DO_DHCP: { @@ -819,7 +816,7 @@ void ProcessEvent(WfxEvent_t inEvent) } /********************************************************************************* - * @fn void wfx_rsi_task(void *arg) + * @fn void sl_matter_wifi_task(void *arg) * @brief * The main WLAN task - started by wfx_wifi_start () that interfaces with RSI. * The rest of RSI stuff come in call-backs. @@ -829,20 +826,20 @@ void ProcessEvent(WfxEvent_t inEvent) * None **********************************************************************************/ /* ARGSUSED */ -void wfx_rsi_task(void * arg) +void sl_matter_wifi_task(void * arg) { (void) arg; - uint32_t rsi_status = wfx_rsi_init(); + uint32_t rsi_status = sl_matter_wifi_init(); if (rsi_status != RSI_SUCCESS) { - ChipLogError(DeviceLayer, "wfx_rsi_task: wfx_rsi_init failed: %ld", rsi_status); + ChipLogError(DeviceLayer, "sl_matter_wifi_task: sl_matter_wifi_init failed: %ld", rsi_status); return; } WfxEvent_t wfxEvent; - wfx_lwip_start(); - wfx_started_notify(); + sl_matter_lwip_start(); + sl_matter_wifi_task_started(); - ChipLogProgress(DeviceLayer, "wfx_rsi_task: starting event loop"); + ChipLogProgress(DeviceLayer, "sl_matter_wifi_task: starting event loop"); for (;;) { osStatus_t status = osMessageQueueGet(sWifiEventQueue, &wfxEvent, NULL, osWaitForever); @@ -852,7 +849,7 @@ void wfx_rsi_task(void * arg) } else { - ChipLogProgress(DeviceLayer, "wfx_rsi_task: get event failed: %x", status); + ChipLogProgress(DeviceLayer, "sl_matter_wifi_task: get event failed: %x", status); } } } diff --git a/examples/platform/silabs/efr32/rs911x/sl_wifi_if.cpp b/examples/platform/silabs/efr32/rs911x/sl_wifi_if.cpp deleted file mode 120000 index 2f233ccc6cdbe0..00000000000000 --- a/examples/platform/silabs/efr32/rs911x/sl_wifi_if.cpp +++ /dev/null @@ -1 +0,0 @@ -../../SiWx917/SiWx917/sl_wifi_if.cpp \ No newline at end of file diff --git a/examples/platform/silabs/efr32/rs911x/sl_wlan_config.h b/examples/platform/silabs/efr32/rs911x/sl_wlan_config.h deleted file mode 100644 index 2ce2060cd7deeb..00000000000000 --- a/examples/platform/silabs/efr32/rs911x/sl_wlan_config.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * - * Copyright (c) 2022 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. - */ - -#ifndef RSI_CONFIG_H -#define RSI_CONFIG_H - -#include "ble_config.h" -#include "sl_wifi_device.h" - -//! Enable feature -#define RSI_ENABLE 1 -//! Disable feature -#define RSI_DISABLE 0 - -static const sl_wifi_device_configuration_t config = { - .boot_option = LOAD_NWP_FW, - .mac_address = NULL, - .band = SL_SI91X_WIFI_BAND_2_4GHZ, - .region_code = US, - .boot_config = { .oper_mode = SL_SI91X_CLIENT_MODE, - .coex_mode = SL_SI91X_WLAN_BLE_MODE, - .feature_bit_map = -#ifdef SLI_SI91X_MCU_INTERFACE - (SL_SI91X_FEAT_SECURITY_OPEN | SL_SI91X_FEAT_WPS_DISABLE), -#else - (SL_SI91X_FEAT_SECURITY_OPEN | SL_SI91X_FEAT_AGGREGATION), -#endif - .tcp_ip_feature_bit_map = (SL_SI91X_TCP_IP_FEAT_DHCPV4_CLIENT | SL_SI91X_TCP_IP_FEAT_DNS_CLIENT | - SL_SI91X_TCP_IP_FEAT_SSL | SL_SI91X_TCP_IP_FEAT_BYPASS -#ifdef ipv6_FEATURE_REQUIRED - | SL_SI91X_TCP_IP_FEAT_DHCPV6_CLIENT | SL_SI91X_TCP_IP_FEAT_IPV6 -#endif - | SL_SI91X_TCP_IP_FEAT_ICMP | SL_SI91X_TCP_IP_FEAT_EXTENSION_VALID), - .custom_feature_bit_map = (SL_SI91X_CUSTOM_FEAT_EXTENTION_VALID | RSI_CUSTOM_FEATURE_BIT_MAP), - .ext_custom_feature_bit_map = ( -#ifdef SLI_SI917 - (RSI_EXT_CUSTOM_FEATURE_BIT_MAP) -#else // defaults -#ifdef SLI_SI91X_MCU_INTERFACE - (SL_SI91X_EXT_FEAT_256K_MODE | RSI_EXT_CUSTOM_FEATURE_BIT_MAP) -#else - (SL_SI91X_EXT_FEAT_384K_MODE | RSI_EXT_CUSTOM_FEATURE_BIT_MAP) -#endif -#endif - | (SL_SI91X_EXT_FEAT_BT_CUSTOM_FEAT_ENABLE) -#if (defined A2DP_POWER_SAVE_ENABLE) - | SL_SI91X_EXT_FEAT_XTAL_CLK_ENABLE(2) -#endif - ), - .bt_feature_bit_map = (RSI_BT_FEATURE_BITMAP -#if (RSI_BT_GATT_ON_CLASSIC) - | SL_SI91X_BT_ATT_OVER_CLASSIC_ACL /* to support att over classic acl link */ -#endif - ), -#ifdef RSI_PROCESS_MAX_RX_DATA - .ext_tcp_ip_feature_bit_map = - (RSI_EXT_TCPIP_FEATURE_BITMAP | SL_SI91X_CONFIG_FEAT_EXTENTION_VALID | SL_SI91X_EXT_TCP_MAX_RECV_LENGTH), -#else - .ext_tcp_ip_feature_bit_map = (RSI_EXT_TCPIP_FEATURE_BITMAP | SL_SI91X_CONFIG_FEAT_EXTENTION_VALID), -#endif - //! ENABLE_BLE_PROTOCOL in bt_feature_bit_map - .ble_feature_bit_map = - ((SL_SI91X_BLE_MAX_NBR_PERIPHERALS(RSI_BLE_MAX_NBR_PERIPHERALS) | - SL_SI91X_BLE_MAX_NBR_CENTRALS(RSI_BLE_MAX_NBR_CENTRALS) | - SL_SI91X_BLE_MAX_NBR_ATT_SERV(RSI_BLE_MAX_NBR_ATT_SERV) | - SL_SI91X_BLE_MAX_NBR_ATT_REC(RSI_BLE_MAX_NBR_ATT_REC)) | - SL_SI91X_FEAT_BLE_CUSTOM_FEAT_EXTENTION_VALID | SL_SI91X_BLE_PWR_INX(RSI_BLE_PWR_INX) | - SL_SI91X_BLE_PWR_SAVE_OPTIONS(RSI_BLE_PWR_SAVE_OPTIONS) | SL_SI91X_916_BLE_COMPATIBLE_FEAT_ENABLE -#if RSI_BLE_GATT_ASYNC_ENABLE - | SL_SI91X_BLE_GATT_ASYNC_ENABLE -#endif - ), - - .ble_ext_feature_bit_map = ((SL_SI91X_BLE_NUM_CONN_EVENTS(RSI_BLE_NUM_CONN_EVENTS) | - SL_SI91X_BLE_NUM_REC_BYTES(RSI_BLE_NUM_REC_BYTES)) -#if RSI_BLE_INDICATE_CONFIRMATION_FROM_HOST - | SL_SI91X_BLE_INDICATE_CONFIRMATION_FROM_HOST // indication response from app -#endif -#if RSI_BLE_MTU_EXCHANGE_FROM_HOST - | SL_SI91X_BLE_MTU_EXCHANGE_FROM_HOST // MTU Exchange request initiation from app -#endif -#if RSI_BLE_SET_SCAN_RESP_DATA_FROM_HOST - | (SL_SI91X_BLE_SET_SCAN_RESP_DATA_FROM_HOST) // Set SCAN Resp Data from app -#endif -#if RSI_BLE_DISABLE_CODED_PHY_FROM_HOST - | (SL_SI91X_BLE_DISABLE_CODED_PHY_FROM_HOST) // Disable Coded PHY from app -#endif -#if BLE_SIMPLE_GATT - | SL_SI91X_BLE_GATT_INIT -#endif - ), - .config_feature_bit_map = (SL_SI91X_FEAT_SLEEP_GPIO_SEL_BITMAP | RSI_CONFIG_FEATURE_BITMAP) } -}; - -#endif diff --git a/examples/platform/silabs/efr32/wf200/host_if.cpp b/examples/platform/silabs/efr32/wf200/host_if.cpp index 516abca22b98e6..e38f4c43a27e67 100644 --- a/examples/platform/silabs/efr32/wf200/host_if.cpp +++ b/examples/platform/silabs/efr32/wf200/host_if.cpp @@ -28,8 +28,6 @@ #include "em_usart.h" #include "gpiointerrupt.h" -#include "wifi_config.h" - #include "AppConfig.h" #include "sl_wfx_board.h" #include "sl_wfx_host.h" @@ -715,8 +713,8 @@ static void wfx_wifi_hw_start(void) { /* Initialize the LwIP stack */ ChipLogDetail(DeviceLayer, "WF200:Start LWIP"); - wfx_lwip_start(); - wfx_started_notify(); + sl_matter_lwip_start(); + sl_matter_wifi_task_started(); wifiContext.state = SL_WFX_STARTED; /* Really this is a bit mask */ ChipLogDetail(DeviceLayer, "WF200:ready.."); } @@ -1071,7 +1069,7 @@ bool wfx_have_ipv6_addr(sl_wfx_interface_t which_if) * @returns Returns SL_STATUS_OK if successful, * SL_STATUS_FAIL otherwise *****************************************************************************/ -sl_status_t wfx_sta_discon(void) +sl_status_t sl_matter_wifi_disconnect(void) { ChipLogProgress(DeviceLayer, "STA-Disconnecting"); int32_t status = sl_wfx_send_disconnect_command(); diff --git a/examples/platform/silabs/efr32/wf200/wf200.gni b/examples/platform/silabs/efr32/wf200/wf200.gni index 307b6815374c38..f904f74495c632 100644 --- a/examples/platform/silabs/efr32/wf200/wf200.gni +++ b/examples/platform/silabs/efr32/wf200/wf200.gni @@ -1,6 +1,6 @@ import("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") -import("${efr32_sdk_build_root}/efr32_sdk.gni") +import("${silabs_sdk_build_root}/efr32_sdk.gni") wf200_plat_incs = [ "${examples_plat_dir}/wf200" ] wf200_plat_src = [ diff --git a/examples/platform/silabs/provision/BUILD.gn b/examples/platform/silabs/provision/BUILD.gn index f9e056f5ffa8a2..517dd33c124e47 100644 --- a/examples/platform/silabs/provision/BUILD.gn +++ b/examples/platform/silabs/provision/BUILD.gn @@ -14,12 +14,12 @@ import("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") -import("${efr32_sdk_build_root}/silabs_board.gni") +import("${silabs_sdk_build_root}/silabs_board.gni") if (wifi_soc) { - import("${efr32_sdk_build_root}/SiWx917_sdk.gni") + import("${silabs_sdk_build_root}/SiWx917_sdk.gni") } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") } source_set("storage") { diff --git a/examples/platform/silabs/wfx_rsi.h b/examples/platform/silabs/wfx_rsi.h index 0e62cb78029a79..4ef6bd224fdfb5 100644 --- a/examples/platform/silabs/wfx_rsi.h +++ b/examples/platform/silabs/wfx_rsi.h @@ -91,19 +91,24 @@ typedef struct wfx_rsi_s extern WfxRsi_t wfx_rsi; -#ifdef __cplusplus -extern "C" { -#endif -void wfx_rsidev_init(void); -void wfx_rsi_task(void * arg); +void sl_matter_wifi_task(void * arg); + #if CHIP_DEVICE_CONFIG_ENABLE_IPV4 void wfx_ip_changed_notify(int got_ip); #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ + int32_t wfx_rsi_get_ap_info(wfx_wifi_scan_result_t * ap); int32_t wfx_rsi_get_ap_ext(wfx_wifi_scan_ext_t * extra_info); int32_t wfx_rsi_reset_count(); -int32_t wfx_rsi_disconnect(); -int32_t wfx_wifi_rsi_init(void); +int32_t sl_wifi_platform_disconnect(); + +// TODO : this needs to be extern otherwise we get a linking error. We need to figure out why in the header clean up +// NCP files are including this while being c files +#ifdef __cplusplus +extern "C" { +#endif +sl_status_t sl_matter_wifi_platform_init(void); + #if CHIP_CONFIG_ENABLE_ICD_SERVER #if SLI_SI91X_MCU_INTERFACE void sl_si91x_invoke_btn_press_event(); @@ -114,11 +119,14 @@ int32_t wfx_rsi_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_ int32_t wfx_rsi_power_save(); #endif /* SLI_SI917 */ #endif /* SL_ICD_ENABLED */ - -/// WfxPostEvent -/// @brief Allows to allocate an event to the WFX task event queue from outside of sl_wifi_if.c -/// @param event The event that will be allocated to the event queue -void WfxPostEvent(WfxEvent_t * event); #ifdef __cplusplus } #endif + +/** + * @brief Posts an event to the Wi-Fi task + * + * @param[in] event Event to process. Must be valid ptr + */ +// TODO: Can't be a const & since the ncp builds are still using c files +void sl_matter_wifi_post_event(WfxEvent_t * event); diff --git a/examples/platform/silabs/wifi/wfx_notify.cpp b/examples/platform/silabs/wifi/wfx_notify.cpp index de1becacb33b30..fe097a60983e7f 100644 --- a/examples/platform/silabs/wifi/wfx_notify.cpp +++ b/examples/platform/silabs/wifi/wfx_notify.cpp @@ -60,13 +60,13 @@ static void RetryConnectionTimerHandler(void * arg) } } /*********************************************************************************** - * @fn wfx_started_notify(void) + * @fn sl_matter_wifi_task_started(void) * @brief * Wifi device started notification * @param[in]: None * @return None *************************************************************************************/ -void wfx_started_notify(void) +void sl_matter_wifi_task_started(void) { sl_wfx_startup_ind_t evt; sl_wfx_mac_address_t mac; diff --git a/examples/platform/silabs/wifi/wfx_rsi_host.cpp b/examples/platform/silabs/wifi/wfx_rsi_host.cpp index d76bc9c7959c8b..3263d884c70af3 100644 --- a/examples/platform/silabs/wifi/wfx_rsi_host.cpp +++ b/examples/platform/silabs/wifi/wfx_rsi_host.cpp @@ -15,6 +15,8 @@ * limitations under the License. */ +// SL MATTER WI-FI INTERFACE + #include #include #include @@ -62,11 +64,11 @@ sl_status_t wfx_wifi_start(void) wfx_rsi.dev_state |= WFX_RSI_ST_STARTED; // Creating a Wi-Fi driver thread - sWlanThread = osThreadNew(wfx_rsi_task, NULL, &kWlanTaskAttr); + sWlanThread = osThreadNew(sl_matter_wifi_task, NULL, &kWlanTaskAttr); VerifyOrReturnError(sWlanThread != NULL, SL_STATUS_FAIL); - ChipLogProgress(DeviceLayer, "wfx_rsi_task created successfully"); + ChipLogProgress(DeviceLayer, "sl_matter_wifi_task created successfully"); return SL_STATUS_OK; } @@ -175,7 +177,7 @@ sl_status_t wfx_connect_to_ap(void) ChipLogProgress(DeviceLayer, "connect to access point: %s", wfx_rsi.sec.ssid); WfxEvent_t event; event.eventType = WFX_EVT_STA_START_JOIN; - WfxPostEvent(&event); + sl_matter_wifi_post_event(&event); return SL_STATUS_OK; } @@ -221,7 +223,7 @@ sl_status_t wfx_power_save(void) void wfx_setup_ip6_link_local(sl_wfx_interface_t whichif) { /* - * TODO: Implement IPV6 setup, currently in wfx_rsi_task() + * TODO: Implement IPV6 setup, currently in sl_matter_wifi_task() * This is hooked with MATTER code. */ } @@ -256,17 +258,17 @@ wifi_mode_t wfx_get_wifi_mode(void) } /********************************************************************* - * @fn sl_status_t wfx_sta_discon(void) + * @fn sl_status_t sl_matter_wifi_disconnect(void) * @brief * called fuction when STA disconnected * @param[in] None * @return return SL_STATUS_OK if successful, * SL_STATUS_FAIL otherwise ***********************************************************************/ -sl_status_t wfx_sta_discon(void) +sl_status_t sl_matter_wifi_disconnect(void) { sl_status_t status; - status = wfx_rsi_disconnect(); + status = sl_wifi_platform_disconnect(); wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_CONNECTED; return status; } @@ -376,7 +378,7 @@ bool wfx_start_scan(char * ssid, void (*callback)(wfx_wifi_scan_result_t *)) WfxEvent_t event; event.eventType = WFX_EVT_SCAN; - WfxPostEvent(&event); + sl_matter_wifi_post_event(&event); return true; } diff --git a/examples/pump-app/silabs/BUILD.gn b/examples/pump-app/silabs/BUILD.gn index 8321ba6c80adc9..e8acd1501c5a18 100644 --- a/examples/pump-app/silabs/BUILD.gn +++ b/examples/pump-app/silabs/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -38,7 +38,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/examples/smoke-co-alarm-app/silabs/BUILD.gn b/examples/smoke-co-alarm-app/silabs/BUILD.gn index c6fe0967a9775b..ad2db014594416 100644 --- a/examples/smoke-co-alarm-app/silabs/BUILD.gn +++ b/examples/smoke-co-alarm-app/silabs/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -38,7 +38,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/examples/thermostat/silabs/BUILD.gn b/examples/thermostat/silabs/BUILD.gn index f51ee14825d27e..623d87c2f74555 100644 --- a/examples/thermostat/silabs/BUILD.gn +++ b/examples/thermostat/silabs/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -38,7 +38,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/examples/window-app/silabs/BUILD.gn b/examples/window-app/silabs/BUILD.gn index c45dbda632a5f9..f55d63012f8444 100644 --- a/examples/window-app/silabs/BUILD.gn +++ b/examples/window-app/silabs/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -39,7 +39,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/src/lwip/BUILD.gn b/src/lwip/BUILD.gn index ca08a8c392182d..78657a635a4268 100644 --- a/src/lwip/BUILD.gn +++ b/src/lwip/BUILD.gn @@ -219,7 +219,7 @@ if (current_os == "zephyr" || current_os == "mbed") { } else if (lwip_platform == "cc32xx") { public_deps += [ "${ti_simplelink_sdk_build_root}:ti_simplelink_sdk" ] } else if (lwip_platform == "silabs") { - public_deps += [ "${efr32_sdk_build_root}:efr32_sdk" ] + public_deps += [ "${silabs_sdk_build_root}:silabs_sdk" ] sources += [ "${lwip_platform}/lwipopts-rs911x.h", diff --git a/src/platform/silabs/ConfigurationManagerImpl.cpp b/src/platform/silabs/ConfigurationManagerImpl.cpp index b4dd5c9c524f72..0219852813f28e 100644 --- a/src/platform/silabs/ConfigurationManagerImpl.cpp +++ b/src/platform/silabs/ConfigurationManagerImpl.cpp @@ -290,10 +290,10 @@ void ConfigurationManagerImpl::DoFactoryReset(intptr_t arg) PersistedStorage::KeyValueStoreMgrImpl().ErasePartition(); #if CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION - sl_status_t status = wfx_sta_discon(); + sl_status_t status = sl_matter_wifi_disconnect(); if (status != SL_STATUS_OK) { - ChipLogError(DeviceLayer, "wfx_sta_discon() failed: %lx", status); + ChipLogError(DeviceLayer, "sl_matter_wifi_disconnect() failed: %lx", status); } ChipLogProgress(DeviceLayer, "Clearing WiFi provision"); wfx_clear_wifi_provision(); diff --git a/src/platform/silabs/ConnectivityManagerImpl_WIFI.cpp b/src/platform/silabs/ConnectivityManagerImpl_WIFI.cpp index 6e5470f7d05f26..2dd946feb12a6d 100644 --- a/src/platform/silabs/ConnectivityManagerImpl_WIFI.cpp +++ b/src/platform/silabs/ConnectivityManagerImpl_WIFI.cpp @@ -277,7 +277,7 @@ void ConnectivityManagerImpl::DriveStationState() (mWiFiStationMode != kWiFiStationMode_Enabled && !IsWiFiStationProvisioned())) { ChipLogProgress(DeviceLayer, "Disconnecting WiFi station interface"); - serr = wfx_sta_discon(); + serr = sl_matter_wifi_disconnect(); if (serr != SL_STATUS_OK) { ChipLogError(DeviceLayer, "wfx_wifi_disconnect() failed: %lx", serr); diff --git a/src/platform/silabs/NetworkCommissioningWiFiDriver.cpp b/src/platform/silabs/NetworkCommissioningWiFiDriver.cpp index 7f6240c32c5858..ba80a94be6a96c 100644 --- a/src/platform/silabs/NetworkCommissioningWiFiDriver.cpp +++ b/src/platform/silabs/NetworkCommissioningWiFiDriver.cpp @@ -140,7 +140,7 @@ CHIP_ERROR SlWiFiDriver::ConnectWiFiNetwork(const char * ssid, uint8_t ssidLen, if (ConnectivityMgr().IsWiFiStationProvisioned()) { ChipLogProgress(DeviceLayer, "Disconecting for current wifi"); - status = wfx_sta_discon(); + status = sl_matter_wifi_disconnect(); if (status != SL_STATUS_OK) { return CHIP_ERROR_INTERNAL; diff --git a/src/platform/silabs/PlatformManagerImpl.cpp b/src/platform/silabs/PlatformManagerImpl.cpp index dccb5db7657251..20d7b94ada5edf 100644 --- a/src/platform/silabs/PlatformManagerImpl.cpp +++ b/src/platform/silabs/PlatformManagerImpl.cpp @@ -84,10 +84,10 @@ CHIP_ERROR PlatformManagerImpl::_InitChipStack(void) err = chip::DeviceLayer::PersistedStorage::KeyValueStoreMgrImpl().Init(); SuccessOrExit(err); -#if CHIP_SYSTEM_CONFIG_USE_LWIP +#if CHIP_SYSTEM_CONFIG_USE_LWIP && !defined(SLI_SI91X_MCU_INTERFACE) // Initialize LwIP. tcpip_init(NULL, NULL); -#endif // CHIP_SYSTEM_CONFIG_USE_LWIP +#endif // CHIP_SYSTEM_CONFIG_USE_LWIP && !defined(SLI_SI91X_MCU_INTERFACE) ReturnErrorOnFailure(System::Clock::InitClock_RealTime()); diff --git a/src/platform/silabs/SiWx917/BUILD.gn b/src/platform/silabs/SiWx917/BUILD.gn index 188f1f3396f7de..0c2f9032e4bc81 100644 --- a/src/platform/silabs/SiWx917/BUILD.gn +++ b/src/platform/silabs/SiWx917/BUILD.gn @@ -103,7 +103,6 @@ static_library("SiWx917") { "${silabs_platform_dir}/NetworkCommissioningWiFiDriver.h", "${silabs_platform_dir}/wifi/wfx_host_events.h", "wifi/wfx_msgs.h", - "wifi/wifi_config.h", ] public_configs = [ ":siwx917-platform-wifi-config" ] } diff --git a/src/platform/silabs/SiWx917/wifi/ethernetif.cpp b/src/platform/silabs/SiWx917/wifi/ethernetif.cpp deleted file mode 100644 index 2860b895ce7fae..00000000000000 --- a/src/platform/silabs/SiWx917/wifi/ethernetif.cpp +++ /dev/null @@ -1,269 +0,0 @@ -/* - * - * Copyright (c) 2022 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. - */ - -/* Includes */ - -#include -#include -#include - -#include "wfx_host_events.h" -#include "wifi_config.h" -#ifdef __cplusplus -extern "C" { -#endif -#include "cmsis_os2.h" -#include "sl_board_configuration.h" -#include "sl_net.h" -#include "sl_si91x_driver.h" -#include "sl_si91x_host_interface.h" -#include "sl_si91x_types.h" -#include "sl_wifi.h" -#include "sl_wifi_callback_framework.h" -#include "sl_wifi_constants.h" -#include "sl_wifi_types.h" -#ifdef __cplusplus -} -#endif -/* LwIP includes. */ -#include "ethernetif.h" -#include "lwip/ethip6.h" -#include "lwip/timeouts.h" -#include "netif/etharp.h" -#include - -StaticSemaphore_t xEthernetIfSemaBuffer; - -/***************************************************************************** - * Defines - ******************************************************************************/ -#define STATION_NETIF0 's' -#define STATION_NETIF1 't' - -#define LWIP_FRAME_ALIGNMENT 60 - -uint32_t gOverrunCount = 0; - -/***************************************************************************** - * Variables - ******************************************************************************/ - -/***************************************************************************** - * @fn static void low_level_init(struct netif *netif) - * @brief - * Initializes the hardware parameters. Called from ethernetif_init(). - * - * @param[in] netif: the already initialized lwip network interface structure - * - * @return - * None - ******************************************************************************/ -static void low_level_init(struct netif * netif) -{ - /* set netif MAC hardware address length */ - netif->hwaddr_len = ETH_HWADDR_LEN; - - /* Set netif MAC hardware address */ - sl_wfx_mac_address_t mac_addr; - - wfx_get_wifi_mac_addr(SL_WFX_STA_INTERFACE, &mac_addr); - - netif->hwaddr[0] = mac_addr.octet[0]; - netif->hwaddr[1] = mac_addr.octet[1]; - netif->hwaddr[2] = mac_addr.octet[2]; - netif->hwaddr[3] = mac_addr.octet[3]; - netif->hwaddr[4] = mac_addr.octet[4]; - netif->hwaddr[5] = mac_addr.octet[5]; - - /* Set netif maximum transfer unit */ - netif->mtu = 1500; - - /* Accept broadcast address and ARP traffic */ - netif->flags |= NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP; - -#if LWIP_IPV6_MLD - netif->flags |= NETIF_FLAG_MLD6; -#endif /* LWIP_IPV6_MLD */ -} - -/******************************************************************************** - * @fn static void low_level_input(struct netif *netif, uint8_t *b, uint16_t len) - * @brief - * Make PBUF out of a linear buffer - that can be fed into lwip - * @param[in] netif: the already initialized lwip network interface structure - * @param[in] len: length - * @return - * None - ************************************************************************************/ -static void low_level_input(struct netif * netif, uint8_t * b, uint16_t len) -{ - struct pbuf *p, *q; - uint32_t bufferoffset; - - if (len <= 0) - { - return; - } - if (len < LWIP_FRAME_ALIGNMENT) - { /* 60 : LWIP frame alignment */ - len = LWIP_FRAME_ALIGNMENT; - } - - /* Drop packets originated from the same interface and is not destined for the said interface */ - const uint8_t * src_mac = b + netif->hwaddr_len; - const uint8_t * dst_mac = b; - - if (!(ip6_addr_ispreferred(netif_ip6_addr_state(netif, 0))) && (memcmp(netif->hwaddr, src_mac, netif->hwaddr_len) == 0) && - (memcmp(netif->hwaddr, dst_mac, netif->hwaddr_len) != 0)) - { -#ifdef WIFI_DEBUG_ENABLED - ChipLogDetail(DeviceLayer, "DROP: [%02x:%02x:%02x:%02x:%02x:%02x]->[%02x:%02x:%02x:%02x:%02x:%02x] type=%02x%02x", - - src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5], - - dst_mac[0], dst_mac[1], dst_mac[2], dst_mac[3], dst_mac[4], dst_mac[5], - - b[12], b[13]); -#endif - return; - } - - /* We allocate a pbuf chain of pbufs from the Lwip buffer pool - * and copy the data to the pbuf chain - */ - if ((p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL)) != STRUCT_PBUF) - { - for (q = p, bufferoffset = 0; q != NULL; q = q->next) - { - memcpy((uint8_t *) q->payload, (uint8_t *) b + bufferoffset, q->len); - bufferoffset += q->len; - } -#ifdef WIFI_DEBUG_ENABLED - ChipLogDetail(DeviceLayer, "ACCEPT(%d): [%02x:%02x:%02x:%02x:%02x:%02x]->[%02x:%02x:%02x:%02x:%02x:%02x] type=%02x%02x", - bufferoffset, - - src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5], - - dst_mac[0], dst_mac[1], dst_mac[2], dst_mac[3], dst_mac[4], dst_mac[5], - - b[12], b[13]); -#endif - - if (netif->input(p, netif) != ERR_OK) - { - gOverrunCount++; - pbuf_free(p); - } - } - else - { - gOverrunCount++; - } -} - -static SemaphoreHandle_t ethout_sem; -/***************************************************************************** - * @fn static err_t low_level_output(struct netif *netif, struct pbuf *p) - * @brief - * This function is called from LWIP task when LWIP stack - * has some data to be forwarded over WiFi Network - * - * @param[in] netif: lwip network interface - * - * @param[in] p: the packet to send - * - * @return - * ERR_OK if successful - ******************************************************************************/ -static err_t low_level_output(struct netif * netif, struct pbuf * p) -{ - UNUSED_PARAMETER(netif); - sl_status_t status; - status = sl_wifi_send_raw_data_frame(SL_WIFI_CLIENT_INTERFACE, (uint8_t *) p->payload, p->len); - if (status != SL_STATUS_OK) - { - return ERR_IF; - } - return ERR_OK; -} - -/***************************************************************************** - * @fn void sl_si91x_host_process_data_frame(uint8_t *buf, int len) - * @brief - * host received frame cb - * - * @param[in] buf: buffer - * - * @param[in] len: length - * - * @return - * None - ******************************************************************************/ -sl_status_t sl_si91x_host_process_data_frame(sl_wifi_interface_t interface, sl_wifi_buffer_t * buffer) -{ - struct pbuf * pbuf_packet; - void * packet; - struct netif * ifp; - sl_si91x_packet_t * rsi_pkt; - packet = sl_si91x_host_get_buffer_data(buffer, 0, NULL); - rsi_pkt = (sl_si91x_packet_t *) packet; - - /* get the network interface for STATION interface, - * and forward the received frame buffer to LWIP - */ - if ((ifp = wfx_get_netif(SL_WFX_STA_INTERFACE)) != (struct netif *) 0) - { - low_level_input(ifp, rsi_pkt->data, rsi_pkt->length); - } - return SL_STATUS_OK; -} - -/***************************************************************************** - * @fn err_t sta_ethernetif_init(struct netif *netif) - * @brief - * sta ethernet if initialization - * - * @param[in] netif: the lwip network interface structure - * - * @return - * ERR_OK if successful - ******************************************************************************/ -err_t sta_ethernetif_init(struct netif * netif) -{ - LWIP_ASSERT("netif != NULL", (netif != NULL)); - - /* Set the netif name to identify the interface */ - netif->name[0] = STATION_NETIF0; - netif->name[1] = STATION_NETIF1; - -#if LWIP_IPV4 && LWIP_ARP - netif->output = etharp_output; -#endif /* #if LWIP_IPV4 && LWIP_ARP */ -#if LWIP_IPV6 && LWIP_ETHERNET - netif->output_ip6 = ethip6_output; -#endif /* LWIP_IPV6 && LWIP_ETHERNET */ - netif->linkoutput = low_level_output; - - /* initialize the hardware */ - low_level_init(netif); - - /* Need single output only */ - ethout_sem = xSemaphoreCreateBinaryStatic(&xEthernetIfSemaBuffer); - xSemaphoreGive(ethout_sem); - - return ERR_OK; -} diff --git a/src/platform/silabs/SiWx917/wifi/ethernetif.h b/src/platform/silabs/SiWx917/wifi/ethernetif.h deleted file mode 100644 index bac51b9258cd85..00000000000000 --- a/src/platform/silabs/SiWx917/wifi/ethernetif.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * - * Copyright (c) 2022 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. - */ - -#pragma once - -#include "lwip/err.h" -#include "lwip/netif.h" -#ifdef __cplusplus -extern "C" { -#endif -/*************************************************************************** - * @fn err_t sta_ethernetif_init(struct netif *netif) - * @brief - * Sets up the station network interface. - * - * @param netif the lwip network interface structure - * @returns ERR_OK if successful - ******************************************************************************/ -err_t sta_ethernetif_init(struct netif * netif); - -/*************************************************************************** - * @fn err_t ap_ethernetif_init(struct netif *netif - * @brief - * Sets up the AP network interface. - * - * @param netif the lwip network interface structure - * @returns ERR_OK if successful - ******************************************************************************/ -err_t ap_ethernetif_init(struct netif * netif); - -void wfx_host_received_sta_frame_cb(uint8_t * buf, int len); - -#ifdef __cplusplus -} -#endif diff --git a/src/platform/silabs/SiWx917/wifi/lwip_netif.cpp b/src/platform/silabs/SiWx917/wifi/lwip_netif.cpp deleted file mode 100644 index d4bcbe4739a10f..00000000000000 --- a/src/platform/silabs/SiWx917/wifi/lwip_netif.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/* - * - * Copyright (c) 2022 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. - */ - -#include -#include -#include - -#include "wfx_host_events.h" -#include "wifi_config.h" - -#include "dhcp_client.h" -#include "ethernetif.h" - -#include "FreeRTOS.h" -#include "event_groups.h" -#include "task.h" - -#include -using namespace ::chip; -using namespace ::chip::DeviceLayer; -static struct netif sta_netif; - -#ifdef SL_WFX_CONFIG_SOFTAP -static struct netif ap_netif; -#endif - -/**************************************************************************** - * @fn static void netif_config(struct netif *sta_if, struct netif *ap_if) - * @brief - * netif configuration - * @param[in] sta_if: - * @param[in] ap_if: - * @return None - *****************************************************************************/ -static void netif_config(struct netif * sta_if, struct netif * ap_if) -{ - if (sta_if != NULL) - { -#if LWIP_IPV4 - ip_addr_t sta_ipaddr; - ip_addr_t sta_netmask; - ip_addr_t sta_gw; - - /* Initialize the Station information */ - ip_addr_set_zero_ip4(&sta_ipaddr); - ip_addr_set_zero_ip4(&sta_netmask); - ip_addr_set_zero_ip4(&sta_gw); -#endif /* LWIP_IPV4 */ - - /* Add station interfaces */ - netif_add(sta_if, -#if LWIP_IPV4 - (const ip4_addr_t *) &sta_ipaddr, (const ip4_addr_t *) &sta_netmask, (const ip4_addr_t *) &sta_gw, -#endif /* LWIP_IPV4 */ - NULL, &sta_ethernetif_init, &tcpip_input); - - /* Registers the default network interface */ - netif_set_default(sta_if); - } -} - -/**************************************************************************** - * @fn void wfx_lwip_set_sta_link_up(void) - * @brief - * Set station link status to up. - * @param[in] None - * @return None - *****************************************************************************/ -void wfx_lwip_set_sta_link_up(void) -{ - netifapi_netif_set_up(&sta_netif); - netifapi_netif_set_link_up(&sta_netif); -#if LWIP_IPV4 && LWIP_DHCP - dhcpclient_set_link_state(LINK_UP); -#endif /* LWIP_IPV4 && LWIP_DHCP */ - /* - * Enable IPV6 - */ - -#if LWIP_IPV6_AUTOCONFIG - sta_netif.ip6_autoconfig_enabled = 1; -#endif /* LWIP_IPV6_AUTOCONFIG */ - netif_create_ip6_linklocal_address(&sta_netif, MAC_48_BIT_SET); -} - -/*************************************************************************** - * @fn void wfx_lwip_set_sta_link_down(void) - * @brief - * Set station link status to down. - * @param[in] None - * @return None - *****************************************************************************/ -void wfx_lwip_set_sta_link_down(void) -{ -#if LWIP_IPV4 && LWIP_DHCP - dhcpclient_set_link_state(LINK_DOWN); -#endif /* LWIP_IPV4 && LWIP_DHCP */ - netifapi_netif_set_link_down(&sta_netif); - netifapi_netif_set_down(&sta_netif); -} - -/*************************************************************************** - * @fn void wfx_lwip_start(void) - * @brief - * Initialize the LwIP stack - * @param[in] None - * @return None - *****************************************************************************/ -void wfx_lwip_start(void) -{ - /* Initialize the LwIP stack */ - netif_config(&sta_netif, NULL); -} - -/*************************************************************************** - * @fn struct netif *wfx_get_netif(sl_wfx_interface_t interface) - * @brief - * get the netif - * @param[in] interface: - * @return None - *****************************************************************************/ -struct netif * wfx_get_netif(sl_wfx_interface_t interface) -{ - if (interface == SL_WFX_STA_INTERFACE) - { - return &sta_netif; - } -#ifdef SL_WFX_CONFIG_SOFTAP - else if (interface == SL_WFX_SOFTAP_INTERFACE) - { - return &ap_netif; - } -#endif - return (struct netif *) 0; -} diff --git a/src/platform/silabs/SiWx917/wifi/wifi_config.h b/src/platform/silabs/SiWx917/wifi/wifi_config.h deleted file mode 100644 index f2f3b7ffeb3740..00000000000000 --- a/src/platform/silabs/SiWx917/wifi/wifi_config.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * - * Copyright (c) 2022 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. - */ - -#ifndef DEMO_CONFIG_H -#define DEMO_CONFIG_H - -#define USE_DHCP_CLIENT_DEFAULT (1) ///< If defined, DHCP is enabled, otherwise static address below is used - -/************************** Station Static Default ****************************/ -#define STA_IP_ADDR0_DEFAULT ((uint8_t) 192) ///< Static IP: IP address value 0 -#define STA_IP_ADDR1_DEFAULT ((uint8_t) 168) ///< Static IP: IP address value 1 -#define STA_IP_ADDR2_DEFAULT ((uint8_t) 0) ///< Static IP: IP address value 2 -#define STA_IP_ADDR3_DEFAULT ((uint8_t) 1) ///< Static IP: IP address value 3 - -/*NETMASK*/ -#define STA_NETMASK_ADDR0_DEFAULT ((uint8_t) 255) ///< Static IP: Netmask value 0 -#define STA_NETMASK_ADDR1_DEFAULT ((uint8_t) 255) ///< Static IP: Netmask value 1 -#define STA_NETMASK_ADDR2_DEFAULT ((uint8_t) 255) ///< Static IP: Netmask value 2 -#define STA_NETMASK_ADDR3_DEFAULT ((uint8_t) 0) ///< Static IP: Netmask value 3 - -/*Gateway Address*/ -#define STA_GW_ADDR0_DEFAULT ((uint8_t) 0) ///< Static IP: Gateway value 0 -#define STA_GW_ADDR1_DEFAULT ((uint8_t) 0) ///< Static IP: Gateway value 1 -#define STA_GW_ADDR2_DEFAULT ((uint8_t) 0) ///< Static IP: Gateway value 2 -#define STA_GW_ADDR3_DEFAULT ((uint8_t) 0) ///< Static IP: Gateway value 3 - -/************************** Access Point Static Default ****************************/ -// #define AP_IP_ADDR0_DEFAULT (uint8_t) 10 ///< Static IP: IP address value 0 -// #define AP_IP_ADDR1_DEFAULT (uint8_t) 10 ///< Static IP: IP address value 1 -// #define AP_IP_ADDR2_DEFAULT (uint8_t) 0 ///< Static IP: IP address value 2 -// #define AP_IP_ADDR3_DEFAULT (uint8_t) 1 ///< Static IP: IP address value 3 - -/*NETMASK*/ -// #define AP_NETMASK_ADDR0_DEFAULT (uint8_t) 255 ///< Static IP: Netmask value 0 -// #define AP_NETMASK_ADDR1_DEFAULT (uint8_t) 255 ///< Static IP: Netmask value 1 -// #define AP_NETMASK_ADDR2_DEFAULT (uint8_t) 255 ///< Static IP: Netmask value 2 -// #define AP_NETMASK_ADDR3_DEFAULT (uint8_t) 0 ///< Static IP: Netmask value 3 - -/*Gateway Address*/ -// #define AP_GW_ADDR0_DEFAULT (uint8_t) 0 ///< Static IP: Gateway value 0 -// #define AP_GW_ADDR1_DEFAULT (uint8_t) 0 ///< Static IP: Gateway value 1 -// #define AP_GW_ADDR2_DEFAULT (uint8_t) 0 ///< Static IP: Gateway value 2 -// #define AP_GW_ADDR3_DEFAULT (uint8_t) 0 ///< Static IP: Gateway value 3 - -#define WLAN_SSID_DEFAULT "AP_name" ///< wifi ssid for client mode -#define WLAN_PASSKEY_DEFAULT "passkey" ///< wifi password for client mode -#define WLAN_SECURITY_DEFAULT WFM_SECURITY_MODE_WPA2_PSK ///< wifi security mode for client mode: -///< WFM_SECURITY_MODE_OPEN/WFM_SECURITY_MODE_WEP/WFM_SECURITY_MODE_WPA2_WPA1_PSK - -#define SOFTAP_SSID_DEFAULT "silabs_softap" ///< wifi ssid for soft ap mode -#define SOFTAP_PASSKEY_DEFAULT "changeme" ///< wifi password for soft ap mode -#define SOFTAP_SECURITY_DEFAULT WFM_SECURITY_MODE_WPA2_PSK ///< wifi security for soft ap mode: -///< WFM_SECURITY_MODE_OPEN/WFM_SECURITY_MODE_WEP/WFM_SECURITY_MODE_WPA2_WPA1_PSK - -#define SOFTAP_CHANNEL_DEFAULT (6) ///< wifi channel for soft ap - -#endif // DEMO_CONFIG_H diff --git a/src/platform/silabs/efr32/BUILD.gn b/src/platform/silabs/efr32/BUILD.gn index 4bc881f5f54a27..b1e50faafca0e0 100644 --- a/src/platform/silabs/efr32/BUILD.gn +++ b/src/platform/silabs/efr32/BUILD.gn @@ -161,10 +161,9 @@ static_library("efr32") { "${silabs_platform_dir}/NetworkCommissioningWiFiDriver.h", "${silabs_platform_dir}/wifi/wfx_host_events.h", "wifi/wfx_msgs.h", - "wifi/wifi_config.h", ] - if (use_wf200 || use_rs9116 || use_SiWx917) { + if (use_wf200 || use_rs9116) { sources += [ "${silabs_platform_dir}/wifi/dhcp_client.cpp", "wifi/ethernetif.cpp", diff --git a/src/platform/silabs/efr32/args.gni b/src/platform/silabs/efr32/args.gni index 394e4bb1bd806a..501661866ad61e 100644 --- a/src/platform/silabs/efr32/args.gni +++ b/src/platform/silabs/efr32/args.gni @@ -20,9 +20,9 @@ import("${chip_root}/examples/platform/silabs/args.gni") import("${chip_root}/src/crypto/crypto.gni") # ARM architecture flags will be set based on silabs_family. -arm_platform_config = "${efr32_sdk_build_root}/silabs_arm.gni" +arm_platform_config = "${silabs_sdk_build_root}/silabs_arm.gni" -mbedtls_target = "${efr32_sdk_build_root}:efr32_sdk" +mbedtls_target = "${silabs_sdk_build_root}:silabs_sdk" openthread_external_mbedtls = mbedtls_target diff --git a/src/platform/silabs/efr32/wifi/ethernetif.cpp b/src/platform/silabs/efr32/wifi/ethernetif.cpp index d0f0ec6daf47f7..5993cf90cc631a 100644 --- a/src/platform/silabs/efr32/wifi/ethernetif.cpp +++ b/src/platform/silabs/efr32/wifi/ethernetif.cpp @@ -51,7 +51,6 @@ extern "C" { #endif // WF200_WIFI #include "wfx_host_events.h" -#include "wifi_config.h" #ifdef WF200_WIFI #include "sl_wfx.h" #endif diff --git a/src/platform/silabs/efr32/wifi/lwip_netif.cpp b/src/platform/silabs/efr32/wifi/lwip_netif.cpp index 3a0d104a90be71..f8d719b387fb09 100644 --- a/src/platform/silabs/efr32/wifi/lwip_netif.cpp +++ b/src/platform/silabs/efr32/wifi/lwip_netif.cpp @@ -26,7 +26,6 @@ #include "em_usart.h" #include "wfx_host_events.h" -#include "wifi_config.h" #include "dhcp_client.h" #include "ethernetif.h" @@ -121,13 +120,13 @@ void wfx_lwip_set_sta_link_down(void) } /*************************************************************************** - * @fn void wfx_lwip_start(void) + * @fn void sl_matter_lwip_start(void) * @brief * Initialize the LwIP stack * @param[in] None * @return None *****************************************************************************/ -void wfx_lwip_start(void) +void sl_matter_lwip_start(void) { /* Initialize the LwIP stack */ netif_config(&sta_netif, NULL); diff --git a/src/platform/silabs/efr32/wifi/wifi_config.h b/src/platform/silabs/efr32/wifi/wifi_config.h deleted file mode 100644 index 8e00201b7fc102..00000000000000 --- a/src/platform/silabs/efr32/wifi/wifi_config.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * - * Copyright (c) 2022 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. - */ - -#ifndef WIFI_CONFIG_H -#define WIFI_CONFIG_H - -#define USE_DHCP_CLIENT_DEFAULT 1 ///< If defined, DHCP is enabled, otherwise static address below is used - -/************************** Station Static Default ****************************/ -#define STA_IP_ADDR0_DEFAULT (uint8_t) 192 ///< Static IP: IP address value 0 -#define STA_IP_ADDR1_DEFAULT (uint8_t) 168 ///< Static IP: IP address value 1 -#define STA_IP_ADDR2_DEFAULT (uint8_t) 0 ///< Static IP: IP address value 2 -#define STA_IP_ADDR3_DEFAULT (uint8_t) 1 ///< Static IP: IP address value 3 - -/*NETMASK*/ -#define STA_NETMASK_ADDR0_DEFAULT (uint8_t) 255 ///< Static IP: Netmask value 0 -#define STA_NETMASK_ADDR1_DEFAULT (uint8_t) 255 ///< Static IP: Netmask value 1 -#define STA_NETMASK_ADDR2_DEFAULT (uint8_t) 255 ///< Static IP: Netmask value 2 -#define STA_NETMASK_ADDR3_DEFAULT (uint8_t) 0 ///< Static IP: Netmask value 3 - -/*Gateway Address*/ -#define STA_GW_ADDR0_DEFAULT (uint8_t) 0 ///< Static IP: Gateway value 0 -#define STA_GW_ADDR1_DEFAULT (uint8_t) 0 ///< Static IP: Gateway value 1 -#define STA_GW_ADDR2_DEFAULT (uint8_t) 0 ///< Static IP: Gateway value 2 -#define STA_GW_ADDR3_DEFAULT (uint8_t) 0 ///< Static IP: Gateway value 3 - -#define WLAN_SSID_DEFAULT "AP_name" ///< wifi ssid for client mode -#define WLAN_PASSKEY_DEFAULT "passkey" ///< wifi password for client mode -#define WLAN_SECURITY_DEFAULT WFM_SECURITY_MODE_WPA2_PSK ///< wifi security mode for client mode: -///< WFM_SECURITY_MODE_OPEN/WFM_SECURITY_MODE_WEP/WFM_SECURITY_MODE_WPA2_WPA1_PSK - -#define SOFTAP_SSID_DEFAULT "silabs_softap" ///< wifi ssid for soft ap mode -#define SOFTAP_PASSKEY_DEFAULT "changeme" ///< wifi password for soft ap mode -#define SOFTAP_SECURITY_DEFAULT WFM_SECURITY_MODE_WPA2_PSK ///< wifi security for soft ap mode: -///< WFM_SECURITY_MODE_OPEN/WFM_SECURITY_MODE_WEP/WFM_SECURITY_MODE_WPA2_WPA1_PSK - -#define SOFTAP_CHANNEL_DEFAULT 6 ///< wifi channel for soft ap - -#endif // WIFI_CONFIG_H diff --git a/src/platform/silabs/provision/BUILD.gn b/src/platform/silabs/provision/BUILD.gn index ea5d4b072a03ac..7ae41c05154731 100644 --- a/src/platform/silabs/provision/BUILD.gn +++ b/src/platform/silabs/provision/BUILD.gn @@ -14,7 +14,7 @@ import("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") -import("${efr32_sdk_build_root}/silabs_board.gni") +import("${silabs_sdk_build_root}/silabs_board.gni") config("provision-config") { include_dirs = [ "." ] diff --git a/src/platform/silabs/wifi/dhcp_client.cpp b/src/platform/silabs/wifi/dhcp_client.cpp index c8b47a9f2b3735..a219430762cf50 100644 --- a/src/platform/silabs/wifi/dhcp_client.cpp +++ b/src/platform/silabs/wifi/dhcp_client.cpp @@ -24,7 +24,6 @@ #include "dhcp_client.h" #include "lwip/dhcp.h" #include "wfx_host_events.h" -#include "wifi_config.h" #include "FreeRTOS.h" #include "event_groups.h" diff --git a/src/platform/silabs/wifi/wfx_host_events.h b/src/platform/silabs/wifi/wfx_host_events.h index 3bd973467bf915..d3d8de6ec78569 100644 --- a/src/platform/silabs/wifi/wfx_host_events.h +++ b/src/platform/silabs/wifi/wfx_host_events.h @@ -316,7 +316,7 @@ void wfx_clear_wifi_provision(void); sl_status_t wfx_connect_to_ap(void); void wfx_setup_ip6_link_local(sl_wfx_interface_t); bool wfx_is_sta_connected(void); -sl_status_t wfx_sta_discon(void); +sl_status_t sl_matter_wifi_disconnect(void); #if CHIP_DEVICE_CONFIG_ENABLE_IPV4 bool wfx_have_ipv4_addr(sl_wfx_interface_t); #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ @@ -328,14 +328,14 @@ void wfx_cancel_scan(void); /* * Call backs into the Matter Platform code */ -void wfx_started_notify(void); +void sl_matter_wifi_task_started(void); void wfx_connected_notify(int32_t status, sl_wfx_mac_address_t * ap); void wfx_disconnected_notify(int32_t status); + /* Implemented for LWIP */ -void wfx_host_received_sta_frame_cb(uint8_t * buf, int len); void wfx_lwip_set_sta_link_up(void); void wfx_lwip_set_sta_link_down(void); -void wfx_lwip_start(void); +void sl_matter_lwip_start(void); struct netif * wfx_get_netif(sl_wfx_interface_t interface); bool wfx_hw_ready(void); diff --git a/src/platform/silabs/wifi_args.gni b/src/platform/silabs/wifi_args.gni index 5d523bd3a65d8c..7b4da179daf885 100644 --- a/src/platform/silabs/wifi_args.gni +++ b/src/platform/silabs/wifi_args.gni @@ -21,9 +21,9 @@ import("${chip_root}/examples/platform/silabs/args.gni") import("${chip_root}/src/crypto/crypto.gni") # ARM architecture flags will be set based on silabs_family. -arm_platform_config = "${efr32_sdk_build_root}/silabs_arm.gni" +arm_platform_config = "${silabs_sdk_build_root}/silabs_arm.gni" -mbedtls_target = "${efr32_sdk_build_root}:efr32_sdk" +mbedtls_target = "${silabs_sdk_build_root}:silabs_sdk" # default to platform crypto implementation but allow commandline override if (chip_crypto == "") { @@ -35,7 +35,7 @@ if (chip_crypto == "") { chip_use_transitional_commissionable_data_provider = false # Use GSDK lwip instead of CHIP -lwip_root = "${efr32_sdk_build_root}/silabs_lwip" +lwip_root = "${silabs_sdk_build_root}/silabs_lwip" #lwip_platform = "external" lwip_platform = "silabs" diff --git a/src/system/BUILD.gn b/src/system/BUILD.gn index 40ae99ae99c77e..a8d15cf83f4223 100644 --- a/src/system/BUILD.gn +++ b/src/system/BUILD.gn @@ -177,7 +177,7 @@ source_set("system_config_header") { public_deps += [ "${lwip_root}:lwip" ] } else { if (chip_device_platform == "efr32") { - public_deps += [ "${efr32_sdk_build_root}:efr32_sdk" ] + public_deps += [ "${silabs_sdk_build_root}:silabs_sdk" ] } if (chip_device_platform == "qpg") { public_deps += [ "${qpg_sdk_build_root}:qpg_sdk" ] diff --git a/src/test_driver/efr32/BUILD.gn b/src/test_driver/efr32/BUILD.gn index 51fe90751ae219..9df7e4787a0325 100644 --- a/src/test_driver/efr32/BUILD.gn +++ b/src/test_driver/efr32/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/efr32_sdk.gni") +import("${silabs_sdk_build_root}/efr32_sdk.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") diff --git a/src/test_driver/efr32/args.gni b/src/test_driver/efr32/args.gni index 35be5dd63e3870..c4bc72c2a3cd97 100644 --- a/src/test_driver/efr32/args.gni +++ b/src/test_driver/efr32/args.gni @@ -38,7 +38,7 @@ pw_unit_test_BACKEND = "$dir_pw_unit_test:light" # Override the executable type and the test main's target. pw_unit_test_EXECUTABLE_TARGET_TYPE = "silabs_executable" pw_unit_test_EXECUTABLE_TARGET_TYPE_FILE = - "${efr32_sdk_build_root}/silabs_executable.gni" + "${silabs_sdk_build_root}/silabs_executable.gni" pw_unit_test_MAIN = "//:efr32_test_main" # Additional variables needed by silabs_executable that must be passed in to pw_test. diff --git a/third_party/openthread/platforms/efr32/BUILD.gn b/third_party/openthread/platforms/efr32/BUILD.gn index e270db2ae8757f..88f8f44c107e1b 100644 --- a/third_party/openthread/platforms/efr32/BUILD.gn +++ b/third_party/openthread/platforms/efr32/BUILD.gn @@ -18,8 +18,8 @@ import("//build_overrides/openthread.gni") import("//build_overrides/openthread.gni") -import("${efr32_sdk_build_root}/efr32_sdk.gni") -import("${efr32_sdk_build_root}/silabs_board.gni") +import("${silabs_sdk_build_root}/efr32_sdk.gni") +import("${silabs_sdk_build_root}/silabs_board.gni") config("openthread_efr32_config") { defines = [ @@ -48,7 +48,7 @@ source_set("openthread_core_config_efr32") { "${sl_ot_efr32_root}/openthread-core-efr32-config.h", ] - public_deps = [ "${efr32_sdk_build_root}:efr32_sdk" ] + public_deps = [ "${silabs_sdk_build_root}:silabs_sdk" ] public_configs = [ ":openthread_efr32_config" ] } diff --git a/third_party/silabs/BUILD.gn b/third_party/silabs/BUILD.gn index 16e0ba68c4607a..16d823dd4e73a3 100644 --- a/third_party/silabs/BUILD.gn +++ b/third_party/silabs/BUILD.gn @@ -18,12 +18,12 @@ import("//build_overrides/jlink.gni") import("//build_overrides/openthread.gni") import("${chip_root}/src/lwip/lwip.gni") import("${chip_root}/src/platform/device.gni") -import("${efr32_sdk_build_root}/silabs_board.gni") +import("${silabs_sdk_build_root}/silabs_board.gni") if (wifi_soc == true) { # CCP board - import("${efr32_sdk_build_root}/SiWx917_sdk.gni") + import("${silabs_sdk_build_root}/SiWx917_sdk.gni") } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") } declare_args() { @@ -49,7 +49,7 @@ config("silabs_config") { } assert(silabs_sdk_target != "", "silabs_sdk_target must be specified") -group("efr32_sdk") { +group("silabs_sdk") { public_deps = [ silabs_sdk_target ] public_configs = [ ":silabs_config" ] } @@ -117,7 +117,7 @@ if (wifi_soc != true) { # CCP board public_deps = [ ":libopenthread-platform", - "${efr32_sdk_build_root}:efr32_sdk", + "${silabs_sdk_build_root}:silabs_sdk", ] public_configs = [ ":openthread_efr32_config" ] @@ -190,7 +190,7 @@ if (wifi_soc != true) { # CCP board "${segger_rtt_root}:segger_rtt", ] - deps = [ "${efr32_sdk_build_root}:efr32_sdk" ] + deps = [ "${silabs_sdk_build_root}:silabs_sdk" ] # selected thread device type FTD or MTD XTD = "ftd" diff --git a/third_party/silabs/SiWx917_sdk.gni b/third_party/silabs/SiWx917_sdk.gni index 3accbed0bc12f2..ab94c6372d18e0 100644 --- a/third_party/silabs/SiWx917_sdk.gni +++ b/third_party/silabs/SiWx917_sdk.gni @@ -16,12 +16,11 @@ import("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") import("//build_overrides/jlink.gni") import("//build_overrides/mbedtls.gni") - import("${chip_root}/src/app/icd/icd.gni") import("${chip_root}/src/crypto/crypto.gni") import("${chip_root}/src/lib/lib.gni") import("${chip_root}/src/platform/silabs/wifi_args.gni") -import("${efr32_sdk_build_root}/efr32_sdk.gni") +import("${silabs_sdk_build_root}/efr32_sdk.gni") import("silabs_board.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" @@ -682,7 +681,6 @@ template("siwx917_sdk") { "${wifi_sdk_root}/components/device/silabs/si91x/wireless/src/sl_si91x_callback_framework.c", "${wifi_sdk_root}/components/device/silabs/si91x/wireless/src/sl_si91x_driver.c", "${wifi_sdk_root}/components/device/silabs/si91x/wireless/threading/sli_si91x_multithreaded.c", - "${wifi_sdk_root}/components/service/network_manager/si91x/sl_net_si91x.c", # modified hal "${efr32_sdk_root}/platform/emdrv/nvm3/src/nvm3_default_common_linker.c", @@ -829,7 +827,7 @@ template("siwx917_sdk") { "${_mbedtls_root}/library/ssl_srv.c", "${_mbedtls_root}/library/ssl_tls.c", "${_mbedtls_root}/library/x509.c", - "${efr32_sdk_build_root}/mqtt/stack/mqtt.c", + "${silabs_sdk_build_root}/mqtt/stack/mqtt.c", ] } diff --git a/third_party/silabs/lwip.gni b/third_party/silabs/lwip.gni index 9a35e7c45f7a61..db19c088398b68 100644 --- a/third_party/silabs/lwip.gni +++ b/third_party/silabs/lwip.gni @@ -13,7 +13,7 @@ # limitations under the License. import("//build_overrides/efr32_sdk.gni") import("//build_overrides/lwip.gni") -import("${efr32_sdk_build_root}/efr32_sdk.gni") +import("${silabs_sdk_build_root}/efr32_sdk.gni") # Defines a lwIP build target. # diff --git a/third_party/silabs/matter_support b/third_party/silabs/matter_support index fddcd73de5d30e..eab695e438ada9 160000 --- a/third_party/silabs/matter_support +++ b/third_party/silabs/matter_support @@ -1 +1 @@ -Subproject commit fddcd73de5d30e41036993dc575f78835fba6e7c +Subproject commit eab695e438ada903a18956eb916696678227cb0d diff --git a/third_party/silabs/silabs_lwip/BUILD.gn b/third_party/silabs/silabs_lwip/BUILD.gn index e148763a9ca70d..4d0bcb24c518f1 100644 --- a/third_party/silabs/silabs_lwip/BUILD.gn +++ b/third_party/silabs/silabs_lwip/BUILD.gn @@ -41,7 +41,7 @@ lwip_target("silabs_lwip") { public_deps = [ "${chip_root}/src/lwip:lwip_buildconfig", - "${efr32_sdk_build_root}:efr32_sdk", + "${silabs_sdk_build_root}:silabs_sdk", ] public_configs = [ From a10fc1f93551b61b1d69ddaf4fcb696696fe5e52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ludovic=20BOU=C3=89?= Date: Wed, 30 Oct 2024 22:45:41 +0100 Subject: [PATCH 020/121] energy-management-app: Fix chip-repl broken link (#36308) --- examples/energy-management-app/linux/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/energy-management-app/linux/README.md b/examples/energy-management-app/linux/README.md index 615f1f50dbc7de..b52a3ab131c5be 100644 --- a/examples/energy-management-app/linux/README.md +++ b/examples/energy-management-app/linux/README.md @@ -239,7 +239,7 @@ data (e.g. fabric info). ## CHIP-REPL Interaction - See chip-repl documentation in - [Matter_REPL_Intro](../../../docs/guides/repl/Matter_REPL_Intro.ipynb) + [Matter_REPL_Intro](../../../docs/development_controllers/chip-repl/Matter_REPL_Intro.ipynb) ### Building chip-repl: From 6fd08a0ec8be895af411ba9a42c58bea7bc7ecc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=C5=82osz=20Tomkiel?= Date: Wed, 30 Oct 2024 23:15:44 +0100 Subject: [PATCH 021/121] [Tizen] Add code coverage for tests on QEMU (#36245) * Add -coverage target * Allow to specify runner * Fix the .gcda files output location * Allow runner in interactive mode * Remove wrap * Fix expected test output * Collect common lcov args * Update scripts/build/builders/tizen.py Co-authored-by: Arkadiusz Bokowy --------- Co-authored-by: Andrei Litvin Co-authored-by: Arkadiusz Bokowy --- scripts/build/build/targets.py | 2 + scripts/build/builders/tizen.py | 51 +++++++++++++++++++ .../build/testdata/all_targets_linux_x64.txt | 2 +- src/test_driver/tizen/chip_tests/BUILD.gn | 7 ++- src/test_driver/tizen/chip_tests/runner.sh | 6 ++- .../integration_tests/lighting-app/BUILD.gn | 5 +- .../integration_tests/lighting-app/runner.sh | 4 ++ third_party/tizen/tizen_qemu.py | 12 +++-- third_party/tizen/tizen_sdk.gni | 2 + 9 files changed, 82 insertions(+), 9 deletions(-) diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index d86c36f328031e..52696de1cd25cf 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -692,6 +692,8 @@ def BuildTizenTarget(): target.AppendModifier("no-wifi", enable_wifi=False) target.AppendModifier("asan", use_asan=True) target.AppendModifier("ubsan", use_ubsan=True) + target.AppendModifier('coverage', use_coverage=True).OnlyIfRe( + '-tests') target.AppendModifier('with-ui', with_ui=True) return target diff --git a/scripts/build/builders/tizen.py b/scripts/build/builders/tizen.py index 8c7968888e67e5..e886558ba820ec 100644 --- a/scripts/build/builders/tizen.py +++ b/scripts/build/builders/tizen.py @@ -89,6 +89,7 @@ def __init__(self, use_asan: bool = False, use_tsan: bool = False, use_ubsan: bool = False, + use_coverage: bool = False, with_ui: bool = False, ): super(TizenBuilder, self).__init__( @@ -130,9 +131,59 @@ def __init__(self, raise Exception("TSAN sanitizer not supported by Tizen toolchain") if use_ubsan: self.extra_gn_options.append('is_ubsan=true') + self.use_coverage = use_coverage + if use_coverage: + self.extra_gn_options.append('use_coverage=true') if with_ui: self.extra_gn_options.append('chip_examples_enable_ui=true') + def generate(self): + super(TizenBuilder, self).generate() + if self.app == TizenApp.TESTS and self.use_coverage: + self.coverage_dir = os.path.join(self.output_dir, 'coverage') + self._Execute(['mkdir', '-p', self.coverage_dir], title="Create coverage output location") + + def lcov_args(self): + gcov = os.path.join(os.environ['TIZEN_SDK_TOOLCHAIN'], 'bin/arm-linux-gnueabi-gcov') + return [ + 'lcov', '--gcov-tool', gcov, '--ignore-errors', 'unused,mismatch', '--capture', '--directory', os.path.join( + self.output_dir, 'obj'), + '--exclude', '**/src/controller/*', + '--exclude', '**/connectedhomeip/zzz_generated/*', + '--exclude', '**/connectedhomeip/third_party/*', + '--exclude', '/opt/*', + ] + + def PreBuildCommand(self): + if self.app == TizenApp.TESTS and self.use_coverage: + cmd = ['ninja', '-C', self.output_dir] + + if self.ninja_jobs is not None: + cmd.append('-j' + str(self.ninja_jobs)) + + cmd.append('Tizen') + + self._Execute(cmd, title="Build-only") + + self._Execute(self.lcov_args() + [ + '--initial', + '--output-file', os.path.join(self.coverage_dir, 'lcov_base.info') + ], title="Initial coverage baseline") + + def PostBuildCommand(self): + if self.app == TizenApp.TESTS and self.use_coverage: + + self._Execute(self.lcov_args() + ['--output-file', os.path.join(self.coverage_dir, + 'lcov_test.info')], title="Update coverage") + + gcov = os.path.join(os.environ['TIZEN_SDK_TOOLCHAIN'], 'bin/arm-linux-gnueabi-gcov') + self._Execute(['lcov', '--gcov-tool', gcov, '--add-tracefile', os.path.join(self.coverage_dir, 'lcov_base.info'), + '--add-tracefile', os.path.join(self.coverage_dir, 'lcov_test.info'), + '--output-file', os.path.join(self.coverage_dir, 'lcov_final.info') + ], title="Final coverage info") + self._Execute(['genhtml', os.path.join(self.coverage_dir, 'lcov_final.info'), '--output-directory', + os.path.join(self.coverage_dir, 'html')], title="HTML coverage") + def GnBuildArgs(self): # Make sure that required ENV variables are defined for env in ('TIZEN_SDK_ROOT', 'TIZEN_SDK_SYSROOT'): diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index 58a1fc1021d305..5e17f58a8af78c 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -21,6 +21,6 @@ nrf-native-posix-64-tests nuttx-x64-light qpg-qpg6105-{lock,light,shell,persistent-storage,light-switch,thermostat}[-updateimage][-data-model-disabled][-data-model-enabled] stm32-stm32wb5mm-dk-light -tizen-arm-{all-clusters,chip-tool,light,tests}[-no-ble][-no-thread][-no-wifi][-asan][-ubsan][-with-ui] +tizen-arm-{all-clusters,chip-tool,light,tests}[-no-ble][-no-thread][-no-wifi][-asan][-ubsan][-coverage][-with-ui] telink-{tlsr9118bdk40d,tlsr9518adk80d,tlsr9528a,tlsr9528a_retention,tlsr9258a,tlsr9258a_retention}-{air-quality-sensor,all-clusters,all-clusters-minimal,bridge,contact-sensor,light,light-switch,lock,ota-requestor,pump,pump-controller,shell,smoke-co-alarm,temperature-measurement,thermostat,window-covering}[-ota][-dfu][-shell][-rpc][-factory-data][-4mb][-mars][-usb][-data-model-disabled][-data-model-enabled] openiotsdk-{shell,lock}[-mbedtls][-psa] diff --git a/src/test_driver/tizen/chip_tests/BUILD.gn b/src/test_driver/tizen/chip_tests/BUILD.gn index 47be87923546f5..ba72060b89afcd 100644 --- a/src/test_driver/tizen/chip_tests/BUILD.gn +++ b/src/test_driver/tizen/chip_tests/BUILD.gn @@ -24,12 +24,15 @@ tizen_qemu_run("chip-tests") { virtio_net = true # Share tests directory. - share = "${root_out_dir}/tests" + share = "${root_out_dir}" + + # Runner script file name. + runner = "runner-${target_name}.sh" # Copy runner script to shared directory. copy("${target_name}:runner") { sources = [ "runner.sh" ] - outputs = [ share + "/runner.sh" ] + outputs = [ share + "/" + runner ] } # Build CHIP unit tests. diff --git a/src/test_driver/tizen/chip_tests/runner.sh b/src/test_driver/tizen/chip_tests/runner.sh index 1cc401626cb230..cad90e20e00bcc 100755 --- a/src/test_driver/tizen/chip_tests/runner.sh +++ b/src/test_driver/tizen/chip_tests/runner.sh @@ -21,6 +21,10 @@ set -e # Print CHIP logs on stdout dlogutil CHIP & +# Set the correct path for .gcda files +export GCOV_PREFIX=/mnt/chip +export GCOV_PREFIX_STRIP=5 + FAILED=() STATUS=0 @@ -43,7 +47,7 @@ while IFS= read -r TEST; do echo -e "DONE: \e[31mFAIL\e[0m" fi -done < <(find /mnt/chip -type f -executable ! -name runner.sh) +done < <(find /mnt/chip/tests -type f -executable ! -name runner.sh) if [ ! "$STATUS" -eq 0 ]; then echo diff --git a/src/test_driver/tizen/integration_tests/lighting-app/BUILD.gn b/src/test_driver/tizen/integration_tests/lighting-app/BUILD.gn index 67de6abd80efea..49eabcc5c490aa 100644 --- a/src/test_driver/tizen/integration_tests/lighting-app/BUILD.gn +++ b/src/test_driver/tizen/integration_tests/lighting-app/BUILD.gn @@ -26,10 +26,13 @@ tizen_qemu_run("lighting-app") { # Share output directory. share = "${root_out_dir}" + # Runner script file name. + runner = "runner-${target_name}.sh" + # Copy runner script to shared directory. copy("${target_name}:runner") { sources = [ "runner.sh" ] - outputs = [ share + "/runner.sh" ] + outputs = [ share + "/" + runner ] } # Build applications used in the test. diff --git a/src/test_driver/tizen/integration_tests/lighting-app/runner.sh b/src/test_driver/tizen/integration_tests/lighting-app/runner.sh index 52e7562f47fc42..54ae160b1148b7 100755 --- a/src/test_driver/tizen/integration_tests/lighting-app/runner.sh +++ b/src/test_driver/tizen/integration_tests/lighting-app/runner.sh @@ -21,6 +21,10 @@ set -e # Print CHIP logs on stdout dlogutil CHIP & +# Set the correct path for .gcda files +export GCOV_PREFIX=/mnt/chip +export GCOV_PREFIX_STRIP=5 + # Install lighting Matter app pkgcmd -i -t tpk -p /mnt/chip/org.tizen.matter.*/out/org.tizen.matter.*.tpk # Launch lighting Matter app diff --git a/third_party/tizen/tizen_qemu.py b/third_party/tizen/tizen_qemu.py index 93bdfd3666ecf5..7b7eb412a23c04 100755 --- a/third_party/tizen/tizen_qemu.py +++ b/third_party/tizen/tizen_qemu.py @@ -66,9 +66,10 @@ "default: $TIZEN_SDK_ROOT/iot-sysdata.img")) parser.add_argument( '--share', type=str, - help=("host directory to share with the guest; if file named 'runner.sh' " - "is present at the root of that directory, it will be executed " - "automatically after boot")) + help=("host directory to share with the guest")) +parser.add_argument( + '--runner', type=str, + help=("path to the runner script which will run automatically after boot. path should be relative to shared directory")) parser.add_argument( '--output', metavar='FILE', default="/dev/null", help="store the QEMU output in a FILE") @@ -136,6 +137,9 @@ def whereis(binary_name): # Run root shell instead of the runner script. kernel_args += " rootshell" +if args.runner: + kernel_args += " runner=/mnt/chip/%s" % args.runner + qemu_args += [ '-kernel', args.kernel, '-append', kernel_args, @@ -153,7 +157,7 @@ def whereis(binary_name): for line in iter(proc.stdout.readline, b''): # Forward the output to the stdout and the log file. - sys.stdout.write(line.decode(sys.stdout.encoding)) + sys.stdout.write(line.decode(sys.stdout.encoding, errors='ignore')) sys.stdout.flush() output.write(line) diff --git a/third_party/tizen/tizen_sdk.gni b/third_party/tizen/tizen_sdk.gni index 72fb20777303b1..fbf82756a278ad 100644 --- a/third_party/tizen/tizen_sdk.gni +++ b/third_party/tizen/tizen_sdk.gni @@ -175,6 +175,7 @@ template("tizen_qemu_run") { testonly = true assert(defined(invoker.share), "It is required to specify path to share.") + assert(defined(invoker.runner), "It is required to specify runner script.") # Store QEMU output in a dedicated log file. output_log_file = "${root_out_dir}/tizen-qemu-" + target_name + ".log" @@ -186,6 +187,7 @@ template("tizen_qemu_run") { args = [ "--share=" + invoker.share, + "--runner=" + invoker.runner, "--output=" + rebase_path(output_log_file), ] if (defined(invoker.virtio_net) && invoker.virtio_net) { From a6f016813e7d3b43c119bc70d9498788bd876ec5 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 30 Oct 2024 18:56:02 -0400 Subject: [PATCH 022/121] Update Darwin availability annotations to account for new release. (#36304) --- .../Framework/CHIP/MTRBackwardsCompatShims.h | 21 +-- .../Framework/CHIP/MTRCertificateInfo.h | 2 +- src/darwin/Framework/CHIP/MTRClusterNames.h | 6 +- src/darwin/Framework/CHIP/MTRDevice.h | 2 +- .../Framework/CHIP/MTRDeviceController.h | 10 +- .../CHIP/MTRDeviceControllerDelegate.h | 2 +- .../CHIP/MTRDeviceControllerParameters.h | 8 +- src/darwin/Framework/CHIP/MTRDeviceType.h | 2 +- .../CHIP/XPC Protocol/MTRXPCClientProtocol.h | 6 +- .../CHIP/XPC Protocol/MTRXPCServerProtocol.h | 12 +- .../CHIP/templates/MTRClusterConstants.zapt | 2 +- .../CHIP/templates/availability.yaml | 17 +- .../CHIP/zap-generated/MTRBaseClusters.h | 177 +++++++----------- .../CHIP/zap-generated/MTRClusterConstants.h | 134 ++++++------- 14 files changed, 180 insertions(+), 221 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRBackwardsCompatShims.h b/src/darwin/Framework/CHIP/MTRBackwardsCompatShims.h index e1b935ca665810..592e1ac527234e 100644 --- a/src/darwin/Framework/CHIP/MTRBackwardsCompatShims.h +++ b/src/darwin/Framework/CHIP/MTRBackwardsCompatShims.h @@ -168,27 +168,20 @@ typedef NS_ENUM(uint8_t, MTROTASoftwareUpdateRequestorOTAUpdateState) { * SaturationMoveMode and SaturationStepMode. */ typedef NS_ENUM(uint8_t, MTRColorControlSaturationMoveMode) { - MTRColorControlSaturationMoveModeStop MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlMoveModeStop") + MTRColorControlSaturationMoveModeStop MTR_DEPRECATED("Please use MTRColorControlMoveModeStop", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x00, - MTRColorControlSaturationMoveModeUp MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlMoveModeUp") + MTRColorControlSaturationMoveModeUp MTR_DEPRECATED("Please use MTRColorControlMoveModeUp", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x01, - MTRColorControlSaturationMoveModeDown MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlMoveModeDown") + MTRColorControlSaturationMoveModeDown MTR_DEPRECATED("Please use MTRColorControlMoveModeDown", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x03, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlMoveMode"); +} MTR_DEPRECATED("Please use MTRColorControlMoveMode", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)); typedef NS_ENUM(uint8_t, MTRColorControlSaturationStepMode) { - MTRColorControlSaturationStepModeUp MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlStepModeUp") + MTRColorControlSaturationStepModeUp MTR_DEPRECATED("Please use MTRColorControlStepModeUp", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x01, - MTRColorControlSaturationStepModeDown MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlStepModeDown") + MTRColorControlSaturationStepModeDown MTR_DEPRECATED("Please use MTRColorControlStepModeDown", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x03, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlStepMode"); +} MTR_DEPRECATED("Please use MTRColorControlStepMode", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)); #pragma mark - Clusters that were removed wholesale: OnOffSwitchConfiguration diff --git a/src/darwin/Framework/CHIP/MTRCertificateInfo.h b/src/darwin/Framework/CHIP/MTRCertificateInfo.h index 88b64730f1260a..f6e67d51b1b736 100644 --- a/src/darwin/Framework/CHIP/MTRCertificateInfo.h +++ b/src/darwin/Framework/CHIP/MTRCertificateInfo.h @@ -68,7 +68,7 @@ MTR_AVAILABLE(ios(16.4), macos(13.3), watchos(9.4), tvos(16.4)) /** * Public key data for this certificate */ -@property (nullable, readonly, retain) NSData * publicKeyData MTR_NEWLY_AVAILABLE; +@property (nullable, readonly, retain) NSData * publicKeyData MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); @end diff --git a/src/darwin/Framework/CHIP/MTRClusterNames.h b/src/darwin/Framework/CHIP/MTRClusterNames.h index 46b5a5bfd55636..5dd8b744119574 100644 --- a/src/darwin/Framework/CHIP/MTRClusterNames.h +++ b/src/darwin/Framework/CHIP/MTRClusterNames.h @@ -49,7 +49,7 @@ MTR_EXTERN MTR_AVAILABLE(ios(17.6), macos(14.6), watchos(10.6), tvos(17.6)) NSSt * or '' (if the cluster ID is known but the command ID is not known) * will be returned. */ -MTR_EXTERN MTR_NEWLY_AVAILABLE NSString * MTRRequestCommandNameForID(MTRClusterIDType clusterID, MTRCommandIDType commandID); +MTR_EXTERN MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) NSString * MTRRequestCommandNameForID(MTRClusterIDType clusterID, MTRCommandIDType commandID); /** * Resolve Matter response (server to client) command IDs into a descriptive string. @@ -58,7 +58,7 @@ MTR_EXTERN MTR_NEWLY_AVAILABLE NSString * MTRRequestCommandNameForID(MTRClusterI * or '' (if the cluster ID is known but the command ID is not known) * will be returned. */ -MTR_EXTERN MTR_NEWLY_AVAILABLE NSString * MTRResponseCommandNameForID(MTRClusterIDType clusterID, MTRCommandIDType commandID); +MTR_EXTERN MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) NSString * MTRResponseCommandNameForID(MTRClusterIDType clusterID, MTRCommandIDType commandID); /** * Resolve Matter event IDs into a descriptive string. @@ -67,4 +67,4 @@ MTR_EXTERN MTR_NEWLY_AVAILABLE NSString * MTRResponseCommandNameForID(MTRCluster * or '' (if the cluster ID is known but the event ID is not known) * will be returned. */ -MTR_EXTERN MTR_NEWLY_AVAILABLE NSString * MTREventNameForID(MTRClusterIDType clusterID, MTREventIDType eventID); +MTR_EXTERN MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) NSString * MTREventNameForID(MTRClusterIDType clusterID, MTREventIDType eventID); diff --git a/src/darwin/Framework/CHIP/MTRDevice.h b/src/darwin/Framework/CHIP/MTRDevice.h index 5b19eb3bf434e4..2055bf8a877690 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.h +++ b/src/darwin/Framework/CHIP/MTRDevice.h @@ -212,7 +212,7 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) * documentation for MTRDeviceResponseHandler. Each one will have an * MTRAttributePathKey and an MTRDataKey. */ -- (NSArray *> *)readAttributePaths:(NSArray *)attributePaths MTR_NEWLY_AVAILABLE; +- (NSArray *> *)readAttributePaths:(NSArray *)attributePaths MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); /** * Invoke a command with a designated command path diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.h b/src/darwin/Framework/CHIP/MTRDeviceController.h index 0b553c9d43d25e..35a20c1ab43e25 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController.h @@ -68,7 +68,7 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) /** * If true, the controller has been suspended via `suspend` and not resumed yet. */ -@property (readonly, nonatomic, getter=isSuspended) BOOL suspended MTR_NEWLY_AVAILABLE; +@property (readonly, nonatomic, getter=isSuspended) BOOL suspended MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); /** * The ID assigned to this controller at creation time. @@ -210,14 +210,14 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) * @param[in] queue The queue on which the callbacks will be delivered */ - (void)addDeviceControllerDelegate:(id)delegate - queue:(dispatch_queue_t)queue MTR_NEWLY_AVAILABLE; + queue:(dispatch_queue_t)queue MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); /** * Removes a Delegate from the device controller * * @param[in] delegate The delegate to be removed */ -- (void)removeDeviceControllerDelegate:(id)delegate MTR_NEWLY_AVAILABLE; +- (void)removeDeviceControllerDelegate:(id)delegate MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); /** * Start scanning for commissionable devices. @@ -289,7 +289,7 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) * * Suspending an already-suspended controller has no effect. */ -- (void)suspend MTR_NEWLY_AVAILABLE; +- (void)suspend MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); /** * Resume the controller. This has no effect if the controller is not @@ -298,7 +298,7 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) * A resume following any number of suspend calls will resume the controller; * there does not need to be a resume call to match every suspend call. */ -- (void)resume MTR_NEWLY_AVAILABLE; +- (void)resume MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); /** * Shut down the controller. Calls to shutdown after the first one are NO-OPs. diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerDelegate.h b/src/darwin/Framework/CHIP/MTRDeviceControllerDelegate.h index 374b8aec2064aa..bd575e5a42def3 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerDelegate.h +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerDelegate.h @@ -112,7 +112,7 @@ MTR_AVAILABLE(ios(16.4), macos(13.3), watchos(9.4), tvos(16.4)) * the controller will be in the specified state. */ - (void)controller:(MTRDeviceController *)controller - suspendedChangedTo:(BOOL)suspended MTR_NEWLY_AVAILABLE; + suspendedChangedTo:(BOOL)suspended MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); @end typedef NS_ENUM(NSUInteger, MTRPairingStatus) { diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerParameters.h b/src/darwin/Framework/CHIP/MTRDeviceControllerParameters.h index c18a49ba3aaba6..8ba1ae7dff77a9 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerParameters.h +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerParameters.h @@ -153,11 +153,11 @@ MTR_AVAILABLE(ios(17.6), macos(14.6), watchos(10.6), tvos(17.6)) /** * The root certificate we were initialized with. */ -@property (nonatomic, copy, readonly) MTRCertificateDERBytes rootCertificate MTR_NEWLY_AVAILABLE; +@property (nonatomic, copy, readonly) MTRCertificateDERBytes rootCertificate MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); @end -MTR_NEWLY_AVAILABLE +MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) @interface MTRXPCDeviceControllerParameters : MTRDeviceControllerAbstractParameters - (instancetype)init NS_UNAVAILABLE; @@ -174,8 +174,8 @@ MTR_NEWLY_AVAILABLE - (instancetype)initWithXPConnectionBlock:(NSXPCConnection * (^)(void) )xpcConnectionBlock uniqueIdentifier:(NSUUID *)uniqueIdentifier; -@property (atomic, readonly, retain) NSUUID * uniqueIdentifier MTR_NEWLY_AVAILABLE; -@property (readonly, strong, nonatomic) NSXPCConnection * (^xpcConnectionBlock)(void) MTR_NEWLY_AVAILABLE; +@property (atomic, readonly, retain) NSUUID * uniqueIdentifier MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); +@property (readonly, strong, nonatomic) NSXPCConnection * (^xpcConnectionBlock)(void) MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); @end diff --git a/src/darwin/Framework/CHIP/MTRDeviceType.h b/src/darwin/Framework/CHIP/MTRDeviceType.h index aded23e7af514a..0330b76d1533a2 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceType.h +++ b/src/darwin/Framework/CHIP/MTRDeviceType.h @@ -23,7 +23,7 @@ NS_ASSUME_NONNULL_BEGIN -MTR_NEWLY_AVAILABLE +MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) @interface MTRDeviceType : NSObject /** diff --git a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h index bd9048e4595f81..7879ff61af6275 100644 --- a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h +++ b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCClientProtocol.h @@ -19,7 +19,7 @@ NS_ASSUME_NONNULL_BEGIN -MTR_NEWLY_AVAILABLE +MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) @protocol MTRXPCClientProtocol_MTRDevice - (oneway void)device:(NSNumber *)nodeID stateChanged:(MTRDeviceState)state; - (oneway void)device:(NSNumber *)nodeID receivedAttributeReport:(NSArray *> *)attributeReport; @@ -30,7 +30,7 @@ MTR_NEWLY_AVAILABLE - (oneway void)device:(NSNumber *)nodeID internalStateUpdated:(NSDictionary *)dictionary; @end -MTR_NEWLY_AVAILABLE +MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) @protocol MTRXPCClientProtocol_MTRDeviceController // Not Supported via XPC //- (oneway void)controller:(NSUUID *)controller statusUpdate:(MTRCommissioningStatus)status; @@ -41,7 +41,7 @@ MTR_NEWLY_AVAILABLE - (oneway void)controller:(NSUUID *)controller controllerConfigurationUpdated:(NSDictionary *)configuration; @end -MTR_NEWLY_AVAILABLE +MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) @protocol MTRXPCClientProtocol @end diff --git a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h index 1a468a133264bb..8290078765f471 100644 --- a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h +++ b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h @@ -18,14 +18,14 @@ NS_ASSUME_NONNULL_BEGIN -MTR_EXTERN NSString * const MTRDeviceControllerRegistrationNodeIDsKey MTR_NEWLY_AVAILABLE; -MTR_EXTERN NSString * const MTRDeviceControllerRegistrationNodeIDKey MTR_NEWLY_AVAILABLE; -MTR_EXTERN NSString * const MTRDeviceControllerRegistrationControllerContextKey MTR_NEWLY_AVAILABLE; +MTR_EXTERN NSString * const MTRDeviceControllerRegistrationNodeIDsKey MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); +MTR_EXTERN NSString * const MTRDeviceControllerRegistrationNodeIDKey MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); +MTR_EXTERN NSString * const MTRDeviceControllerRegistrationControllerContextKey MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); MTR_EXTERN NSString * const MTRDeviceControllerRegistrationControllerNodeIDKey MTR_NEWLY_AVAILABLE; MTR_EXTERN NSString * const MTRDeviceControllerRegistrationControllerIsRunningKey MTR_NEWLY_AVAILABLE; MTR_EXTERN NSString * const MTRDeviceControllerRegistrationDeviceInternalStateKey MTR_NEWLY_AVAILABLE; -MTR_NEWLY_AVAILABLE +MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) @protocol MTRXPCServerProtocol_MTRDevice - (oneway void)deviceController:(NSUUID *)controller nodeID:(NSNumber *)nodeID getStateWithReply:(void (^)(MTRDeviceState state))reply; @@ -53,7 +53,7 @@ MTR_NEWLY_AVAILABLE @end -MTR_NEWLY_AVAILABLE +MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) @protocol MTRXPCServerProtocol_MTRDeviceController @optional @@ -76,7 +76,7 @@ MTR_NEWLY_AVAILABLE @end -MTR_NEWLY_AVAILABLE +MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) @protocol MTRXPCServerProtocol @optional - (oneway void)deviceController:(NSUUID *)controller checkInWithContext:(NSDictionary *)context; diff --git a/src/darwin/Framework/CHIP/templates/MTRClusterConstants.zapt b/src/darwin/Framework/CHIP/templates/MTRClusterConstants.zapt index 606732b12a63cd..a2524dbf585b20 100644 --- a/src/darwin/Framework/CHIP/templates/MTRClusterConstants.zapt +++ b/src/darwin/Framework/CHIP/templates/MTRClusterConstants.zapt @@ -236,4 +236,4 @@ typedef NS_ENUM(uint32_t, MTRDeviceTypeIDType) { MTRDeviceTypeIDType{{asUpperCamelCase caption preserveAcronyms=true}}ID {{availability "" deviceType=(asUpperCamelCase caption preserveAcronyms=true)}} = {{asHex code 8}}, {{/if}} {{/zcl_device_types}} -} MTR_NEWLY_AVAILABLE; +} MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); diff --git a/src/darwin/Framework/CHIP/templates/availability.yaml b/src/darwin/Framework/CHIP/templates/availability.yaml index c8beeca6772ee1..60fe08f618c2d5 100644 --- a/src/darwin/Framework/CHIP/templates/availability.yaml +++ b/src/darwin/Framework/CHIP/templates/availability.yaml @@ -9682,8 +9682,12 @@ - Presets - MatterScheduleConfiguration -- release: "Future" - versions: "future" +- release: "6C44AB2F-2F6B-4B57-B523-5CD89584986F" + versions: + iOS: "18.2" + macOS: "15.2" + watchOS: "11.2" + tvOS: "18.2" introduced: enums: ColorControl: @@ -10077,3 +10081,12 @@ - ColorLoop - XY - ColorTemperature + +- release: "Future" + versions: "future" + provisional: + device types: + - BatteryStorage + - HeatPump + - SolarPower + - WaterHeater diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h index 9c1755c5414f8f..73008bfde7f718 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h @@ -19196,123 +19196,85 @@ typedef NS_ENUM(uint8_t, MTRColorControlColorLoopAction) { } MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); typedef NS_ENUM(uint8_t, MTRColorControlColorLoopDirection) { - MTRColorControlColorLoopDirectionDecrement MTR_NEWLY_AVAILABLE = 0x00, - MTRColorControlColorLoopDirectionDecrementHue MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlColorLoopDirectionDecrement") - = 0x00, - MTRColorControlColorLoopDirectionIncrement MTR_NEWLY_AVAILABLE = 0x01, - MTRColorControlColorLoopDirectionIncrementHue MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlColorLoopDirectionIncrement") - = 0x01, + MTRColorControlColorLoopDirectionDecrement MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00, + MTRColorControlColorLoopDirectionDecrementHue MTR_DEPRECATED("Please use MTRColorControlColorLoopDirectionDecrement", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x00, + MTRColorControlColorLoopDirectionIncrement MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x01, + MTRColorControlColorLoopDirectionIncrementHue MTR_DEPRECATED("Please use MTRColorControlColorLoopDirectionIncrement", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x01, } MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); typedef NS_ENUM(uint8_t, MTRColorControlColorMode) { MTRColorControlColorModeCurrentHueAndCurrentSaturation MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x00, MTRColorControlColorModeCurrentXAndCurrentY MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x01, - MTRColorControlColorModeColorTemperatureMireds MTR_NEWLY_AVAILABLE = 0x02, - MTRColorControlColorModeColorTemperature MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlColorModeColorTemperatureMireds") - = 0x02, + MTRColorControlColorModeColorTemperatureMireds MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x02, + MTRColorControlColorModeColorTemperature MTR_DEPRECATED("Please use MTRColorControlColorModeColorTemperatureMireds", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x02, } MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); typedef NS_ENUM(uint8_t, MTRColorControlDirection) { - MTRColorControlDirectionShortest MTR_NEWLY_AVAILABLE = 0x00, - MTRColorControlDirectionLongest MTR_NEWLY_AVAILABLE = 0x01, - MTRColorControlDirectionUp MTR_NEWLY_AVAILABLE = 0x02, - MTRColorControlDirectionDown MTR_NEWLY_AVAILABLE = 0x03, -} MTR_NEWLY_AVAILABLE; + MTRColorControlDirectionShortest MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00, + MTRColorControlDirectionLongest MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x01, + MTRColorControlDirectionUp MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x02, + MTRColorControlDirectionDown MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x03, +} MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); typedef NS_ENUM(uint8_t, MTRColorControlHueDirection) { - MTRColorControlHueDirectionShortestDistance MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlDirectionShortest") - = 0x00, - MTRColorControlHueDirectionLongestDistance MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlDirectionLongest") - = 0x01, - MTRColorControlHueDirectionUp MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlDirectionUp") - = 0x02, - MTRColorControlHueDirectionDown MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlDirectionDown") - = 0x03, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlDirection"); + MTRColorControlHueDirectionShortestDistance MTR_DEPRECATED("Please use MTRColorControlDirectionShortest", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x00, + MTRColorControlHueDirectionLongestDistance MTR_DEPRECATED("Please use MTRColorControlDirectionLongest", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x01, + MTRColorControlHueDirectionUp MTR_DEPRECATED("Please use MTRColorControlDirectionUp", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x02, + MTRColorControlHueDirectionDown MTR_DEPRECATED("Please use MTRColorControlDirectionDown", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x03, +} MTR_DEPRECATED("Please use MTRColorControlDirection", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)); typedef NS_ENUM(uint8_t, MTRColorControlDriftCompensation) { - MTRColorControlDriftCompensationNone MTR_NEWLY_AVAILABLE = 0x00, - MTRColorControlDriftCompensationOtherOrUnknown MTR_NEWLY_AVAILABLE = 0x01, - MTRColorControlDriftCompensationTemperatureMonitoring MTR_NEWLY_AVAILABLE = 0x02, - MTRColorControlDriftCompensationOpticalLuminanceMonitoringAndFeedback MTR_NEWLY_AVAILABLE = 0x03, - MTRColorControlDriftCompensationOpticalColorMonitoringAndFeedback MTR_NEWLY_AVAILABLE = 0x04, -} MTR_NEWLY_AVAILABLE; + MTRColorControlDriftCompensationNone MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00, + MTRColorControlDriftCompensationOtherOrUnknown MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x01, + MTRColorControlDriftCompensationTemperatureMonitoring MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x02, + MTRColorControlDriftCompensationOpticalLuminanceMonitoringAndFeedback MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x03, + MTRColorControlDriftCompensationOpticalColorMonitoringAndFeedback MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x04, +} MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); typedef NS_ENUM(uint8_t, MTRColorControlEnhancedColorMode) { - MTRColorControlEnhancedColorModeCurrentHueAndCurrentSaturation MTR_NEWLY_AVAILABLE = 0x00, - MTRColorControlEnhancedColorModeCurrentXAndCurrentY MTR_NEWLY_AVAILABLE = 0x01, - MTRColorControlEnhancedColorModeColorTemperatureMireds MTR_NEWLY_AVAILABLE = 0x02, - MTRColorControlEnhancedColorModeEnhancedCurrentHueAndCurrentSaturation MTR_NEWLY_AVAILABLE = 0x03, -} MTR_NEWLY_AVAILABLE; + MTRColorControlEnhancedColorModeCurrentHueAndCurrentSaturation MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00, + MTRColorControlEnhancedColorModeCurrentXAndCurrentY MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x01, + MTRColorControlEnhancedColorModeColorTemperatureMireds MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x02, + MTRColorControlEnhancedColorModeEnhancedCurrentHueAndCurrentSaturation MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x03, +} MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); typedef NS_ENUM(uint8_t, MTRColorControlMoveMode) { - MTRColorControlMoveModeStop MTR_NEWLY_AVAILABLE = 0x00, - MTRColorControlMoveModeUp MTR_NEWLY_AVAILABLE = 0x01, - MTRColorControlMoveModeDown MTR_NEWLY_AVAILABLE = 0x03, -} MTR_NEWLY_AVAILABLE; + MTRColorControlMoveModeStop MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00, + MTRColorControlMoveModeUp MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x01, + MTRColorControlMoveModeDown MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x03, +} MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); typedef NS_ENUM(uint8_t, MTRColorControlHueMoveMode) { - MTRColorControlHueMoveModeStop MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlMoveModeStop") - = 0x00, - MTRColorControlHueMoveModeUp MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlMoveModeUp") - = 0x01, - MTRColorControlHueMoveModeDown MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlMoveModeDown") - = 0x03, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlMoveMode"); + MTRColorControlHueMoveModeStop MTR_DEPRECATED("Please use MTRColorControlMoveModeStop", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x00, + MTRColorControlHueMoveModeUp MTR_DEPRECATED("Please use MTRColorControlMoveModeUp", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x01, + MTRColorControlHueMoveModeDown MTR_DEPRECATED("Please use MTRColorControlMoveModeDown", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x03, +} MTR_DEPRECATED("Please use MTRColorControlMoveMode", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)); typedef NS_ENUM(uint8_t, MTRColorControlStepMode) { - MTRColorControlStepModeUp MTR_NEWLY_AVAILABLE = 0x01, - MTRColorControlStepModeDown MTR_NEWLY_AVAILABLE = 0x03, -} MTR_NEWLY_AVAILABLE; + MTRColorControlStepModeUp MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x01, + MTRColorControlStepModeDown MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x03, +} MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); typedef NS_ENUM(uint8_t, MTRColorControlHueStepMode) { - MTRColorControlHueStepModeUp MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlStepModeUp") - = 0x01, - MTRColorControlHueStepModeDown MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlStepModeDown") - = 0x03, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlStepMode"); + MTRColorControlHueStepModeUp MTR_DEPRECATED("Please use MTRColorControlStepModeUp", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x01, + MTRColorControlHueStepModeDown MTR_DEPRECATED("Please use MTRColorControlStepModeDown", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x03, +} MTR_DEPRECATED("Please use MTRColorControlStepMode", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)); typedef NS_OPTIONS(uint16_t, MTRColorControlColorCapabilitiesBitmap) { - MTRColorControlColorCapabilitiesBitmapHueSaturation MTR_NEWLY_AVAILABLE = 0x1, - MTRColorControlColorCapabilitiesBitmapEnhancedHue MTR_NEWLY_AVAILABLE = 0x2, - MTRColorControlColorCapabilitiesBitmapColorLoop MTR_NEWLY_AVAILABLE = 0x4, - MTRColorControlColorCapabilitiesBitmapXY MTR_NEWLY_AVAILABLE = 0x8, - MTRColorControlColorCapabilitiesBitmapColorTemperature MTR_NEWLY_AVAILABLE = 0x10, -} MTR_NEWLY_AVAILABLE; + MTRColorControlColorCapabilitiesBitmapHueSaturation MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x1, + MTRColorControlColorCapabilitiesBitmapEnhancedHue MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x2, + MTRColorControlColorCapabilitiesBitmapColorLoop MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x4, + MTRColorControlColorCapabilitiesBitmapXY MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x8, + MTRColorControlColorCapabilitiesBitmapColorTemperature MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x10, +} MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); typedef NS_OPTIONS(uint16_t, MTRColorControlColorCapabilities) { - MTRColorControlColorCapabilitiesHueSaturationSupported MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlColorCapabilitiesBitmapHueSaturation") - = 0x1, - MTRColorControlColorCapabilitiesEnhancedHueSupported MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlColorCapabilitiesBitmapEnhancedHue") - = 0x2, - MTRColorControlColorCapabilitiesColorLoopSupported MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlColorCapabilitiesBitmapColorLoop") - = 0x4, - MTRColorControlColorCapabilitiesXYAttributesSupported MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlColorCapabilitiesBitmapXY") - = 0x8, - MTRColorControlColorCapabilitiesColorTemperatureSupported MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlColorCapabilitiesBitmapColorTemperature") - = 0x10, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlColorCapabilitiesBitmap"); + MTRColorControlColorCapabilitiesHueSaturationSupported MTR_DEPRECATED("Please use MTRColorControlColorCapabilitiesBitmapHueSaturation", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x1, + MTRColorControlColorCapabilitiesEnhancedHueSupported MTR_DEPRECATED("Please use MTRColorControlColorCapabilitiesBitmapEnhancedHue", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x2, + MTRColorControlColorCapabilitiesColorLoopSupported MTR_DEPRECATED("Please use MTRColorControlColorCapabilitiesBitmapColorLoop", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x4, + MTRColorControlColorCapabilitiesXYAttributesSupported MTR_DEPRECATED("Please use MTRColorControlColorCapabilitiesBitmapXY", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x8, + MTRColorControlColorCapabilitiesColorTemperatureSupported MTR_DEPRECATED("Please use MTRColorControlColorCapabilitiesBitmapColorTemperature", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x10, +} MTR_DEPRECATED("Please use MTRColorControlColorCapabilitiesBitmap", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)); typedef NS_OPTIONS(uint32_t, MTRColorControlFeature) { MTRColorControlFeatureHueAndSaturation MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) = 0x1, @@ -19323,31 +19285,22 @@ typedef NS_OPTIONS(uint32_t, MTRColorControlFeature) { } MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)); typedef NS_OPTIONS(uint8_t, MTRColorControlOptionsBitmap) { - MTRColorControlOptionsBitmapExecuteIfOff MTR_NEWLY_AVAILABLE = 0x1, -} MTR_NEWLY_AVAILABLE; + MTRColorControlOptionsBitmapExecuteIfOff MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x1, +} MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); typedef NS_OPTIONS(uint8_t, MTRColorControlUpdateFlagsBitmap) { - MTRColorControlUpdateFlagsBitmapUpdateAction MTR_NEWLY_AVAILABLE = 0x1, - MTRColorControlUpdateFlagsBitmapUpdateDirection MTR_NEWLY_AVAILABLE = 0x2, - MTRColorControlUpdateFlagsBitmapUpdateTime MTR_NEWLY_AVAILABLE = 0x4, - MTRColorControlUpdateFlagsBitmapUpdateStartHue MTR_NEWLY_AVAILABLE = 0x8, -} MTR_NEWLY_AVAILABLE; + MTRColorControlUpdateFlagsBitmapUpdateAction MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x1, + MTRColorControlUpdateFlagsBitmapUpdateDirection MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x2, + MTRColorControlUpdateFlagsBitmapUpdateTime MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x4, + MTRColorControlUpdateFlagsBitmapUpdateStartHue MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x8, +} MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); typedef NS_OPTIONS(uint8_t, MTRColorControlColorLoopUpdateFlags) { - MTRColorControlColorLoopUpdateFlagsUpdateAction MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlUpdateFlagsBitmapUpdateAction") - = 0x1, - MTRColorControlColorLoopUpdateFlagsUpdateDirection MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlUpdateFlagsBitmapUpdateDirection") - = 0x2, - MTRColorControlColorLoopUpdateFlagsUpdateTime MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlUpdateFlagsBitmapUpdateTime") - = 0x4, - MTRColorControlColorLoopUpdateFlagsUpdateStartHue MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlUpdateFlagsBitmapUpdateStartHue") - = 0x8, -} MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) - MTR_NEWLY_DEPRECATED("Please use MTRColorControlUpdateFlagsBitmap"); + MTRColorControlColorLoopUpdateFlagsUpdateAction MTR_DEPRECATED("Please use MTRColorControlUpdateFlagsBitmapUpdateAction", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x1, + MTRColorControlColorLoopUpdateFlagsUpdateDirection MTR_DEPRECATED("Please use MTRColorControlUpdateFlagsBitmapUpdateDirection", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x2, + MTRColorControlColorLoopUpdateFlagsUpdateTime MTR_DEPRECATED("Please use MTRColorControlUpdateFlagsBitmapUpdateTime", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x4, + MTRColorControlColorLoopUpdateFlagsUpdateStartHue MTR_DEPRECATED("Please use MTRColorControlUpdateFlagsBitmapUpdateStartHue", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)) = 0x8, +} MTR_DEPRECATED("Please use MTRColorControlUpdateFlagsBitmap", ios(16.1, 18.2), macos(13.0, 15.2), watchos(9.1, 11.2), tvos(16.1, 18.2)); typedef NS_OPTIONS(uint8_t, MTRBallastConfigurationBallastStatusBitmap) { MTRBallastConfigurationBallastStatusBitmapBallastNonOperational MTR_PROVISIONALLY_AVAILABLE = 0x1, diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h b/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h index c44b789060f895..a5e2650097b105 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h @@ -7562,74 +7562,74 @@ typedef NS_ENUM(uint32_t, MTREventIDType) { #pragma mark - Device Type IDs typedef NS_ENUM(uint32_t, MTRDeviceTypeIDType) { - MTRDeviceTypeIDTypeDoorLockID MTR_NEWLY_AVAILABLE = 0x0000000A, - MTRDeviceTypeIDTypeDoorLockControllerID MTR_NEWLY_AVAILABLE = 0x0000000B, - MTRDeviceTypeIDTypeAggregatorID MTR_NEWLY_AVAILABLE = 0x0000000E, - MTRDeviceTypeIDTypeGenericSwitchID MTR_NEWLY_AVAILABLE = 0x0000000F, - MTRDeviceTypeIDTypePowerSourceID MTR_NEWLY_AVAILABLE = 0x00000011, - MTRDeviceTypeIDTypeOTARequestorID MTR_NEWLY_AVAILABLE = 0x00000012, - MTRDeviceTypeIDTypeBridgedNodeID MTR_NEWLY_AVAILABLE = 0x00000013, - MTRDeviceTypeIDTypeOTAProviderID MTR_NEWLY_AVAILABLE = 0x00000014, - MTRDeviceTypeIDTypeContactSensorID MTR_NEWLY_AVAILABLE = 0x00000015, - MTRDeviceTypeIDTypeRootNodeID MTR_NEWLY_AVAILABLE = 0x00000016, + MTRDeviceTypeIDTypeDoorLockID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000000A, + MTRDeviceTypeIDTypeDoorLockControllerID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000000B, + MTRDeviceTypeIDTypeAggregatorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000000E, + MTRDeviceTypeIDTypeGenericSwitchID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000000F, + MTRDeviceTypeIDTypePowerSourceID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000011, + MTRDeviceTypeIDTypeOTARequestorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000012, + MTRDeviceTypeIDTypeBridgedNodeID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000013, + MTRDeviceTypeIDTypeOTAProviderID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000014, + MTRDeviceTypeIDTypeContactSensorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000015, + MTRDeviceTypeIDTypeRootNodeID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000016, MTRDeviceTypeIDTypeSolarPowerID MTR_PROVISIONALLY_AVAILABLE = 0x00000017, MTRDeviceTypeIDTypeBatteryStorageID MTR_PROVISIONALLY_AVAILABLE = 0x00000018, - MTRDeviceTypeIDTypeSecondaryNetworkInterfaceID MTR_NEWLY_AVAILABLE = 0x00000019, - MTRDeviceTypeIDTypeSpeakerID MTR_NEWLY_AVAILABLE = 0x00000022, - MTRDeviceTypeIDTypeCastingVideoPlayerID MTR_NEWLY_AVAILABLE = 0x00000023, - MTRDeviceTypeIDTypeContentAppID MTR_NEWLY_AVAILABLE = 0x00000024, - MTRDeviceTypeIDTypeModeSelectID MTR_NEWLY_AVAILABLE = 0x00000027, - MTRDeviceTypeIDTypeBasicVideoPlayerID MTR_NEWLY_AVAILABLE = 0x00000028, - MTRDeviceTypeIDTypeCastingVideoClientID MTR_NEWLY_AVAILABLE = 0x00000029, - MTRDeviceTypeIDTypeVideoRemoteControlID MTR_NEWLY_AVAILABLE = 0x0000002A, - MTRDeviceTypeIDTypeFanID MTR_NEWLY_AVAILABLE = 0x0000002B, - MTRDeviceTypeIDTypeAirQualitySensorID MTR_NEWLY_AVAILABLE = 0x0000002C, - MTRDeviceTypeIDTypeAirPurifierID MTR_NEWLY_AVAILABLE = 0x0000002D, - MTRDeviceTypeIDTypeWaterFreezeDetectorID MTR_NEWLY_AVAILABLE = 0x00000041, - MTRDeviceTypeIDTypeWaterValveID MTR_NEWLY_AVAILABLE = 0x00000042, - MTRDeviceTypeIDTypeWaterLeakDetectorID MTR_NEWLY_AVAILABLE = 0x00000043, - MTRDeviceTypeIDTypeRainSensorID MTR_NEWLY_AVAILABLE = 0x00000044, - MTRDeviceTypeIDTypeRefrigeratorID MTR_NEWLY_AVAILABLE = 0x00000070, - MTRDeviceTypeIDTypeTemperatureControlledCabinetID MTR_NEWLY_AVAILABLE = 0x00000071, - MTRDeviceTypeIDTypeRoomAirConditionerID MTR_NEWLY_AVAILABLE = 0x00000072, - MTRDeviceTypeIDTypeLaundryWasherID MTR_NEWLY_AVAILABLE = 0x00000073, - MTRDeviceTypeIDTypeRoboticVacuumCleanerID MTR_NEWLY_AVAILABLE = 0x00000074, - MTRDeviceTypeIDTypeDishwasherID MTR_NEWLY_AVAILABLE = 0x00000075, - MTRDeviceTypeIDTypeSmokeCOAlarmID MTR_NEWLY_AVAILABLE = 0x00000076, - MTRDeviceTypeIDTypeCookSurfaceID MTR_NEWLY_AVAILABLE = 0x00000077, - MTRDeviceTypeIDTypeCooktopID MTR_NEWLY_AVAILABLE = 0x00000078, - MTRDeviceTypeIDTypeMicrowaveOvenID MTR_NEWLY_AVAILABLE = 0x00000079, - MTRDeviceTypeIDTypeExtractorHoodID MTR_NEWLY_AVAILABLE = 0x0000007A, - MTRDeviceTypeIDTypeOvenID MTR_NEWLY_AVAILABLE = 0x0000007B, - MTRDeviceTypeIDTypeLaundryDryerID MTR_NEWLY_AVAILABLE = 0x0000007C, - MTRDeviceTypeIDTypeNetworkInfrastructureManagerID MTR_NEWLY_AVAILABLE = 0x00000090, - MTRDeviceTypeIDTypeThreadBorderRouterID MTR_NEWLY_AVAILABLE = 0x00000091, - MTRDeviceTypeIDTypeOnOffLightID MTR_NEWLY_AVAILABLE = 0x00000100, - MTRDeviceTypeIDTypeDimmableLightID MTR_NEWLY_AVAILABLE = 0x00000101, - MTRDeviceTypeIDTypeOnOffLightSwitchID MTR_NEWLY_AVAILABLE = 0x00000103, - MTRDeviceTypeIDTypeDimmerSwitchID MTR_NEWLY_AVAILABLE = 0x00000104, - MTRDeviceTypeIDTypeColorDimmerSwitchID MTR_NEWLY_AVAILABLE = 0x00000105, - MTRDeviceTypeIDTypeLightSensorID MTR_NEWLY_AVAILABLE = 0x00000106, - MTRDeviceTypeIDTypeOccupancySensorID MTR_NEWLY_AVAILABLE = 0x00000107, - MTRDeviceTypeIDTypeOnOffPlugInUnitID MTR_NEWLY_AVAILABLE = 0x0000010A, - MTRDeviceTypeIDTypeDimmablePlugInUnitID MTR_NEWLY_AVAILABLE = 0x0000010B, - MTRDeviceTypeIDTypeColorTemperatureLightID MTR_NEWLY_AVAILABLE = 0x0000010C, - MTRDeviceTypeIDTypeExtendedColorLightID MTR_NEWLY_AVAILABLE = 0x0000010D, - MTRDeviceTypeIDTypeWindowCoveringID MTR_NEWLY_AVAILABLE = 0x00000202, - MTRDeviceTypeIDTypeWindowCoveringControllerID MTR_NEWLY_AVAILABLE = 0x00000203, - MTRDeviceTypeIDTypeHeatingCoolingUnitID MTR_NEWLY_AVAILABLE = 0x00000300, - MTRDeviceTypeIDTypeThermostatID MTR_NEWLY_AVAILABLE = 0x00000301, - MTRDeviceTypeIDTypeTemperatureSensorID MTR_NEWLY_AVAILABLE = 0x00000302, - MTRDeviceTypeIDTypePumpID MTR_NEWLY_AVAILABLE = 0x00000303, - MTRDeviceTypeIDTypePumpControllerID MTR_NEWLY_AVAILABLE = 0x00000304, - MTRDeviceTypeIDTypePressureSensorID MTR_NEWLY_AVAILABLE = 0x00000305, - MTRDeviceTypeIDTypeFlowSensorID MTR_NEWLY_AVAILABLE = 0x00000306, - MTRDeviceTypeIDTypeHumiditySensorID MTR_NEWLY_AVAILABLE = 0x00000307, + MTRDeviceTypeIDTypeSecondaryNetworkInterfaceID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000019, + MTRDeviceTypeIDTypeSpeakerID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000022, + MTRDeviceTypeIDTypeCastingVideoPlayerID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000023, + MTRDeviceTypeIDTypeContentAppID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000024, + MTRDeviceTypeIDTypeModeSelectID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000027, + MTRDeviceTypeIDTypeBasicVideoPlayerID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000028, + MTRDeviceTypeIDTypeCastingVideoClientID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000029, + MTRDeviceTypeIDTypeVideoRemoteControlID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000002A, + MTRDeviceTypeIDTypeFanID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000002B, + MTRDeviceTypeIDTypeAirQualitySensorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000002C, + MTRDeviceTypeIDTypeAirPurifierID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000002D, + MTRDeviceTypeIDTypeWaterFreezeDetectorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000041, + MTRDeviceTypeIDTypeWaterValveID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000042, + MTRDeviceTypeIDTypeWaterLeakDetectorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000043, + MTRDeviceTypeIDTypeRainSensorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000044, + MTRDeviceTypeIDTypeRefrigeratorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000070, + MTRDeviceTypeIDTypeTemperatureControlledCabinetID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000071, + MTRDeviceTypeIDTypeRoomAirConditionerID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000072, + MTRDeviceTypeIDTypeLaundryWasherID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000073, + MTRDeviceTypeIDTypeRoboticVacuumCleanerID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000074, + MTRDeviceTypeIDTypeDishwasherID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000075, + MTRDeviceTypeIDTypeSmokeCOAlarmID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000076, + MTRDeviceTypeIDTypeCookSurfaceID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000077, + MTRDeviceTypeIDTypeCooktopID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000078, + MTRDeviceTypeIDTypeMicrowaveOvenID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000079, + MTRDeviceTypeIDTypeExtractorHoodID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000007A, + MTRDeviceTypeIDTypeOvenID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000007B, + MTRDeviceTypeIDTypeLaundryDryerID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000007C, + MTRDeviceTypeIDTypeNetworkInfrastructureManagerID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000090, + MTRDeviceTypeIDTypeThreadBorderRouterID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000091, + MTRDeviceTypeIDTypeOnOffLightID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000100, + MTRDeviceTypeIDTypeDimmableLightID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000101, + MTRDeviceTypeIDTypeOnOffLightSwitchID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000103, + MTRDeviceTypeIDTypeDimmerSwitchID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000104, + MTRDeviceTypeIDTypeColorDimmerSwitchID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000105, + MTRDeviceTypeIDTypeLightSensorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000106, + MTRDeviceTypeIDTypeOccupancySensorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000107, + MTRDeviceTypeIDTypeOnOffPlugInUnitID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000010A, + MTRDeviceTypeIDTypeDimmablePlugInUnitID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000010B, + MTRDeviceTypeIDTypeColorTemperatureLightID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000010C, + MTRDeviceTypeIDTypeExtendedColorLightID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000010D, + MTRDeviceTypeIDTypeWindowCoveringID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000202, + MTRDeviceTypeIDTypeWindowCoveringControllerID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000203, + MTRDeviceTypeIDTypeHeatingCoolingUnitID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000300, + MTRDeviceTypeIDTypeThermostatID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000301, + MTRDeviceTypeIDTypeTemperatureSensorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000302, + MTRDeviceTypeIDTypePumpID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000303, + MTRDeviceTypeIDTypePumpControllerID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000304, + MTRDeviceTypeIDTypePressureSensorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000305, + MTRDeviceTypeIDTypeFlowSensorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000306, + MTRDeviceTypeIDTypeHumiditySensorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000307, MTRDeviceTypeIDTypeHeatPumpID MTR_PROVISIONALLY_AVAILABLE = 0x00000309, - MTRDeviceTypeIDTypeEVSEID MTR_NEWLY_AVAILABLE = 0x0000050C, - MTRDeviceTypeIDTypeDeviceEnergyManagementID MTR_NEWLY_AVAILABLE = 0x0000050D, + MTRDeviceTypeIDTypeEVSEID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000050C, + MTRDeviceTypeIDTypeDeviceEnergyManagementID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x0000050D, MTRDeviceTypeIDTypeWaterHeaterID MTR_PROVISIONALLY_AVAILABLE = 0x0000050F, - MTRDeviceTypeIDTypeElectricalSensorID MTR_NEWLY_AVAILABLE = 0x00000510, - MTRDeviceTypeIDTypeControlBridgeID MTR_NEWLY_AVAILABLE = 0x00000840, - MTRDeviceTypeIDTypeOnOffSensorID MTR_NEWLY_AVAILABLE = 0x00000850, -} MTR_NEWLY_AVAILABLE; + MTRDeviceTypeIDTypeElectricalSensorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000510, + MTRDeviceTypeIDTypeControlBridgeID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000840, + MTRDeviceTypeIDTypeOnOffSensorID MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) = 0x00000850, +} MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)); From daf2bce48390c6f59b2d8d8fb467965958020738 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 31 Oct 2024 00:11:35 -0400 Subject: [PATCH 023/121] Switch `DataModel::Provider` interface to default enabled (except on linux where it stays as check) (#36042) * Switch data model provider usage to default to enabled * Decouple pump configuration and control from compatibility functions. Still 100% ember tied. * Fix up some private/public dependencies: instance header should always be a private dependency * Allow java (or generally dynamic server) controller builds to compile with dynamic dispatcher. Dynamic dispatcher seems to only care about commands so implemented all the rest as empty, which is not ideal * Restyled by clang-format * Restyled by gn * Better dynamic dispatch implementation, removed extra TODO functions * Restyled by whitespace * Update dep a bit more * Fix linter * Fix linter again * Update NXP to support various logging targets and for K32W0 enable progress logging and up (no detail/automation) * Fix nxp compile (ordering issue) * Update logic a bit to use log level for low power * Update builds to consider low power already removing logs * Make microwave oven cluster compilable * Restyle * Add codegen data model to darwin xproject: given that we add ember, we need these to access the ember bits as there is no app or data model to provide these * Add missing override for darwin dispatch when codegen data model uses lower level methods for ember access * Fix linter * Add ability to track structural changes in ember for the purpose of codegen data model caching * Fix typo: uint is unsigned * Restyle * Fix android to also provide a generation version * Fix another uint/unsigned typo ... oops * Add assertion of stack lock in darwin override of emberAfWriteAttribute * Restyled by isort * Remove formatting changes from python files * Pick up restyle changes too * Add comment on attribute laregest * Use TLV-based encoding for ember data buffer. This saves 2K of flash on some test devices, being much more efficient in code size compared to using datamodel code. * Restyled by clang-format * Restyled by shfmt * Undo unrelated change * Add some casts to make android compiler happy * Update darwin build project as well with the new files * Updates based on code review * Added unit tests for min/max int64 values * Rename PascalString to PascalStringType * Fix rename * Restyle * Add helper methods inside odd sized integers to localize code logic * Restyled by clang-format * Fix up negative ranges * Fixed ranges * Fix signed max bug and update unit tests * Make android happy * Typo fix * Switch up unit tests * Update a nullable check to make use of ValueToNullValue * Add namespace prefix * Update src/app/codegen-data-model-provider/EmberDataBuffer.cpp Co-authored-by: Boris Zbarsky * Update src/app/codegen-data-model-provider/EmberDataBuffer.h Co-authored-by: Boris Zbarsky * Correct comments:signed, not unsigned * Use constructors for the buffer info * Rename things to EmberAttributeDataBuffer * Undo submodule updates * Restyled by clang-format * Use EmberAttributeDataBuffer for codegen provider _Read * Fix comments * Restyled by clang-format * Update DynamicDispatcher comment * Rename file * Use a pointer for the subject descriptor. This seems to save about 88 bytes of flash on a test NRF board. * Restyle * Fix include * Fix include * Also fix PW rpc * This saves 136 bytes... * More changes to save slightly more flash for code * Restyle * Fix typo * Fix includes * make more detailed logging optional in the codegen data model and enable it only on known large platforms * Pull back the event path validity mixin, start with a datamodel implementation * Fix compile logic after I moved things away * Add one more check * Restyle * Fix typo * Fix includes * Restyle * Move decodable lists bits as a non-template class to save flash * Update src/app/InteractionModelEngine.cpp Co-authored-by: Boris Zbarsky * Rename method * Restyle * More renames * Restyle * Fix some renames * Restyle * A few more renames * Restyle * Use chip::app::IsSignedAttributeType * Fix up put as well as naming for null value and comment * Fix up nullable tests * Test that you cannot decode a null value for non-nullable double and single * Allow NAN for non-nullable floating points * Add test case for non nullable bool * Restyle * Add a header for efr32 * Update src/app/codegen-data-model-provider/EmberAttributeDataBuffer.cpp Co-authored-by: Boris Zbarsky * Update src/app/codegen-data-model-provider/EmberAttributeDataBuffer.cpp Co-authored-by: Boris Zbarsky * Remove extra comment * Replace switch with if * Comment fix * Another try to make efr32 build of tests happy * Move includes around, to try to work around issues within efr32 compiles... * more updates, this time local efr32 compiles * Remove lookup tables from ember attribute data buffer --------- Co-authored-by: Andrei Litvin Co-authored-by: Restyled.io Co-authored-by: Boris Zbarsky --- .github/workflows/examples-nxp.yaml | 4 +- .github/workflows/lint.yml | 13 ++-- build/chip/esp32/esp32_codegen.cmake | 2 +- config/esp32/components/chip/CMakeLists.txt | 2 +- config/mbed/CMakeLists.txt | 2 +- config/zephyr/Kconfig | 1 + src/app/BUILD.gn | 17 ++++- .../microwave-oven-control-server.cpp | 13 ++-- src/app/common_flags.gni | 2 +- src/app/dynamic_server/DynamicDispatcher.cpp | 64 +++++++++++++++++ .../zap-generated/endpoint_config.h | 2 + src/app/icd/client/BUILD.gn | 1 - .../include/zap-generated/endpoint_config.h | 4 ++ src/controller/java/BUILD.gn | 10 +++ .../CHIP/ServerEndpoint/MTRIMDispatch.mm | 9 +++ .../Matter.xcodeproj/project.pbxproj | 68 +++++++++++++++++++ 16 files changed, 196 insertions(+), 18 deletions(-) diff --git a/.github/workflows/examples-nxp.yaml b/.github/workflows/examples-nxp.yaml index c4b6eb148ae50b..f9c6392bdc71ed 100644 --- a/.github/workflows/examples-nxp.yaml +++ b/.github/workflows/examples-nxp.yaml @@ -70,7 +70,7 @@ jobs: run: | scripts/run_in_build_env.sh "\ ./scripts/build/build_examples.py \ - --target nxp-k32w0-freertos-lighting-factory \ + --target nxp-k32w0-freertos-lighting-factory-log-progress \ --target nxp-k32w0-freertos-contact-sensor-low-power-factory \ build \ --copy-artifacts-to out/artifacts \ @@ -79,7 +79,7 @@ jobs: run: | .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ nxp k32w0+release light \ - out/artifacts/nxp-k32w0-freertos-lighting-factory/chip-k32w0x-light-example.elf \ + out/artifacts/nxp-k32w0-freertos-lighting-factory-log-progress/chip-k32w0x-light-example.elf \ /tmp/bloat_reports/ - name: Get K32W0 contact sensor size stats run: | diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index a914e5ae369b50..68bf4b0310bffb 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -105,10 +105,8 @@ jobs: --known-failure app/reporting/reporting.cpp \ --known-failure app/reporting/tests/MockReportScheduler.cpp \ --known-failure app/reporting/tests/MockReportScheduler.h \ - --known-failure app/util/attribute-storage.cpp \ --known-failure app/util/attribute-storage-detail.h \ --known-failure app/util/attribute-storage.h \ - --known-failure app/util/attribute-table.cpp \ --known-failure app/util/attribute-table-detail.h \ --known-failure app/util/attribute-table.h \ --known-failure app/util/binding-table.cpp \ @@ -118,9 +116,7 @@ jobs: --known-failure app/util/DataModelHandler.h \ --known-failure app/util/ember-compatibility-functions.cpp \ --known-failure app/util/ember-compatibility-functions.h \ - --known-failure app/util/ember-global-attribute-access-interface.cpp \ --known-failure app/util/ember-global-attribute-access-interface.h \ - --known-failure app/util/ember-io-storage.cpp \ --known-failure app/util/ember-io-storage.h \ --known-failure app/util/endpoint-config-api.h \ --known-failure app/util/generic-callbacks.h \ @@ -135,7 +131,12 @@ jobs: --known-failure platform/GLibTypeDeleter.h \ --known-failure platform/SingletonConfigurationManager.cpp \ " - + # These ARE actually orphaned but due to dynamic-server we have code paths + # for them. Keeping them as a list as they still need review ... + # --known-failure app/util/attribute-table.cpp \ + # --known-failure app/util/ember-io-storage.cpp \ + # --known-failure app/util/ember-global-attribute-access-interface.cpp \ + # --known-failure app/util/attribute-storage.cpp \ - name: Check for matter lint errors if: always() run: | @@ -295,11 +296,13 @@ jobs: ':(exclude)examples/common/pigweed/rpc_services/Attributes.h' \ ':(exclude)src/app/codegen-data-model-provider/CodegenDataModelProvider_Write.cpp' \ ':(exclude)src/app/codegen-data-model-provider/tests/EmberReadWriteOverride.cpp' \ + ':(exclude)src/app/dynamic_server/DynamicDispatcher.cpp' \ ':(exclude)src/app/util/attribute-table.cpp' \ ':(exclude)src/app/util/attribute-table.h' \ ':(exclude)src/app/util/ember-compatibility-functions.cpp' \ ':(exclude)src/app/util/mock/CodegenEmberMocks.cpp' \ ':(exclude)src/app/zap-templates/templates/app/attributes/Accessors-src.zapt' \ + ':(exclude)src/darwin/Framework/CHIP/ServerEndpoint/MTRIMDispatch.mm' \ ':(exclude)zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.cpp' \ && exit 1 || exit 0 diff --git a/build/chip/esp32/esp32_codegen.cmake b/build/chip/esp32/esp32_codegen.cmake index 7febb089875172..9148912d568652 100644 --- a/build/chip/esp32/esp32_codegen.cmake +++ b/build/chip/esp32/esp32_codegen.cmake @@ -75,7 +75,7 @@ macro(chip_app_component_zapgen ZAP_NAME) # When data model interface is used, provide a default code-generation data model as # part of zapgen. See `chip_data_model.cmake` for similar logic - set(CHIP_DATA_MODEL_INTERFACE "disabled" CACHE STRING "Data model interface option to use: enabled or disabled") + set(CHIP_DATA_MODEL_INTERFACE "enabled" CACHE STRING "Data model interface option to use: enabled or disabled") if ("${CHIP_DATA_MODEL_INTERFACE}" STREQUAL "enabled") target_sources(${COMPONENT_LIB} PRIVATE ${CODEGEN_DATA_MODEL_SOURCES}) diff --git a/config/esp32/components/chip/CMakeLists.txt b/config/esp32/components/chip/CMakeLists.txt index fde62765dda808..f2036570b01a15 100644 --- a/config/esp32/components/chip/CMakeLists.txt +++ b/config/esp32/components/chip/CMakeLists.txt @@ -33,7 +33,7 @@ include(${CMAKE_CURRENT_LIST_DIR}/ota-image.cmake) set(CHIP_REQUIRE_COMPONENTS esp_eth freertos lwip bt mbedtls fatfs app_update console openthread nvs_flash spi_flash) -set(CHIP_DATA_MODEL_INTERFACE "disabled" CACHE STRING "Data model interface option to use: enabled or disabled") +set(CHIP_DATA_MODEL_INTERFACE "enabled" CACHE STRING "Data model interface option to use: enabled or disabled") if(NOT "${IDF_TARGET}" STREQUAL "esp32h2") list(APPEND CHIP_REQUIRE_COMPONENTS mdns) diff --git a/config/mbed/CMakeLists.txt b/config/mbed/CMakeLists.txt index 37dad135327e07..e74127b7c0073a 100644 --- a/config/mbed/CMakeLists.txt +++ b/config/mbed/CMakeLists.txt @@ -113,7 +113,7 @@ if (CONFIG_MBED_BSD_SOCKET_TRACE) endif() # Option can be set with `-DCHIP_DATA_MODEL_INTERFACE=enabled` or similar on the command line -set(CHIP_DATA_MODEL_INTERFACE "disabled" CACHE STRING "Data model interface option to use: enabled or disabled") +set(CHIP_DATA_MODEL_INTERFACE "enabled" CACHE STRING "Data model interface option to use: enabled or disabled") # ============================================================================== # Generate configuration for CHIP GN build system diff --git a/config/zephyr/Kconfig b/config/zephyr/Kconfig index 27598c7095c9aa..c98628e8070e7d 100644 --- a/config/zephyr/Kconfig +++ b/config/zephyr/Kconfig @@ -583,6 +583,7 @@ config CHIP_BLE_ADVERTISING_DURATION config USE_CHIP_DATA_MODEL_INTERFACE bool "Use a DataModel::Provider interface for data access" + default y help This enables a level of indiraction in the CHIP interaction model engine in accessing underlying data and executing operations such as diff --git a/src/app/BUILD.gn b/src/app/BUILD.gn index 0a000a2d005c6b..8849d39f507a34 100644 --- a/src/app/BUILD.gn +++ b/src/app/BUILD.gn @@ -226,6 +226,10 @@ static_library("interaction-model") { deps = [ "${chip_root}/src/app:events" ] + # Temporary dependency: codegen data provider instance should be provided + # by the application + deps += [ "${chip_root}/src/app/codegen-data-model-provider:instance-header" ] + public_deps = [ ":app_config", ":command-handler-impl", @@ -233,7 +237,6 @@ static_library("interaction-model") { ":paths", ":subscription-info-provider", "${chip_root}/src/app/MessageDef", - "${chip_root}/src/app/codegen-data-model-provider:instance-header", "${chip_root}/src/app/data-model-provider", "${chip_root}/src/app/icd/server:icd-server-config", "${chip_root}/src/app/icd/server:manager", @@ -291,13 +294,23 @@ static_library("interaction-model") { "clusters/ota-provider/ota-provider.cpp", "dynamic_server/AccessControl.cpp", "dynamic_server/AccessControl.h", + ] + + # DynamicDispatcher is actually an ember-override that takes over + # util/attribute-storage.cpp and util/attribute-table.cpp functions. + # + # We likely should formalize and change this with a proper DataModel::Provider that + # is consistent instead + sources += [ + "${chip_root}/src/app/util/ember-global-attribute-access-interface.cpp", + "${chip_root}/src/app/util/ember-io-storage.cpp", "dynamic_server/DynamicDispatcher.cpp", ] public_deps += [ ":global-attributes", "${chip_root}/src/access", - "${chip_root}/src/app/dynamic_server:mock-codegen-includes", + "${chip_root}/src/app/common:attribute-type", ] public_configs += [ ":config-controller-dynamic-server" ] diff --git a/src/app/clusters/microwave-oven-control-server/microwave-oven-control-server.cpp b/src/app/clusters/microwave-oven-control-server/microwave-oven-control-server.cpp index 73a3eb8a96774b..c012ddbb367eeb 100644 --- a/src/app/clusters/microwave-oven-control-server/microwave-oven-control-server.cpp +++ b/src/app/clusters/microwave-oven-control-server/microwave-oven-control-server.cpp @@ -248,11 +248,16 @@ void Instance::HandleSetCookingParameters(HandlerContext & ctx, const Commands:: if (startAfterSetting.HasValue()) { + ConcreteCommandPath commandPath(mEndpointId, OperationalState::Id, OperationalState::Commands::Start::Id); + +#if CHIP_CONFIG_USE_EMBER_DATA_MODEL + bool commandExists = ServerClusterCommandExists(commandPath) == Status::Success; +#else + bool commandExists = + InteractionModelEngine::GetInstance()->GetDataModelProvider()->GetAcceptedCommandInfo(commandPath).has_value(); +#endif VerifyOrExit( - ServerClusterCommandExists( - ConcreteCommandPath(mEndpointId, OperationalState::Id, OperationalState::Commands::Start::Id)) == Status::Success, - status = Status::InvalidCommand; - ChipLogError( + commandExists, status = Status::InvalidCommand; ChipLogError( Zcl, "Microwave Oven Control: Failed to set cooking parameters, Start command of operational state is not supported")); } diff --git a/src/app/common_flags.gni b/src/app/common_flags.gni index e5d5748153d09c..4dbbcb4fa3e145 100644 --- a/src/app/common_flags.gni +++ b/src/app/common_flags.gni @@ -32,7 +32,7 @@ declare_args() { if (matter_enable_recommended && current_os == "linux") { chip_use_data_model_interface = "check" } else { - chip_use_data_model_interface = "disabled" + chip_use_data_model_interface = "enabled" } # Whether we call `chipDie` on DM `check` errors diff --git a/src/app/dynamic_server/DynamicDispatcher.cpp b/src/app/dynamic_server/DynamicDispatcher.cpp index e1f458f0bc3df1..0c9825d6792eb4 100644 --- a/src/app/dynamic_server/DynamicDispatcher.cpp +++ b/src/app/dynamic_server/DynamicDispatcher.cpp @@ -32,7 +32,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -57,6 +59,8 @@ namespace { // AccessControl.cpp. constexpr EndpointId kSupportedEndpoint = 0; +DataVersion gMockDataVersion = 0; + } // anonymous namespace namespace chip { @@ -381,3 +385,63 @@ const EmberAfCluster * emberAfFindServerCluster(EndpointId endpoint, ClusterId c return nullptr; } + +unsigned emberAfMetadataStructureGeneration() +{ + // DynamicDispatcher at this point hardcodes a single OTA provider cluster. + // The structure does not change over time, so the current version stays at 0. + return 0; +} + +Protocols::InteractionModel::Status emberAfWriteAttribute(const ConcreteAttributePath & path, const EmberAfWriteDataInput & input) +{ + return Protocols::InteractionModel::Status::UnsupportedAttribute; +} + +Protocols::InteractionModel::Status emAfReadOrWriteAttribute(const EmberAfAttributeSearchRecord * attRecord, + const EmberAfAttributeMetadata ** metadata, uint8_t * buffer, + uint16_t readLength, bool write) +{ + return Protocols::InteractionModel::Status::UnsupportedAttribute; +} + +void emberAfAttributeChanged(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, + AttributesChangedListener * listener) +{ + gMockDataVersion++; + listener->MarkDirty(AttributePathParams(endpoint, clusterId, attributeId)); +} + +DataVersion * emberAfDataVersionStorage(const ConcreteClusterPath & aConcreteClusterPath) +{ + return &gMockDataVersion; +} + +Protocols::InteractionModel::Status emAfWriteAttributeExternal(const ConcreteAttributePath & path, + const EmberAfWriteDataInput & input) +{ + return Protocols::InteractionModel::Status::UnsupportedAttribute; +} + +Span emberAfDeviceTypeListFromEndpointIndex(unsigned endpointIndex, CHIP_ERROR & err) +{ + err = CHIP_ERROR_NOT_IMPLEMENTED; + return Span(); +} + +const EmberAfCluster * emberAfFindClusterInType(const EmberAfEndpointType * endpointType, ClusterId clusterId, + EmberAfClusterMask mask, uint8_t * index) +{ + if ((endpointType == &otaProviderEndpoint) && (clusterId == Clusters::OtaSoftwareUpdateProvider::Id)) + { + return &otaProviderCluster; + } + + return nullptr; +} + +const EmberAfAttributeMetadata * emberAfLocateAttributeMetadata(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId) +{ + // no known attributes even for OTA + return nullptr; +} diff --git a/src/app/dynamic_server/mock_includes/zap-generated/endpoint_config.h b/src/app/dynamic_server/mock_includes/zap-generated/endpoint_config.h index 80fa88048d1782..08227c50ed59e9 100644 --- a/src/app/dynamic_server/mock_includes/zap-generated/endpoint_config.h +++ b/src/app/dynamic_server/mock_includes/zap-generated/endpoint_config.h @@ -21,3 +21,5 @@ // Some overrides to see that this is not used as a real "endpoint_config" that contains data #define GENERATED_DEFAULTS #error "Not a real codegen. This is a temporary include for dynamic-overrides only" #define GENERATED_CLUSTERS #error "Not a real codegen. This is a temporary include for dynamic-overrides only" + +#define ATTRIBUTE_LARGEST (1003) diff --git a/src/app/icd/client/BUILD.gn b/src/app/icd/client/BUILD.gn index 4d59a627a4bcbb..b56bb98ccd7f8a 100644 --- a/src/app/icd/client/BUILD.gn +++ b/src/app/icd/client/BUILD.gn @@ -46,7 +46,6 @@ source_set("handler") { ] public_deps = [ ":manager", - "${chip_root}/src/app", "${chip_root}/src/controller", "${chip_root}/src/lib/core", "${chip_root}/src/messaging", diff --git a/src/app/util/mock/include/zap-generated/endpoint_config.h b/src/app/util/mock/include/zap-generated/endpoint_config.h index 620e6e29880f36..76781a4cc886b4 100644 --- a/src/app/util/mock/include/zap-generated/endpoint_config.h +++ b/src/app/util/mock/include/zap-generated/endpoint_config.h @@ -1,4 +1,8 @@ // Number of fixed endpoints #define FIXED_ENDPOINT_COUNT (3) +// This is one of the defines that endpoint_config generally has. In particular this +// can (and is) used to size I/O buffers for attribute reads (like ember-io-storage.cpp). +// +// Define this to a large number, matching what an all-clusters-app has. #define ATTRIBUTE_LARGEST (1003) diff --git a/src/controller/java/BUILD.gn b/src/controller/java/BUILD.gn index 2ae828ad09c47e..c1e05cff40fb42 100644 --- a/src/controller/java/BUILD.gn +++ b/src/controller/java/BUILD.gn @@ -19,6 +19,7 @@ import("${chip_root}/build/chip/buildconfig_header.gni") import("${chip_root}/build/chip/java/config.gni") import("${chip_root}/build/chip/java/rules.gni") import("${chip_root}/build/chip/tests.gni") +import("${chip_root}/src/app/codegen-data-model-provider/model.gni") import("${chip_root}/src/app/common_flags.gni") import("${chip_root}/src/platform/device.gni") @@ -171,6 +172,15 @@ shared_library("jni") { defines += [ "CHIP_CONFIG_SKIP_APP_SPECIFIC_GENERATED_HEADER_INCLUDES=1" ] deps += [ "${chip_root}/src/controller:nodatamodel" ] + + # Temporary dependency: InteractionModelEngine NEEDS a codegen data model instance + # defined and application is supposed to provide it. This adds the sources + # in the same way "data_model" implementations do + # + # DynamicDispatcher in src/app:interaction-model implements the actual required + # ember callbacks in this case... + sources += codegen_data_model_SOURCES + public_deps = codegen_data_model_PUBLIC_DEPS } else { deps += [ "${chip_root}/src/controller/data_model" ] } diff --git a/src/darwin/Framework/CHIP/ServerEndpoint/MTRIMDispatch.mm b/src/darwin/Framework/CHIP/ServerEndpoint/MTRIMDispatch.mm index d21242956b01bf..f719e07f34fcce 100644 --- a/src/darwin/Framework/CHIP/ServerEndpoint/MTRIMDispatch.mm +++ b/src/darwin/Framework/CHIP/ServerEndpoint/MTRIMDispatch.mm @@ -50,6 +50,15 @@ void emberAfClusterInitCallback(EndpointId endpoint, ClusterId clusterId) return Protocols::InteractionModel::Status::UnsupportedAttribute; } +Protocols::InteractionModel::Status emberAfWriteAttribute(const ConcreteAttributePath & path, const EmberAfWriteDataInput & input) +{ + assertChipStackLockedByCurrentThread(); + + // All of our attributes are handled via AttributeAccessInterface, so this + // should be unreached. + return Protocols::InteractionModel::Status::UnsupportedAttribute; +} + namespace chip { namespace app { diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index a21e90d726ec0b..7893475aa6050c 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -266,6 +266,26 @@ 754784672BFE93B00089C372 /* MTRDeviceStorageBehaviorConfiguration.h in Headers */ = {isa = PBXBuildFile; fileRef = 754784632BFE65B70089C372 /* MTRDeviceStorageBehaviorConfiguration.h */; settings = {ATTRIBUTES = (Public, ); }; }; 754F3DF427FBB94B00E60580 /* MTREventTLVValueDecoder_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 754F3DF327FBB94B00E60580 /* MTREventTLVValueDecoder_Internal.h */; }; 7560FD1C27FBBD3F005E85B3 /* MTREventTLVValueDecoder.mm in Sources */ = {isa = PBXBuildFile; fileRef = 7560FD1B27FBBD3F005E85B3 /* MTREventTLVValueDecoder.mm */; }; + 7592BCF32CBEE98C00EB74A0 /* Instance.h in Headers */ = {isa = PBXBuildFile; fileRef = 7592BCF12CBEE98C00EB74A0 /* Instance.h */; }; + 7592BCF42CBEE98C00EB74A0 /* EmberMetadata.h in Headers */ = {isa = PBXBuildFile; fileRef = 7592BCEF2CBEE98C00EB74A0 /* EmberMetadata.h */; }; + 7592BCF52CBEE98C00EB74A0 /* CodegenDataModelProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = 7592BCEB2CBEE98C00EB74A0 /* CodegenDataModelProvider.h */; }; + 7592BCF62CBEE98C00EB74A0 /* CodegenDataModelProvider_Read.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7592BCED2CBEE98C00EB74A0 /* CodegenDataModelProvider_Read.cpp */; }; + 7592BCF72CBEE98C00EB74A0 /* Instance.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7592BCF22CBEE98C00EB74A0 /* Instance.cpp */; }; + 7592BCF82CBEE98C00EB74A0 /* EmberMetadata.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7592BCF02CBEE98C00EB74A0 /* EmberMetadata.cpp */; }; + 7592BCF92CBEE98C00EB74A0 /* CodegenDataModelProvider.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7592BCEC2CBEE98C00EB74A0 /* CodegenDataModelProvider.cpp */; }; + 7592BCFA2CBEE98C00EB74A0 /* CodegenDataModelProvider_Write.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7592BCEE2CBEE98C00EB74A0 /* CodegenDataModelProvider_Write.cpp */; }; + 7592BCFB2CBEE98C00EB74A0 /* CodegenDataModelProvider_Read.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7592BCED2CBEE98C00EB74A0 /* CodegenDataModelProvider_Read.cpp */; }; + 7592BCFC2CBEE98C00EB74A0 /* Instance.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7592BCF22CBEE98C00EB74A0 /* Instance.cpp */; }; + 7592BCFD2CBEE98C00EB74A0 /* EmberMetadata.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7592BCF02CBEE98C00EB74A0 /* EmberMetadata.cpp */; }; + 7592BCFE2CBEE98C00EB74A0 /* CodegenDataModelProvider.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7592BCEC2CBEE98C00EB74A0 /* CodegenDataModelProvider.cpp */; }; + 7592BCFF2CBEE98C00EB74A0 /* CodegenDataModelProvider_Write.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7592BCEE2CBEE98C00EB74A0 /* CodegenDataModelProvider_Write.cpp */; }; + 7592BD002CBEE98C00EB74A0 /* Instance.h in Headers */ = {isa = PBXBuildFile; fileRef = 7592BCF12CBEE98C00EB74A0 /* Instance.h */; }; + 7592BD012CBEE98C00EB74A0 /* EmberMetadata.h in Headers */ = {isa = PBXBuildFile; fileRef = 7592BCEF2CBEE98C00EB74A0 /* EmberMetadata.h */; }; + 7592BD022CBEE98C00EB74A0 /* CodegenDataModelProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = 7592BCEB2CBEE98C00EB74A0 /* CodegenDataModelProvider.h */; }; + 7592BD0B2CC6BCC300EB74A0 /* EmberAttributeDataBuffer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7592BD0A2CC6BCC300EB74A0 /* EmberAttributeDataBuffer.cpp */; }; + 7592BD0C2CC6BCC300EB74A0 /* EmberAttributeDataBuffer.h in Headers */ = {isa = PBXBuildFile; fileRef = 7592BD092CC6BCC300EB74A0 /* EmberAttributeDataBuffer.h */; }; + 7592BD0D2CC6BCC300EB74A0 /* EmberAttributeDataBuffer.h in Headers */ = {isa = PBXBuildFile; fileRef = 7592BD092CC6BCC300EB74A0 /* EmberAttributeDataBuffer.h */; }; + 7592BD0E2CC6BCC300EB74A0 /* EmberAttributeDataBuffer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 7592BD0A2CC6BCC300EB74A0 /* EmberAttributeDataBuffer.cpp */; }; 7596A83E28751220004DAE0E /* MTRBaseClusters_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 7596A83D28751220004DAE0E /* MTRBaseClusters_Internal.h */; }; 7596A84428762729004DAE0E /* MTRDevice.h in Headers */ = {isa = PBXBuildFile; fileRef = 7596A84228762729004DAE0E /* MTRDevice.h */; settings = {ATTRIBUTES = (Public, ); }; }; 7596A84528762729004DAE0E /* MTRDevice.mm in Sources */ = {isa = PBXBuildFile; fileRef = 7596A84328762729004DAE0E /* MTRDevice.mm */; }; @@ -729,6 +749,16 @@ 754784662BFE6B890089C372 /* MTRDeviceStorageBehaviorConfiguration_Internal.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDeviceStorageBehaviorConfiguration_Internal.h; sourceTree = ""; }; 754F3DF327FBB94B00E60580 /* MTREventTLVValueDecoder_Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MTREventTLVValueDecoder_Internal.h; sourceTree = ""; }; 7560FD1B27FBBD3F005E85B3 /* MTREventTLVValueDecoder.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MTREventTLVValueDecoder.mm; sourceTree = ""; }; + 7592BCEB2CBEE98C00EB74A0 /* CodegenDataModelProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CodegenDataModelProvider.h; sourceTree = ""; }; + 7592BCEC2CBEE98C00EB74A0 /* CodegenDataModelProvider.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CodegenDataModelProvider.cpp; sourceTree = ""; }; + 7592BCED2CBEE98C00EB74A0 /* CodegenDataModelProvider_Read.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CodegenDataModelProvider_Read.cpp; sourceTree = ""; }; + 7592BCEE2CBEE98C00EB74A0 /* CodegenDataModelProvider_Write.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CodegenDataModelProvider_Write.cpp; sourceTree = ""; }; + 7592BCEF2CBEE98C00EB74A0 /* EmberMetadata.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = EmberMetadata.h; sourceTree = ""; }; + 7592BCF02CBEE98C00EB74A0 /* EmberMetadata.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = EmberMetadata.cpp; sourceTree = ""; }; + 7592BCF12CBEE98C00EB74A0 /* Instance.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Instance.h; sourceTree = ""; }; + 7592BCF22CBEE98C00EB74A0 /* Instance.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = Instance.cpp; sourceTree = ""; }; + 7592BD092CC6BCC300EB74A0 /* EmberAttributeDataBuffer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = EmberAttributeDataBuffer.h; sourceTree = ""; }; + 7592BD0A2CC6BCC300EB74A0 /* EmberAttributeDataBuffer.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = EmberAttributeDataBuffer.cpp; sourceTree = ""; }; 7596A83D28751220004DAE0E /* MTRBaseClusters_Internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MTRBaseClusters_Internal.h; sourceTree = ""; }; 7596A84228762729004DAE0E /* MTRDevice.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRDevice.h; sourceTree = ""; }; 7596A84328762729004DAE0E /* MTRDevice.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDevice.mm; sourceTree = ""; }; @@ -1127,6 +1157,7 @@ 1E857311265519DE0050A4D9 /* app */ = { isa = PBXGroup; children = ( + 7521D2932CBECE3F00218E16 /* codegen-data-model-provider */, 75A202E72BA8DBB700A771DD /* reporting */, 5143041F2914CED9004DC7FE /* generic-callback-stubs.cpp */, 514C79F22B62ED5500DD6D7B /* attribute-storage.cpp */, @@ -1287,6 +1318,23 @@ path = ServerEndpoint; sourceTree = ""; }; + 7521D2932CBECE3F00218E16 /* codegen-data-model-provider */ = { + isa = PBXGroup; + children = ( + 7592BD092CC6BCC300EB74A0 /* EmberAttributeDataBuffer.h */, + 7592BD0A2CC6BCC300EB74A0 /* EmberAttributeDataBuffer.cpp */, + 7592BCEB2CBEE98C00EB74A0 /* CodegenDataModelProvider.h */, + 7592BCEC2CBEE98C00EB74A0 /* CodegenDataModelProvider.cpp */, + 7592BCED2CBEE98C00EB74A0 /* CodegenDataModelProvider_Read.cpp */, + 7592BCEE2CBEE98C00EB74A0 /* CodegenDataModelProvider_Write.cpp */, + 7592BCEF2CBEE98C00EB74A0 /* EmberMetadata.h */, + 7592BCF02CBEE98C00EB74A0 /* EmberMetadata.cpp */, + 7592BCF12CBEE98C00EB74A0 /* Instance.h */, + 7592BCF22CBEE98C00EB74A0 /* Instance.cpp */, + ); + path = "codegen-data-model-provider"; + sourceTree = ""; + }; 75A202E72BA8DBB700A771DD /* reporting */ = { isa = PBXGroup; children = ( @@ -1673,6 +1721,7 @@ 037C3DCE2991BD5100B7EEE2 /* CHIPCommandBridge.h in Headers */, 512431272BA0C8BF000BC136 /* SetMRPParametersCommand.h in Headers */, 037C3DD22991BD5200B7EEE2 /* InteractiveCommands.h in Headers */, + 7592BD0D2CC6BCC300EB74A0 /* EmberAttributeDataBuffer.h in Headers */, 037C3DAF2991BD4F00B7EEE2 /* DeviceControllerDelegateBridge.h in Headers */, B4FCD5712B603A6300832859 /* DownloadLogCommand.h in Headers */, 037C3DC32991BD5100B7EEE2 /* Commands.h in Headers */, @@ -1704,6 +1753,9 @@ 037C3DB72991BD5000B7EEE2 /* ModelCommandBridge.h in Headers */, 037C3DC52991BD5100B7EEE2 /* StorageManagementCommand.h in Headers */, 037C3DCC2991BD5100B7EEE2 /* MTRError_Utils.h in Headers */, + 7592BD002CBEE98C00EB74A0 /* Instance.h in Headers */, + 7592BD012CBEE98C00EB74A0 /* EmberMetadata.h in Headers */, + 7592BD022CBEE98C00EB74A0 /* CodegenDataModelProvider.h in Headers */, 037C3DAD2991BD4F00B7EEE2 /* PairingCommandBridge.h in Headers */, 037C3DBB2991BD5000B7EEE2 /* Commands.h in Headers */, 512431262BA0C8BA000BC136 /* ResetMRPParametersCommand.h in Headers */, @@ -1819,6 +1871,7 @@ 51E51FC0282AD37A00FC978D /* MTRDeviceControllerStartupParams_Internal.h in Headers */, 3DECCB702934AECD00585AEC /* MTRLogging.h in Headers */, 1E4D654E29C208DD00BC3478 /* MTRCommissionableBrowserResult.h in Headers */, + 7592BD0C2CC6BCC300EB74A0 /* EmberAttributeDataBuffer.h in Headers */, 9B231B042C62EF650030EB37 /* (null) in Headers */, 515BE4ED2B72C0C5000BC1FD /* MTRUnfairLock.h in Headers */, 998F286F26D55EC5001846C6 /* MTRP256KeypairBridge.h in Headers */, @@ -1833,6 +1886,9 @@ 51D0B12E2B6177FD006E3511 /* MTRAccessGrant.h in Headers */, 5109E9B52CB8B5DF0006884B /* MTRDeviceType.h in Headers */, 1E4D655029C208DD00BC3478 /* MTRCommissionableBrowserDelegate.h in Headers */, + 7592BCF32CBEE98C00EB74A0 /* Instance.h in Headers */, + 7592BCF42CBEE98C00EB74A0 /* EmberMetadata.h in Headers */, + 7592BCF52CBEE98C00EB74A0 /* CodegenDataModelProvider.h in Headers */, 7596A84828762783004DAE0E /* MTRAsyncCallbackWorkQueue.h in Headers */, 5A7947E527C0129F00434CF2 /* MTRDeviceController+XPC.h in Headers */, 51E95DFB2A78443C00A434F0 /* MTRSessionResumptionStorageBridge.h in Headers */, @@ -1992,11 +2048,17 @@ 0395470F2992DB37006D42A8 /* complete.c in Sources */, 03F430A82994112B00166449 /* editline.c in Sources */, 03F430AA2994113500166449 /* sysunix.c in Sources */, + 7592BD0E2CC6BCC300EB74A0 /* EmberAttributeDataBuffer.cpp in Sources */, B45373BF2A9FEA9100807602 /* adopt.c in Sources */, B4F773CB2CB54B61008C6B23 /* LeakChecker.mm in Sources */, B45373D12A9FEB0C00807602 /* alloc.c in Sources */, B45373DD2A9FEB5300807602 /* base64-decode.c in Sources */, B45373D22A9FEB0C00807602 /* buflist.c in Sources */, + 7592BCFB2CBEE98C00EB74A0 /* CodegenDataModelProvider_Read.cpp in Sources */, + 7592BCFC2CBEE98C00EB74A0 /* Instance.cpp in Sources */, + 7592BCFD2CBEE98C00EB74A0 /* EmberMetadata.cpp in Sources */, + 7592BCFE2CBEE98C00EB74A0 /* CodegenDataModelProvider.cpp in Sources */, + 7592BCFF2CBEE98C00EB74A0 /* CodegenDataModelProvider_Write.cpp in Sources */, B45373C12A9FEA9100807602 /* close.c in Sources */, B45373D42A9FEB0C00807602 /* context.c in Sources */, B45373E52A9FEBA400807602 /* date.c in Sources */, @@ -2096,6 +2158,11 @@ 515C1C6F284F9FFB00A48F0C /* MTRFramework.mm in Sources */, 51029DF6293AA6100087AFB0 /* MTROperationalCertificateIssuer.mm in Sources */, 27A53C1827FBC6920053F131 /* MTRAttestationTrustStoreBridge.mm in Sources */, + 7592BCF62CBEE98C00EB74A0 /* CodegenDataModelProvider_Read.cpp in Sources */, + 7592BCF72CBEE98C00EB74A0 /* Instance.cpp in Sources */, + 7592BCF82CBEE98C00EB74A0 /* EmberMetadata.cpp in Sources */, + 7592BCF92CBEE98C00EB74A0 /* CodegenDataModelProvider.cpp in Sources */, + 7592BCFA2CBEE98C00EB74A0 /* CodegenDataModelProvider_Write.cpp in Sources */, 93B2CF9A2B56E45C00E4D187 /* MTRClusterNames.mm in Sources */, 998F287126D56940001846C6 /* MTRP256KeypairBridge.mm in Sources */, 516416012B6B483C00D5CE11 /* MTRIMDispatch.mm in Sources */, @@ -2153,6 +2220,7 @@ 5109E9B42CB8B5DF0006884B /* MTRDeviceType.mm in Sources */, 3D843757294AD25A0070D20A /* MTRCertificateInfo.mm in Sources */, 5A7947E427C0129600434CF2 /* MTRDeviceController+XPC.mm in Sources */, + 7592BD0B2CC6BCC300EB74A0 /* EmberAttributeDataBuffer.cpp in Sources */, 5A6FEC9027B563D900F25F42 /* MTRDeviceControllerOverXPC.mm in Sources */, 516415FC2B6ACA8300D5CE11 /* MTRServerAccessControl.mm in Sources */, B289D4222639C0D300D4E314 /* MTROnboardingPayloadParser.mm in Sources */, From f212d601738728d58e88ada3bc7e65b84cdfe7f0 Mon Sep 17 00:00:00 2001 From: Sergio Soares Date: Thu, 31 Oct 2024 03:29:29 -0400 Subject: [PATCH 024/121] energy-management-app: Add instructions for Water Heater App using chip-tool and TestEventTriggers (#36307) * energy-management-app: Document instructions for Water Heater TestEventTriggers using chip-tool * Restyled by prettier-markdown * Update examples/energy-management-app/linux/README.md Co-authored-by: Andrei Litvin * Update examples/energy-management-app/linux/README.md Co-authored-by: Andrei Litvin * Restyled by prettier-markdown --------- Co-authored-by: Restyled.io Co-authored-by: Andrei Litvin --- .../energy-management-app/linux/README.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/examples/energy-management-app/linux/README.md b/examples/energy-management-app/linux/README.md index b52a3ab131c5be..3a81d934a09f05 100644 --- a/examples/energy-management-app/linux/README.md +++ b/examples/energy-management-app/linux/README.md @@ -552,3 +552,62 @@ When we re-read the events: state was `kPluggedInCharging` prior to the EV being not detected (normally in a graceful shutdown this would be `kPluggedInNoDemand` or `kPluggedInDemand`). + +## Water Heater App: Interaction using the chip-tool and TestEventTriggers + +This section demonstrates how to run the Water Heater application and interact +with it using the `chip-tool` and `TestEventTriggers`. By default (at the time +of writing), the WaterHeater app does not configure some of its attributes with +simulated values (most default to 0). The steps below set the +[default](https://github.com/project-chip/connectedhomeip/blob/master/src/app/clusters/water-heater-management-server/WaterHeaterManagementTestEventTriggerHandler.h#L47) +`TestEventTrigger` which +`Simulate installation in a 100L tank full of water at 20C, with a target temperature of 60C, in OFF mode`. + +Step-by-step: + +1. Build the `energy-management-app` for linux: + + ``` + ./scripts/build/build_examples.py --target linux-x64-energy-management-no-ble build + ``` + +1. Run the Water Heater application: + + ``` + rm /tmp/chip_* && ./out/linux-x64-energy-management-no-ble/chip-energy-management-app --application water-heater --trace-to json:log --enable-key 000102030405060708090a0b0c0d0e0f + ``` + +1. Commission with chip-tool as node `0x12344321`: + + ``` + ./out/linux-x64-chip-tool-no-ble/chip-tool pairing code 0x12344321 MT:-24J0AFN00KA0648G00 + ``` + +1. Read the `TankVolume` attribute (expect 0 by default): + + ``` + ./out/linux-x64-chip-tool-no-ble/chip-tool waterheatermanagement read tank-volume 0x12344321 2 | grep TOO + + [1730306361.511] [2089549:2089552] [TOO] TankVolume: 0 + ``` + +1. Set the default TestEventTrigger (`0x0094000000000000`): + +- `0x0094000000000000` corresponds to `kBasicInstallationTestEvent` from + `WaterHeadermanagementTestEventTriggerHandler.h` +- `hex:00010203...0e0f` is the `--enable-key` passed to the startup of + chip-energy-management-app +- `0x12344321` is the node-id that the app was commissioned on +- final `0` is the endpoint on which the `GeneralDiagnostics` cluster exists + to call the `TestEventTrigger` command + ``` + ./out/linux-x64-chip-tool-no-ble/chip-tool generaldiagnostics test-event-trigger hex:000102030405060708090a0b0c0d0e0f 0x0094000000000000 0x12344321 0 + ``` + +1. Read TankVolume attribute again (now expect 100): + + ``` + ./out/linux-x64-chip-tool-no-ble/chip-tool waterheatermanagement read tank-volume 0x12344321 2 | grep TOO + + [1730312762.703] [2153606:2153609] [TOO] TankVolume: 100 + ``` From d38d56bab37c51acd63850066a64f291a4fd3766 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Thu, 31 Oct 2024 14:06:16 +0100 Subject: [PATCH 025/121] [Matter.framework] Remove the MTRDeviceController_Concrete::invalidateCASESessionEstablishmentForNode API and move the code inside MTRDevice_Concrete instead (#36315) --- .../Framework/CHIP/MTRDeviceController_Concrete.h | 6 ------ .../Framework/CHIP/MTRDeviceController_Concrete.mm | 11 ----------- src/darwin/Framework/CHIP/MTRDevice_Concrete.mm | 8 +++++--- 3 files changed, 5 insertions(+), 20 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h index f9f1e9d19aa1fe..0cfb25f4944fc9 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h @@ -178,12 +178,6 @@ NS_ASSUME_NONNULL_BEGIN */ - (void)invalidateCASESessionForNode:(NSNumber *)nodeID; -/** - * Invalidate the CASE session establishment for the specified node ID. - * Must not be called on the Matter event queue. - */ -- (void)invalidateCASESessionEstablishmentForNode:(NSNumber *)nodeID; - /** * Download log of the desired type from the device. */ diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm index 74e3437caf807f..1a164e50b14b5c 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm @@ -1619,17 +1619,6 @@ - (void)invalidateCASESessionForNode:(NSNumber *)nodeID; [self syncRunOnWorkQueue:block error:nil]; } -- (void)invalidateCASESessionEstablishmentForNode:(NSNumber *)nodeID; -{ - auto block = ^{ - auto caseSessionMgr = self->_cppCommissioner->CASESessionMgr(); - VerifyOrDie(caseSessionMgr != nullptr); - caseSessionMgr->ReleaseSession(self->_cppCommissioner->GetPeerScopedId(nodeID.unsignedLongLongValue)); - }; - - [self syncRunOnWorkQueue:block error:nil]; -} - - (void)operationalInstanceAdded:(NSNumber *)nodeID { // Don't use deviceForNodeID here, because we don't want to create the diff --git a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm index 5668f61d0fd224..61e8ab68ea89f8 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm @@ -901,9 +901,11 @@ - (void)_triggerResubscribeWithReason:(NSString *)reason nodeLikelyReachable:(BO } else if (_internalDeviceState == MTRInternalDeviceStateSubscribing && nodeLikelyReachable) { // If we have reason to suspect that the node is now reachable and we haven’t established a // CASE session yet, let’s consider it to be stalled and invalidate the pairing session. - dispatch_async(self.queue, ^{ - [[self _concreteController] invalidateCASESessionEstablishmentForNode:self->_nodeID]; - }); + [[self _concreteController] asyncGetCommissionerOnMatterQueue:^(Controller::DeviceCommissioner * commissioner) { + auto caseSessionMgr = commissioner->CASESessionMgr(); + VerifyOrDie(caseSessionMgr != nullptr); + caseSessionMgr->ReleaseSession(commissioner->GetPeerScopedId(self->_nodeID.unsignedLongLongValue)); + } errorHandler:nil /* not much we can do */]; } } From 6aa13c00ee01a5171959f3c768f64bcf957be4e8 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 31 Oct 2024 10:26:24 -0400 Subject: [PATCH 026/121] Update zamxml conformance skip (#36306) --- .../data_model_xml/handlers/handlers.py | 5 +--- .../matter_idl/zapxml/handlers/handlers.py | 27 ++++++++++++++++++- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/scripts/py_matter_idl/matter_idl/data_model_xml/handlers/handlers.py b/scripts/py_matter_idl/matter_idl/data_model_xml/handlers/handlers.py index 2a909bbbfb4d23..858ec6a19f6d87 100644 --- a/scripts/py_matter_idl/matter_idl/data_model_xml/handlers/handlers.py +++ b/scripts/py_matter_idl/matter_idl/data_model_xml/handlers/handlers.py @@ -343,10 +343,7 @@ def GetNextProcessor(self, name: str, attrs: AttributesImpl): if "nullable" in attrs and attrs["nullable"] != "false": self._attribute.definition.qualities |= FieldQuality.NULLABLE return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) - elif name == "optionalConform": - self._attribute.definition.qualities |= FieldQuality.OPTIONAL - return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) - elif name == "otherwiseConform": + elif name in {"optionalConform", "otherwiseConform"}: self._attribute.definition.qualities |= FieldQuality.OPTIONAL return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) elif name == "mandatoryConform": diff --git a/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py b/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py index cc5ccd9483091d..a303f263f10bc1 100644 --- a/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py +++ b/scripts/py_matter_idl/matter_idl/zapxml/handlers/handlers.py @@ -25,6 +25,10 @@ LOGGER = logging.getLogger('matter-xml-parser') +def _IsConformanceTagName(name: str) -> bool: + return name in {'mandatoryConform', 'optionalConform', 'otherwiseConform', 'provisionalConform', 'deprecateConform'} + + class ClusterNameHandler(BaseHandler): """Handles /configurator/cluster/name elements.""" @@ -110,6 +114,9 @@ def GetNextProcessor(self, name: str, attrs): return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) elif name.lower() == 'description': return DescriptionHandler(self.context, self._event) + elif _IsConformanceTagName(name): + # we do not parse conformance at this point + return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) else: return BaseHandler(self.context) @@ -145,6 +152,9 @@ def GetNextProcessor(self, name: str, attrs): return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) elif name.lower() == 'description': return AttributeDescriptionHandler(self.context, self._attribute) + elif _IsConformanceTagName(name): + # we do not parse conformance at this point + return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) else: return BaseHandler(self.context) @@ -162,6 +172,18 @@ def EndProcessing(self): self._cluster.attributes.append(self._attribute) +class SkipProvisioalHandler(BaseHandler): + def __init__(self, context: Context, attrs): + super().__init__(context, handled=HandledDepth.SINGLE_TAG) + + def GetNextProcessor(self, name: str, attrs): + if _IsConformanceTagName(name): + # we do not parse conformance at this point + return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) + else: + return BaseHandler(self.context) + + class StructHandler(BaseHandler, IdlPostProcessor): """ Handling /configurator/struct elements.""" @@ -213,7 +235,7 @@ def GetNextProcessor(self, name: str, attrs): field.qualities |= FieldQuality.FABRIC_SENSITIVE self._struct.fields.append(field) - return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) + return SkipProvisioalHandler(self.context, attrs) elif name.lower() == 'cluster': self._cluster_codes.add(ParseInt(attrs['code'])) return BaseHandler(self.context, handled=HandledDepth.SINGLE_TAG) @@ -460,6 +482,9 @@ def GetNextProcessor(self, name: str, attrs): if self._command: return DescriptionHandler(self.context, self._command) return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) + elif _IsConformanceTagName(name): + # we do not parse conformance at this point + return BaseHandler(self.context, handled=HandledDepth.ENTIRE_TREE) else: return BaseHandler(self.context) From f11cca380efe3b4be864dd212ba1026fa080e6ec Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 31 Oct 2024 11:40:27 -0400 Subject: [PATCH 027/121] Remove some stale defines from config files. (#36316) * Remove some stale defines from config files. These macros don't configure anything anymore. * Apply suggestion from code review. * Remove more whitespace. --- config/android/CHIPProjectConfig.h | 9 +-------- config/python/CHIPProjectConfig.h | 2 -- config/standalone/CHIPProjectConfig.h | 2 -- examples/chip-tool/include/CHIPProjectAppConfig.h | 2 -- examples/fabric-admin/include/CHIPProjectAppConfig.h | 2 -- .../include/CHIPProjectAppConfig.h | 2 -- .../include/CHIPProjectAppConfig.h | 2 -- examples/lit-icd-app/linux/config/CHIPProjectConfig.h | 2 -- 8 files changed, 1 insertion(+), 22 deletions(-) diff --git a/config/android/CHIPProjectConfig.h b/config/android/CHIPProjectConfig.h index 5b55f3ba7447cb..fd8c7abaa8fa95 100644 --- a/config/android/CHIPProjectConfig.h +++ b/config/android/CHIPProjectConfig.h @@ -26,18 +26,11 @@ #ifndef CHIPPROJECTCONFIG_H #define CHIPPROJECTCONFIG_H -// Enable UDP listening on demand in the CHIPDeviceController -#define CHIP_CONFIG_DEVICE_CONTROLLER_DEMAND_ENABLE_UDP 1 - #define INET_CONFIG_OVERRIDE_SYSTEM_TCP_USER_TIMEOUT 0 // Uncomment this for a large Tunnel MTU. -//#define CHIP_CONFIG_TUNNEL_INTERFACE_MTU (9000) +// #define CHIP_CONFIG_TUNNEL_INTERFACE_MTU (9000) #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 300 -#define CHIP_CONFIG_DATA_MANAGEMENT_CLIENT_EXPERIMENTAL 1 - -#define CHIP_CONFIG_MAX_SOFTWARE_VERSION_LENGTH 128 - #endif /* CHIPPROJECTCONFIG_H */ diff --git a/config/python/CHIPProjectConfig.h b/config/python/CHIPProjectConfig.h index 4412c5bec75a01..d8960f647de6ca 100644 --- a/config/python/CHIPProjectConfig.h +++ b/config/python/CHIPProjectConfig.h @@ -59,8 +59,6 @@ #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 0 -#define CHIP_CONFIG_DATA_MANAGEMENT_CLIENT_EXPERIMENTAL 1 - /* TODO: Ideally, these #defines should be enabled by default for Linux AND the python tool would provide runtime options to enable/disable them */ #define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY 1 diff --git a/config/standalone/CHIPProjectConfig.h b/config/standalone/CHIPProjectConfig.h index 27abcbb247b322..3e91ea40c1113f 100644 --- a/config/standalone/CHIPProjectConfig.h +++ b/config/standalone/CHIPProjectConfig.h @@ -60,8 +60,6 @@ #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 0 -#define CHIP_CONFIG_DATA_MANAGEMENT_CLIENT_EXPERIMENTAL 1 - #ifndef CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT #define CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT 4 #endif diff --git a/examples/chip-tool/include/CHIPProjectAppConfig.h b/examples/chip-tool/include/CHIPProjectAppConfig.h index 8c964bf5024bcb..d8ad2dfd435f08 100644 --- a/examples/chip-tool/include/CHIPProjectAppConfig.h +++ b/examples/chip-tool/include/CHIPProjectAppConfig.h @@ -54,8 +54,6 @@ #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 0 -#define CHIP_CONFIG_DATA_MANAGEMENT_CLIENT_EXPERIMENTAL 1 - #define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY 1 // Enable some test-only interaction model APIs. diff --git a/examples/fabric-admin/include/CHIPProjectAppConfig.h b/examples/fabric-admin/include/CHIPProjectAppConfig.h index b3f85d69359e87..441ecd788f08b6 100644 --- a/examples/fabric-admin/include/CHIPProjectAppConfig.h +++ b/examples/fabric-admin/include/CHIPProjectAppConfig.h @@ -54,8 +54,6 @@ #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 0 -#define CHIP_CONFIG_DATA_MANAGEMENT_CLIENT_EXPERIMENTAL 1 - #define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY 1 // Enable some test-only interaction model APIs. diff --git a/examples/java-matter-controller/include/CHIPProjectAppConfig.h b/examples/java-matter-controller/include/CHIPProjectAppConfig.h index 09183cc4485256..951b79db360a8f 100644 --- a/examples/java-matter-controller/include/CHIPProjectAppConfig.h +++ b/examples/java-matter-controller/include/CHIPProjectAppConfig.h @@ -46,8 +46,6 @@ #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 0 -#define CHIP_CONFIG_DATA_MANAGEMENT_CLIENT_EXPERIMENTAL 1 - #define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY 1 // Enable some test-only interaction model APIs. diff --git a/examples/kotlin-matter-controller/include/CHIPProjectAppConfig.h b/examples/kotlin-matter-controller/include/CHIPProjectAppConfig.h index 09183cc4485256..951b79db360a8f 100644 --- a/examples/kotlin-matter-controller/include/CHIPProjectAppConfig.h +++ b/examples/kotlin-matter-controller/include/CHIPProjectAppConfig.h @@ -46,8 +46,6 @@ #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 0 -#define CHIP_CONFIG_DATA_MANAGEMENT_CLIENT_EXPERIMENTAL 1 - #define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY 1 // Enable some test-only interaction model APIs. diff --git a/examples/lit-icd-app/linux/config/CHIPProjectConfig.h b/examples/lit-icd-app/linux/config/CHIPProjectConfig.h index fd663ffcbc893d..2de4d03ad755db 100644 --- a/examples/lit-icd-app/linux/config/CHIPProjectConfig.h +++ b/examples/lit-icd-app/linux/config/CHIPProjectConfig.h @@ -63,8 +63,6 @@ #define CHIP_SYSTEM_CONFIG_PACKETBUFFER_POOL_SIZE 0 -#define CHIP_CONFIG_DATA_MANAGEMENT_CLIENT_EXPERIMENTAL 1 - #ifndef CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT #define CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT 4 #endif From 32a75b22c012eb88fb8627bac6ef33450c46d70c Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 31 Oct 2024 11:44:26 -0400 Subject: [PATCH 028/121] Make TLVReader/Writer consume slightly less flash (#36286) * Size reductions: 80 bytes for TLV reader * Tiny reduction in code size, slight improvement on readability * Another tiny code diff and readability improvement * Size decrease for TLVWriter as well * Readability update * Restyle * Restyled by clang-format * Pay a bit of price for initialization, but this makes clang-tidy happy (I hope) * Update to make flash smaller with an odd workaround * Add back size comment * Update src/lib/core/TLVReader.cpp Co-authored-by: Boris Zbarsky * Add skip over control byte comment * Added a new comment * Restyled by whitespace --------- Co-authored-by: Andrei Litvin Co-authored-by: Restyled.io Co-authored-by: Boris Zbarsky --- src/lib/core/TLVReader.cpp | 136 +++++++++++-------------------------- src/lib/core/TLVTypes.h | 18 +++-- src/lib/core/TLVWriter.cpp | 75 +++++++++----------- 3 files changed, 84 insertions(+), 145 deletions(-) diff --git a/src/lib/core/TLVReader.cpp b/src/lib/core/TLVReader.cpp index 8368b9fb0fac04..ca3da3b555ba12 100644 --- a/src/lib/core/TLVReader.cpp +++ b/src/lib/core/TLVReader.cpp @@ -647,31 +647,18 @@ CHIP_ERROR TLVReader::Next(TLVType expectedType, Tag expectedTag) CHIP_ERROR TLVReader::Skip() { - CHIP_ERROR err; - TLVElementType elemType = ElementType(); - - if (elemType == TLVElementType::EndOfContainer) - return CHIP_END_OF_TLV; + const TLVElementType elemType = ElementType(); + VerifyOrReturnError(elemType != TLVElementType::EndOfContainer, CHIP_END_OF_TLV); if (TLVTypeIsContainer(elemType)) { TLVType outerContainerType; - err = EnterContainer(outerContainerType); - if (err != CHIP_NO_ERROR) - return err; - err = ExitContainer(outerContainerType); - if (err != CHIP_NO_ERROR) - return err; + ReturnErrorOnFailure(EnterContainer(outerContainerType)); + return ExitContainer(outerContainerType); } - else - { - err = SkipData(); - if (err != CHIP_NO_ERROR) - return err; - - ClearElementState(); - } + ReturnErrorOnFailure(SkipData()); + ClearElementState(); return CHIP_NO_ERROR; } @@ -705,8 +692,6 @@ CHIP_ERROR TLVReader::SkipData() if (TLVTypeHasLength(elemType)) { err = ReadData(nullptr, static_cast(mElemLenOrVal)); - if (err != CHIP_NO_ERROR) - return err; } return err; @@ -755,27 +740,16 @@ CHIP_ERROR TLVReader::SkipToEndOfContainer() CHIP_ERROR TLVReader::ReadElement() { - CHIP_ERROR err; - uint8_t stagingBuf[17]; // 17 = 1 control byte + 8 tag bytes + 8 length/value bytes - const uint8_t * p; - TLVElementType elemType; - // Make sure we have input data. Return CHIP_END_OF_TLV if no more data is available. - err = EnsureData(CHIP_END_OF_TLV); - if (err != CHIP_NO_ERROR) - return err; + ReturnErrorOnFailure(EnsureData(CHIP_END_OF_TLV)); + VerifyOrReturnError(mReadPoint != nullptr, CHIP_ERROR_INVALID_TLV_ELEMENT); - if (mReadPoint == nullptr) - { - return CHIP_ERROR_INVALID_TLV_ELEMENT; - } // Get the element's control byte. mControlByte = *mReadPoint; // Extract the element type from the control byte. Fail if it's invalid. - elemType = ElementType(); - if (!IsValidTLVType(elemType)) - return CHIP_ERROR_INVALID_TLV_ELEMENT; + TLVElementType elemType = ElementType(); + VerifyOrReturnError(IsValidTLVType(elemType), CHIP_ERROR_INVALID_TLV_ELEMENT); // Extract the tag control from the control byte. TLVTagControl tagControl = static_cast(mControlByte & kTLVTagControlMask); @@ -787,54 +761,40 @@ CHIP_ERROR TLVReader::ReadElement() TLVFieldSize lenOrValFieldSize = GetTLVFieldSize(elemType); // Determine the number of bytes in the length/value field. - uint8_t valOrLenBytes = TLVFieldSizeToBytes(lenOrValFieldSize); + const uint8_t valOrLenBytes = TLVFieldSizeToBytes(lenOrValFieldSize); // Determine the number of bytes in the element's 'head'. This includes: the control byte, the tag bytes (if present), the // length bytes (if present), and for elements that don't have a length (e.g. integers), the value bytes. - uint8_t elemHeadBytes = static_cast(1 + tagBytes + valOrLenBytes); + const uint8_t elemHeadBytes = static_cast(1 + tagBytes + valOrLenBytes); - // If the head of the element overlaps the end of the input buffer, read the bytes into the staging buffer - // and arrange to parse them from there. Otherwise read them directly from the input buffer. - if (elemHeadBytes > (mBufEnd - mReadPoint)) - { - err = ReadData(stagingBuf, elemHeadBytes); - if (err != CHIP_NO_ERROR) - return err; - p = stagingBuf; - } - else - { - p = mReadPoint; - mReadPoint += elemHeadBytes; - mLenRead += elemHeadBytes; - } + // 17 = 1 control byte + 8 tag bytes + 8 length/value bytes + uint8_t stagingBuf[17]; + + // Odd workaround: clang-tidy claims garbage value otherwise as it does not + // understand that ReadData initializes stagingBuf + stagingBuf[1] = 0; + + // If the head of the element goes past the end of the current input buffer, + // we need to read it into the staging buffer to parse it. Just do that unconditionally, + // even if the head does not go past end of current buffer, to save codesize. + ReturnErrorOnFailure(ReadData(stagingBuf, elemHeadBytes)); - // Skip over the control byte. - p++; + // +1 to skip over the control byte + const uint8_t * p = stagingBuf + 1; // Read the tag field, if present. - mElemTag = ReadTag(tagControl, p); + mElemTag = ReadTag(tagControl, p); + mElemLenOrVal = 0; // Read the length/value field, if present. - switch (lenOrValFieldSize) - { - case kTLVFieldSize_0Byte: - mElemLenOrVal = 0; - break; - case kTLVFieldSize_1Byte: - mElemLenOrVal = Read8(p); - break; - case kTLVFieldSize_2Byte: - mElemLenOrVal = LittleEndian::Read16(p); - break; - case kTLVFieldSize_4Byte: - mElemLenOrVal = LittleEndian::Read32(p); - break; - case kTLVFieldSize_8Byte: - mElemLenOrVal = LittleEndian::Read64(p); - VerifyOrReturnError(!TLVTypeHasLength(elemType) || (mElemLenOrVal <= UINT32_MAX), CHIP_ERROR_NOT_IMPLEMENTED); - break; - } + // NOTE: this is works because even though we only memcpy a subset of values and leave + // the rest 0. Value looks like " ... 0 0 ... 0" + // which is the TLV format. HostSwap ensures this becomes a real host value + // (should be a NOOP on LE machines, will full-swap on big-endian machines) + memcpy(&mElemLenOrVal, p, valOrLenBytes); + LittleEndian::HostSwap(mElemLenOrVal); + + VerifyOrReturnError(!TLVTypeHasLength(elemType) || (mElemLenOrVal <= UINT32_MAX), CHIP_ERROR_NOT_IMPLEMENTED); return VerifyElement(); } @@ -929,13 +889,9 @@ Tag TLVReader::ReadTag(TLVTagControl tagControl, const uint8_t *& p) const CHIP_ERROR TLVReader::ReadData(uint8_t * buf, uint32_t len) { - CHIP_ERROR err; - while (len > 0) { - err = EnsureData(CHIP_ERROR_TLV_UNDERRUN); - if (err != CHIP_NO_ERROR) - return err; + ReturnErrorOnFailure(EnsureData(CHIP_ERROR_TLV_UNDERRUN)); uint32_t remainingLen = static_cast(mBufEnd - mReadPoint); @@ -958,29 +914,17 @@ CHIP_ERROR TLVReader::ReadData(uint8_t * buf, uint32_t len) CHIP_ERROR TLVReader::EnsureData(CHIP_ERROR noDataErr) { - CHIP_ERROR err; - if (mReadPoint == mBufEnd) { - if (mLenRead == mMaxLen) - return noDataErr; - - if (mBackingStore == nullptr) - return noDataErr; + VerifyOrReturnError((mLenRead != mMaxLen) && (mBackingStore != nullptr), noDataErr); uint32_t bufLen; - err = mBackingStore->GetNextBuffer(*this, mReadPoint, bufLen); - if (err != CHIP_NO_ERROR) - return err; - if (bufLen == 0) - return noDataErr; + ReturnErrorOnFailure(mBackingStore->GetNextBuffer(*this, mReadPoint, bufLen)); + VerifyOrReturnError(bufLen > 0, noDataErr); // Cap mBufEnd so that we don't read beyond the user's specified maximum length, even // if the underlying buffer is larger. - uint32_t overallLenRemaining = mMaxLen - mLenRead; - if (overallLenRemaining < bufLen) - bufLen = overallLenRemaining; - + bufLen = std::min(bufLen, mMaxLen - mLenRead); mBufEnd = mReadPoint + bufLen; } diff --git a/src/lib/core/TLVTypes.h b/src/lib/core/TLVTypes.h index e6fb238660ac31..06f58d3d8b5c11 100644 --- a/src/lib/core/TLVTypes.h +++ b/src/lib/core/TLVTypes.h @@ -120,7 +120,7 @@ enum * * @return @p true if the specified TLV type is valid; otherwise @p false. */ -inline bool IsValidTLVType(TLVElementType type) +constexpr bool IsValidTLVType(TLVElementType type) { return type <= TLVElementType::EndOfContainer; } @@ -130,7 +130,7 @@ inline bool IsValidTLVType(TLVElementType type) * * @return @p true if the specified TLV type implies the presence of an associated value field; otherwise @p false. */ -inline bool TLVTypeHasValue(TLVElementType type) +constexpr bool TLVTypeHasValue(TLVElementType type) { return (type <= TLVElementType::UInt64 || (type >= TLVElementType::FloatingPointNumber32 && type <= TLVElementType::ByteString_8ByteLength)); @@ -141,7 +141,7 @@ inline bool TLVTypeHasValue(TLVElementType type) * * @return @p true if the specified TLV type implies the presence of an associated length field; otherwise @p false. */ -inline bool TLVTypeHasLength(TLVElementType type) +constexpr bool TLVTypeHasLength(TLVElementType type) { return type >= TLVElementType::UTF8String_1ByteLength && type <= TLVElementType::ByteString_8ByteLength; } @@ -186,13 +186,13 @@ inline bool TLVTypeIsUTF8String(TLVElementType type) * * @return @p true if the specified TLV type is a byte string; otherwise @p false. */ -inline bool TLVTypeIsByteString(TLVElementType type) +constexpr bool TLVTypeIsByteString(TLVElementType type) { return type >= TLVElementType::ByteString_1ByteLength && type <= TLVElementType::ByteString_8ByteLength; } // TODO: move to private namespace -inline TLVFieldSize GetTLVFieldSize(TLVElementType type) +constexpr TLVFieldSize GetTLVFieldSize(TLVElementType type) { if (TLVTypeHasValue(type)) return static_cast(static_cast(type) & kTLVTypeSizeMask); @@ -200,12 +200,18 @@ inline TLVFieldSize GetTLVFieldSize(TLVElementType type) } // TODO: move to private namespace -inline uint8_t TLVFieldSizeToBytes(TLVFieldSize fieldSize) +constexpr uint8_t TLVFieldSizeToBytes(TLVFieldSize fieldSize) { // We would like to assert fieldSize < 7, but that gives us fatal // -Wtautological-constant-out-of-range-compare warnings... return static_cast((fieldSize != kTLVFieldSize_0Byte) ? (1 << fieldSize) : 0); } +static_assert(TLVFieldSizeToBytes(kTLVFieldSize_0Byte) == 0); +static_assert(TLVFieldSizeToBytes(kTLVFieldSize_1Byte) == 1); +static_assert(TLVFieldSizeToBytes(kTLVFieldSize_2Byte) == 2); +static_assert(TLVFieldSizeToBytes(kTLVFieldSize_4Byte) == 4); +static_assert(TLVFieldSizeToBytes(kTLVFieldSize_8Byte) == 8); + } // namespace TLV } // namespace chip diff --git a/src/lib/core/TLVWriter.cpp b/src/lib/core/TLVWriter.cpp index db019fb5488622..aee91011bc1373 100644 --- a/src/lib/core/TLVWriter.cpp +++ b/src/lib/core/TLVWriter.cpp @@ -659,13 +659,13 @@ CHIP_ERROR TLVWriter::WriteElementHead(TLVElementType elemType, Tag tag, uint64_ ABORT_ON_UNINITIALIZED_IF_ENABLED(); VerifyOrReturnError(IsInitialized(), CHIP_ERROR_INCORRECT_STATE); - if (IsContainerOpen()) - return CHIP_ERROR_TLV_CONTAINER_OPEN; + VerifyOrReturnError(!IsContainerOpen(), CHIP_ERROR_TLV_CONTAINER_OPEN); uint8_t stagingBuf[17]; // 17 = 1 control byte + 8 tag bytes + 8 length/value bytes - uint8_t * p = stagingBuf; uint32_t tagNum = TagNumFromTag(tag); + Encoding::LittleEndian::BufferWriter writer(stagingBuf, sizeof(stagingBuf)); + if (IsSpecialTag(tag)) { if (tagNum <= Tag::kContextTagMaxNum) @@ -673,8 +673,8 @@ CHIP_ERROR TLVWriter::WriteElementHead(TLVElementType elemType, Tag tag, uint64_ if (mContainerType != kTLVType_Structure && mContainerType != kTLVType_List) return CHIP_ERROR_INVALID_TLV_TAG; - Write8(p, TLVTagControl::ContextSpecific | elemType); - Write8(p, static_cast(tagNum)); + writer.Put8(TLVTagControl::ContextSpecific | elemType); + writer.Put8(static_cast(tagNum)); } else { @@ -682,7 +682,7 @@ CHIP_ERROR TLVWriter::WriteElementHead(TLVElementType elemType, Tag tag, uint64_ mContainerType != kTLVType_Array && mContainerType != kTLVType_List) return CHIP_ERROR_INVALID_TLV_TAG; - Write8(p, TLVTagControl::Anonymous | elemType); + writer.Put8(TLVTagControl::Anonymous | elemType); } } else @@ -694,28 +694,28 @@ CHIP_ERROR TLVWriter::WriteElementHead(TLVElementType elemType, Tag tag, uint64_ if (profileId == kCommonProfileId) { - if (tagNum < 65536) + if (tagNum <= std::numeric_limits::max()) { - Write8(p, TLVTagControl::CommonProfile_2Bytes | elemType); - LittleEndian::Write16(p, static_cast(tagNum)); + writer.Put8(TLVTagControl::CommonProfile_2Bytes | elemType); + writer.Put16(static_cast(tagNum)); } else { - Write8(p, TLVTagControl::CommonProfile_4Bytes | elemType); - LittleEndian::Write32(p, tagNum); + writer.Put8(TLVTagControl::CommonProfile_4Bytes | elemType); + writer.Put32(tagNum); } } else if (profileId == ImplicitProfileId) { - if (tagNum < 65536) + if (tagNum <= std::numeric_limits::max()) { - Write8(p, TLVTagControl::ImplicitProfile_2Bytes | elemType); - LittleEndian::Write16(p, static_cast(tagNum)); + writer.Put8(TLVTagControl::ImplicitProfile_2Bytes | elemType); + writer.Put16(static_cast(tagNum)); } else { - Write8(p, TLVTagControl::ImplicitProfile_4Bytes | elemType); - LittleEndian::Write32(p, tagNum); + writer.Put8(TLVTagControl::ImplicitProfile_4Bytes | elemType); + writer.Put32(tagNum); } } else @@ -723,44 +723,33 @@ CHIP_ERROR TLVWriter::WriteElementHead(TLVElementType elemType, Tag tag, uint64_ uint16_t vendorId = static_cast(profileId >> 16); uint16_t profileNum = static_cast(profileId); - if (tagNum < 65536) + if (tagNum <= std::numeric_limits::max()) { - Write8(p, TLVTagControl::FullyQualified_6Bytes | elemType); - LittleEndian::Write16(p, vendorId); - LittleEndian::Write16(p, profileNum); - LittleEndian::Write16(p, static_cast(tagNum)); + + writer.Put8(TLVTagControl::FullyQualified_6Bytes | elemType); + writer.Put16(vendorId); + writer.Put16(profileNum); + writer.Put16(static_cast(tagNum)); } else { - Write8(p, TLVTagControl::FullyQualified_8Bytes | elemType); - LittleEndian::Write16(p, vendorId); - LittleEndian::Write16(p, profileNum); - LittleEndian::Write32(p, tagNum); + writer.Put8(TLVTagControl::FullyQualified_8Bytes | elemType); + writer.Put16(vendorId); + writer.Put16(profileNum); + writer.Put32(tagNum); } } } - switch (GetTLVFieldSize(elemType)) + uint8_t lengthSize = TLVFieldSizeToBytes(GetTLVFieldSize(elemType)); + if (lengthSize > 0) { - case kTLVFieldSize_0Byte: - break; - case kTLVFieldSize_1Byte: - Write8(p, static_cast(lenOrVal)); - break; - case kTLVFieldSize_2Byte: - LittleEndian::Write16(p, static_cast(lenOrVal)); - break; - case kTLVFieldSize_4Byte: - LittleEndian::Write32(p, static_cast(lenOrVal)); - break; - case kTLVFieldSize_8Byte: - LittleEndian::Write64(p, lenOrVal); - break; + writer.EndianPut(lenOrVal, lengthSize); } - uint32_t bytesStaged = static_cast(p - stagingBuf); - VerifyOrDie(bytesStaged <= sizeof(stagingBuf)); - return WriteData(stagingBuf, bytesStaged); + size_t written = 0; + VerifyOrDie(writer.Fit(written)); + return WriteData(stagingBuf, static_cast(written)); } CHIP_ERROR TLVWriter::WriteElementWithData(TLVType type, Tag tag, const uint8_t * data, uint32_t dataLen) From 2c91e39911b599d7d274bd96d411d80a54e6d8a7 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 31 Oct 2024 12:04:49 -0400 Subject: [PATCH 029/121] Remove session accessors on non-concrete MTRDeviceController. (#36317) CASE/PASE sessions only make sense for concrete controllers. --- src/darwin/Framework/CHIP/MTRBaseDevice.mm | 5 --- .../Framework/CHIP/MTRBaseDevice_Internal.h | 6 +++ .../Framework/CHIP/MTRCallbackBridgeBase.h | 45 +++++++++---------- .../Framework/CHIP/MTRDeviceController.mm | 12 ----- .../CHIP/MTRDeviceController_Concrete.h | 34 ++++++++++++++ .../CHIP/MTRDeviceController_Internal.h | 34 -------------- .../CHIPTests/MTRPerControllerStorageTests.m | 4 +- 7 files changed, 64 insertions(+), 76 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRBaseDevice.mm b/src/darwin/Framework/CHIP/MTRBaseDevice.mm index 3868060175bb1b..0f86a76b8afa2d 100644 --- a/src/darwin/Framework/CHIP/MTRBaseDevice.mm +++ b/src/darwin/Framework/CHIP/MTRBaseDevice.mm @@ -233,11 +233,6 @@ - (void)onDone @end -@interface MTRBaseDevice () -// Will return nil if our controller is not in fact a concrete controller. -@property (nullable, nonatomic, strong, readonly) MTRDeviceController_Concrete * concreteController; -@end - @implementation MTRBaseDevice - (instancetype)initWithPASEDevice:(chip::DeviceProxy *)device controller:(MTRDeviceController *)controller diff --git a/src/darwin/Framework/CHIP/MTRBaseDevice_Internal.h b/src/darwin/Framework/CHIP/MTRBaseDevice_Internal.h index fa766463e3e025..4cf02ebd8ebf1c 100644 --- a/src/darwin/Framework/CHIP/MTRBaseDevice_Internal.h +++ b/src/darwin/Framework/CHIP/MTRBaseDevice_Internal.h @@ -19,6 +19,7 @@ #import #import "MTRDefines_Internal.h" +#import "MTRDeviceController_Concrete.h" #include #include @@ -210,6 +211,11 @@ static inline MTRTransportType MTRMakeTransportType(chip::Transport::Type type) queue:(dispatch_queue_t)queue completion:(MTRDeviceResponseHandler)completion; +/** + * Will return nil if our controller is not in fact a concrete controller. + */ +@property (nullable, nonatomic, strong, readonly) MTRDeviceController_Concrete * concreteController; + @end @interface MTRClusterPath () diff --git a/src/darwin/Framework/CHIP/MTRCallbackBridgeBase.h b/src/darwin/Framework/CHIP/MTRCallbackBridgeBase.h index d9c98157c2fe1d..e8b0d1efc638c4 100644 --- a/src/darwin/Framework/CHIP/MTRCallbackBridgeBase.h +++ b/src/darwin/Framework/CHIP/MTRCallbackBridgeBase.h @@ -18,8 +18,10 @@ #import #import "MTRBaseDevice_Internal.h" +#import "MTRDeviceController_Concrete.h" #import "MTRDeviceController_Internal.h" #import "MTRError_Internal.h" +#import "MTRLogging_Internal.h" #import "zap-generated/MTRBaseClusters.h" #include @@ -36,17 +38,6 @@ NS_ASSUME_NONNULL_BEGIN */ class MTRCallbackBridgeBase { public: - /** - * Run the given MTRActionBlock on the Matter thread, after getting a CASE - * session (possibly pre-existing) to the given node ID on the fabric - * represented by the given MTRDeviceController. On success, convert the - * success value to whatever type it needs to be to call the callback type - * we're templated over. Once this function has been called, on a callback - * bridge allocated with `new`, the bridge object must not be accessed by - * the caller. The action block will handle deleting the bridge. - */ - void DispatchAction(chip::NodeId nodeID, MTRDeviceController * controller) && { ActionWithNodeID(nodeID, controller); } - /** * Run the given MTRActionBlock on the Matter thread after getting a secure * session corresponding to the given MTRBaseDevice. On success, convert @@ -60,7 +51,7 @@ class MTRCallbackBridgeBase { if (device.isPASEDevice) { ActionWithPASEDevice(device); } else { - ActionWithNodeID(device.nodeID, device.deviceController); + ActionWithNodeID(device.nodeID, device.concreteController); } } @@ -81,22 +72,30 @@ class MTRCallbackBridgeBase { { LogRequestStart(); - // TODO: Figure out whether we can usefully get an MTRDeviceController_Concrete in here, so - // we can move getSessionForCommissioneeDevice off of MTRDeviceController_Internal. Ideally - // without bloating this inline method too much. - [device.deviceController getSessionForCommissioneeDevice:device.nodeID - completion:^(chip::Messaging::ExchangeManager * exchangeManager, - const chip::Optional & session, NSError * _Nullable error, NSNumber * _Nullable retryDelay) { - MaybeDoAction(exchangeManager, session, error); - }]; + MTRDeviceController_Concrete * _Nullable controller = device.concreteController; + if (!controller) { + MTR_LOG_ERROR("Trying to perform action with PASE device with a non-concrete controller"); + MaybeDoAction(nullptr, chip::NullOptional, [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]); + return; + } + + [controller getSessionForCommissioneeDevice:device.nodeID + completion:^(chip::Messaging::ExchangeManager * exchangeManager, + const chip::Optional & session, NSError * _Nullable error, NSNumber * _Nullable retryDelay) { + MaybeDoAction(exchangeManager, session, error); + }]; } - void ActionWithNodeID(chip::NodeId nodeID, MTRDeviceController * controller) + void ActionWithNodeID(chip::NodeId nodeID, MTRDeviceController_Concrete * _Nullable controller) { LogRequestStart(); - // TODO: Figure out whether we can usefully get an MTRDeviceController_Concrete in here, so - // we can move getSessionForNode off of MTRDeviceController_Internal. + if (!controller) { + MTR_LOG_ERROR("Trying to perform action on node ID 0x%016llX (%llu) with a non-concrete controller", nodeID, nodeID); + MaybeDoAction(nullptr, chip::NullOptional, [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]); + return; + } + [controller getSessionForNode:nodeID completion:^(chip::Messaging::ExchangeManager * _Nullable exchangeManager, const chip::Optional & session, NSError * _Nullable error, NSNumber * _Nullable retryDelay) { diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index 8b8295d94450c2..5850d88601a4f3 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -535,18 +535,6 @@ - (BOOL)checkIsRunning:(NSError * __autoreleasing *)error return NO; } -- (void)getSessionForNode:(chip::NodeId)nodeID completion:(MTRInternalDeviceConnectionCallback)completion -{ - MTR_ABSTRACT_METHOD(); - completion(nullptr, chip::NullOptional, [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE], nil); -} - -- (void)getSessionForCommissioneeDevice:(chip::NodeId)deviceID completion:(MTRInternalDeviceConnectionCallback)completion -{ - MTR_ABSTRACT_METHOD(); - completion(nullptr, chip::NullOptional, [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE], nil); -} - - (void)asyncDispatchToMatterQueue:(dispatch_block_t)block errorHandler:(nullable MTRDeviceErrorHandler)errorHandler { // TODO: Figure out how to get callsites to have an MTRDeviceController_Concrete. diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h index 0cfb25f4944fc9..80f5b222bd5cd8 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h @@ -120,6 +120,23 @@ NS_ASSUME_NONNULL_BEGIN */ - (void)clearPendingShutdown; +/** + * Ensure we have a CASE session to the given node ID and then call the provided + * connection callback. This may be called on any queue (including the Matter + * event queue) and on success will always call the provided connection callback + * on the Matter queue, asynchronously. Consumers must be prepared to run on + * the Matter queue (an in particular must not use any APIs that will try to do + * sync dispatch to the Matter queue). + * + * If the controller is not running when this function is called, it will + * synchronously invoke the completion with an error, on whatever queue + * getSessionForNode was called on. + * + * If the controller is not running when the async dispatch on the Matter queue + * happens, the completion will be invoked with an error on the Matter queue. + */ +- (void)getSessionForNode:(chip::NodeId)nodeID completion:(MTRInternalDeviceConnectionCallback)completion; + /** * Since getSessionForNode now enqueues by the subscription pool for Thread * devices, MTRDevice_Concrete needs a direct non-queued access because it already @@ -127,6 +144,23 @@ NS_ASSUME_NONNULL_BEGIN */ - (void)directlyGetSessionForNode:(chip::NodeId)nodeID completion:(MTRInternalDeviceConnectionCallback)completion; +/** + * Get a session for the commissionee device with the given device id. This may + * be called on any queue (including the Matter event queue) and on success will + * always call the provided connection callback on the Matter queue, + * asynchronously. Consumers must be prepared to run on the Matter queue (an in + * particular must not use any APIs that will try to do sync dispatch to the + * Matter queue). + * + * If the controller is not running when this function is called, it will + * synchronously invoke the completion with an error, on whatever queue + * getSessionForCommissioneeDevice was called on. + * + * If the controller is not running when the async dispatch on the Matter queue + * happens, the completion will be invoked with an error on the Matter queue. + */ +- (void)getSessionForCommissioneeDevice:(chip::NodeId)deviceID completion:(MTRInternalDeviceConnectionCallback)completion; + /** * Notify the controller that a new operational instance with the given node id * and a compressed fabric id that matches this controller has been observed. diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h index c26518d532e2ea..145f32940941d8 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h @@ -121,40 +121,6 @@ NS_ASSUME_NONNULL_BEGIN */ @property (nonatomic, retain, nullable) NSData * rootPublicKey; -/** - * Ensure we have a CASE session to the given node ID and then call the provided - * connection callback. This may be called on any queue (including the Matter - * event queue) and on success will always call the provided connection callback - * on the Matter queue, asynchronously. Consumers must be prepared to run on - * the Matter queue (an in particular must not use any APIs that will try to do - * sync dispatch to the Matter queue). - * - * If the controller is not running when this function is called, it will - * synchronously invoke the completion with an error, on whatever queue - * getSessionForNode was called on. - * - * If the controller is not running when the async dispatch on the Matter queue - * happens, the completion will be invoked with an error on the Matter queue. - */ -- (void)getSessionForNode:(chip::NodeId)nodeID completion:(MTRInternalDeviceConnectionCallback)completion; - -/** - * Get a session for the commissionee device with the given device id. This may - * be called on any queue (including the Matter event queue) and on success will - * always call the provided connection callback on the Matter queue, - * asynchronously. Consumers must be prepared to run on the Matter queue (an in - * particular must not use any APIs that will try to do sync dispatch to the - * Matter queue). - * - * If the controller is not running when this function is called, it will - * synchronously invoke the completion with an error, on whatever queue - * getSessionForCommissioneeDevice was called on. - * - * If the controller is not running when the async dispatch on the Matter queue - * happens, the completion will be invoked with an error on the Matter queue. - */ -- (void)getSessionForCommissioneeDevice:(chip::NodeId)deviceID completion:(MTRInternalDeviceConnectionCallback)completion; - /** * Try to asynchronously dispatch the given block on the Matter queue. If the * controller is not running either at call time or when the block would be diff --git a/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m b/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m index 071566381cc69c..1ead4692a2b335 100644 --- a/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m +++ b/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m @@ -2706,8 +2706,8 @@ - (void)doTestSubscriptionPoolWithSize:(NSInteger)subscriptionPoolSize deviceOnb // Given the base device read is happening on the 5th device, at the completion // time of the first [pool size] subscriptions, the BaseDevice's request to - // read can't have completed, as it should be gated on its call to the - // MTRDeviceController's getSessionForNode: call. + // read can't have completed, as it should be gated on its call to + // MTRDeviceController_Concrete's getSessionForNode:. if (subscriptionDequeueCount <= (orderedDeviceIDs.count - subscriptionPoolSize)) { XCTAssertFalse(baseDeviceReadCompleted); } From b83a61cf6d85722f996c417b380782a4d87dd2ec Mon Sep 17 00:00:00 2001 From: Sergio Soares Date: Thu, 31 Oct 2024 12:08:03 -0400 Subject: [PATCH 030/121] Fix chip-repl commissioning cmd on readme (#36303) --- examples/energy-management-app/linux/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/energy-management-app/linux/README.md b/examples/energy-management-app/linux/README.md index 3a81d934a09f05..d28121f0a6d33b 100644 --- a/examples/energy-management-app/linux/README.md +++ b/examples/energy-management-app/linux/README.md @@ -272,7 +272,7 @@ data (e.g. fabric info). - Step 3: (In chip-repl) Commissioning OnNetwork ```python - devCtrl.CommissionOnNetwork(1234,20202021) # Commission with NodeID 1234 + await devCtrl.CommissionOnNetwork(1234,20202021) # Commission with NodeID 1234 Established secure session with Device Commissioning complete Out[2]: From f772506f750aab4b7930a5dbdc9524198e86327a Mon Sep 17 00:00:00 2001 From: Dmytro Huz <75682372+interfer@users.noreply.github.com> Date: Thu, 31 Oct 2024 18:31:37 +0200 Subject: [PATCH 031/121] [Telink] Add support for up to 8 groups for lighting-app. (#36290) Groups multicast functionality fixed. Tested on 1-8 groups. Signed-off-by: Dmytro Huz --- config/telink/chip-module/Kconfig.defaults | 11 ++++++++++- .../lighting-app/telink/include/CHIPProjectConfig.h | 6 ++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/config/telink/chip-module/Kconfig.defaults b/config/telink/chip-module/Kconfig.defaults index 835b14c1811be0..d28d77d6cffd32 100644 --- a/config/telink/chip-module/Kconfig.defaults +++ b/config/telink/chip-module/Kconfig.defaults @@ -83,7 +83,12 @@ config COMMON_LIBC_MALLOC_ARENA_SIZE default 12288 config NET_IPV6_MLD - default n + default n if PM + default y + +config NET_IF_MCAST_IPV6_ADDR_COUNT + default 8 if PM + default 15 # Network buffers config NET_PKT_RX_COUNT @@ -272,6 +277,10 @@ config OPENTHREAD_DEFAULT_TX_POWER default 3 if PM default 9 +config OPENTHREAD_IP6_MAX_EXT_MCAST_ADDRS + default 2 if PM + default 8 + endif # NET_L2_OPENTHREAD config NET_TX_STACK_SIZE diff --git a/examples/lighting-app/telink/include/CHIPProjectConfig.h b/examples/lighting-app/telink/include/CHIPProjectConfig.h index 830ad45de5816d..af5f8c6358d817 100644 --- a/examples/lighting-app/telink/include/CHIPProjectConfig.h +++ b/examples/lighting-app/telink/include/CHIPProjectConfig.h @@ -35,3 +35,9 @@ // Until this is improved in OpenThread we need to increase the retransmission // interval to survive the stall. #define CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL (1000_ms32) + +// ========== Multicast groups Configuration Overrides ========= +#undef CHIP_CONFIG_MAX_GROUP_ENDPOINTS_PER_FABRIC +#define CHIP_CONFIG_MAX_GROUP_ENDPOINTS_PER_FABRIC 2 + +#define CHIP_CONFIG_EXAMPLE_ACCESS_CONTROL_MAX_SUBJECTS_PER_ENTRY (4 * CHIP_CONFIG_MAX_GROUP_ENDPOINTS_PER_FABRIC) From 91f4e078b4e65ab5c7332c4089c2c85a6e4ac25b Mon Sep 17 00:00:00 2001 From: Mathieu Kardous <84793247+mkardous-silabs@users.noreply.github.com> Date: Thu, 31 Oct 2024 12:39:14 -0400 Subject: [PATCH 032/121] [Silabs] Rename Wifi interface sources files (#36318) * Rename Wifi interface sources files * restyle --- examples/platform/silabs/MatterConfig.cpp | 2 +- examples/platform/silabs/SiWx917/BUILD.gn | 51 ++- .../silabs/SiWx917/SiWxWifiInterface.cpp | 4 +- .../{rsi_if.cpp => Rsi91xWifiInterface.cpp} | 2 +- .../silabs/efr32/rs911x/hal/efx_spi.c | 2 +- .../efr32/rs911x/hal/rsi_hal_mcu_interrupt.c | 2 +- .../efr32/rs911x/hal/rsi_hal_mcu_ioports.c | 2 +- .../efr32/rs911x/hal/rsi_hal_mcu_timer.c | 2 +- .../efr32/rs911x/hal/sl_si91x_ncp_utility.c | 2 +- .../platform/silabs/efr32/rs911x/rs9117.gni | 18 +- .../platform/silabs/efr32/rs911x/rs911x.gni | 20 +- .../{host_if.cpp => Wf200WifiInterface.cpp} | 0 .../silabs/efr32/wf200/sl_wfx_crypto.c | 409 ------------------ .../efr32/wf200/sl_wfx_securelink_task.c | 85 ---- .../platform/silabs/efr32/wf200/wf200.gni | 24 +- ..._host.cpp => WifiInterfaceAbstraction.cpp} | 225 +++++++++- .../WifiInterfaceAbstraction.h} | 5 - examples/platform/silabs/wifi/wfx_notify.cpp | 228 ---------- src/platform/silabs/rs911x/wfx_sl_ble_init.h | 4 - 19 files changed, 315 insertions(+), 772 deletions(-) rename examples/platform/silabs/efr32/rs911x/{rsi_if.cpp => Rsi91xWifiInterface.cpp} (99%) rename examples/platform/silabs/efr32/wf200/{host_if.cpp => Wf200WifiInterface.cpp} (100%) delete mode 100644 examples/platform/silabs/efr32/wf200/sl_wfx_crypto.c delete mode 100644 examples/platform/silabs/efr32/wf200/sl_wfx_securelink_task.c rename examples/platform/silabs/wifi/{wfx_rsi_host.cpp => WifiInterfaceAbstraction.cpp} (64%) rename examples/platform/silabs/{wfx_rsi.h => wifi/WifiInterfaceAbstraction.h} (98%) delete mode 100644 examples/platform/silabs/wifi/wfx_notify.cpp diff --git a/examples/platform/silabs/MatterConfig.cpp b/examples/platform/silabs/MatterConfig.cpp index 44c60ca0f101e7..43bd2c181fd044 100644 --- a/examples/platform/silabs/MatterConfig.cpp +++ b/examples/platform/silabs/MatterConfig.cpp @@ -41,7 +41,7 @@ #endif #if defined(SLI_SI91X_MCU_INTERFACE) && SLI_SI91X_MCU_INTERFACE == 1 -#include "wfx_rsi.h" +#include "WifiInterfaceAbstraction.h" #endif // SLI_SI91X_MCU_INTERFACE #include diff --git a/examples/platform/silabs/SiWx917/BUILD.gn b/examples/platform/silabs/SiWx917/BUILD.gn index 2abc3bc9d27c9a..3409d8e815e6f0 100644 --- a/examples/platform/silabs/SiWx917/BUILD.gn +++ b/examples/platform/silabs/SiWx917/BUILD.gn @@ -15,6 +15,7 @@ import("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") +import("${chip_root}/examples/platform/silabs/args.gni") import("${chip_root}/src/lib/lib.gni") import("${chip_root}/src/platform/device.gni") import("${chip_root}/src/platform/silabs/wifi_args.gni") @@ -50,10 +51,7 @@ assert(chip_enable_wifi) silabs_plat_dir = "${chip_root}/src/platform/silabs" silabs_plat_si91x_wifi_dir = "${chip_root}/src/platform/silabs/SiWx917/wifi" -import("${silabs_common_plat_dir}/args.gni") config("chip_examples_project_config") { - include_dirs = [ "project_include" ] - # Link options that provide a replacement for dynamic memory operations in standard # library with the sl_memory_manager in platform code. ldflags = [ @@ -107,6 +105,40 @@ source_set("matter-shell") { ] } +config("wifi-interface-config") { + include_dirs = [ + "${silabs_plat_dir}/wifi", + "${silabs_common_plat_dir}/wifi", + ] +} + +source_set("wifi-interface") { + sources = [ + "${silabs_common_plat_dir}/wifi/WifiInterfaceAbstraction.cpp", + "SiWxWifiInterface.cpp", + + # Wi-Fi Config - Using the file sdk support until the wiseconnect file is fixed + "${sdk_support_root}/components/service/network_manager/src/sl_net_for_lwip.c", + ] + + public_deps = [ + "${chip_root}/src/app/icd/server:icd-server-config", + "${chip_root}/src/lib/core", + "${chip_root}/src/lib/support", + "${chip_root}/src/platform:platform", + "${chip_root}/src/platform/silabs/SiWx917:SiWx917", + "${lwip_root}:lwip", + ] + + public_configs = [ + ":siwx917-common-config", + "${silabs_sdk_build_root}:silabs_config", + ":chip_examples_project_config", + ":wifi-interface-config", + ":silabs-wifi-config", + ] +} + config("siwx917-common-config") { defines = [ "OTA_PERIODIC_TIMEOUT=${ota_periodic_query_timeout_sec}" ] @@ -167,7 +199,11 @@ config("silabs-wifi-config") { source_set("siwx917-common") { deps = [ "${silabs_common_plat_dir}/provision:storage" ] defines = [] - public_deps = [ "${lwip_root}:lwip" ] + public_deps = [ + ":wifi-interface", + "${lwip_root}:lwip", + ] + public_configs = [ ":siwx917-common-config", "${silabs_sdk_build_root}:silabs_config", @@ -176,6 +212,7 @@ source_set("siwx917-common") { include_dirs = [ "${silabs_plat_dir}/wifi", + "${silabs_common_plat_dir}/wifi", "${silabs_plat_si91x_wifi_dir}", "${silabs_common_plat_dir}", ] @@ -188,12 +225,6 @@ source_set("siwx917-common") { "${silabs_common_plat_dir}/SoftwareFaultReports.cpp", "${silabs_common_plat_dir}/silabs_utils.cpp", "${silabs_common_plat_dir}/syscalls_stubs.cpp", - "${silabs_common_plat_dir}/wifi/wfx_notify.cpp", - "${silabs_common_plat_dir}/wifi/wfx_rsi_host.cpp", - "SiWxWifiInterface.cpp", - - # Wi-Fi Config - Using the file sdk support until the wiseconnect file is fixed - "${sdk_support_root}/components/service/network_manager/src/sl_net_for_lwip.c", ] if (chip_enable_pw_rpc || chip_build_libshell || sl_uart_log_output) { diff --git a/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp b/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp index 1e573ed5941784..26a16f9aa87f8f 100644 --- a/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp +++ b/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp @@ -28,6 +28,7 @@ #endif // SL_MATTER_GN_BUILD #include "FreeRTOS.h" +#include "WifiInterfaceAbstraction.h" #include "ble_config.h" #include "dhcp_client.h" #include "event_groups.h" @@ -36,7 +37,6 @@ #include "sl_wifi_device.h" #include "task.h" #include "wfx_host_events.h" -#include "wfx_rsi.h" #include #include #include @@ -800,8 +800,8 @@ void ProcessEvent(WfxEvent_t inEvent) osSemaphoreRelease(sScanInProgressSemaphore); } - break; #endif /* SL_WFX_CONFIG_SCAN */ + break; case WFX_EVT_STA_START_JOIN: ChipLogDetail(DeviceLayer, "WFX_EVT_STA_START_JOIN"); diff --git a/examples/platform/silabs/efr32/rs911x/rsi_if.cpp b/examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp similarity index 99% rename from examples/platform/silabs/efr32/rs911x/rsi_if.cpp rename to examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp index 7c727e013e235c..233230b3698265 100644 --- a/examples/platform/silabs/efr32/rs911x/rsi_if.cpp +++ b/examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp @@ -49,11 +49,11 @@ extern "C" { } #endif +#include "WifiInterfaceAbstraction.h" #include "dhcp_client.h" #include "ethernetif.h" #include "lwip/nd6.h" #include "silabs_utils.h" -#include "wfx_rsi.h" #include #include diff --git a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c b/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c index 1f10640e04bad8..b1e4468cfb06e8 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c +++ b/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c @@ -41,10 +41,10 @@ #include "sl_status.h" #include "spidrv.h" +#include "WifiInterfaceAbstraction.h" #include "silabs_utils.h" #include "spi_multiplex.h" #include "wfx_host_events.h" -#include "wfx_rsi.h" #ifdef SL_BOARD_NAME #include "sl_board_control.h" diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c index 1cb5ddf9206d65..fb6a947f95a40c 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c +++ b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c @@ -35,8 +35,8 @@ #include "event_groups.h" #include "task.h" +#include "WifiInterfaceAbstraction.h" #include "wfx_host_events.h" -#include "wfx_rsi.h" #if (SLI_SI91X_MCU_INTERFACE | EXP_BOARD) #include "sl_board_configuration.h" diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c index 6ea20caf48a018..bb7dcf4a70498d 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c +++ b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c @@ -35,8 +35,8 @@ #include "event_groups.h" #include "task.h" +#include "WifiInterfaceAbstraction.h" #include "wfx_host_events.h" -#include "wfx_rsi.h" #include "rsi_board_configuration.h" #include "rsi_driver.h" diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c index 7a800728176081..b8ffea83f97b35 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c +++ b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c @@ -39,6 +39,7 @@ extern void xPortSysTickHandler(void); /* RSI Driver include file */ #include "rsi_driver.h" /* RSI WLAN Config include file */ +#include "WifiInterfaceAbstraction.h" #include "rsi_bootup_config.h" #include "rsi_common_apis.h" #include "rsi_data_types.h" @@ -49,7 +50,6 @@ extern void xPortSysTickHandler(void); #include "rsi_wlan.h" #include "rsi_wlan_apis.h" #include "rsi_wlan_config.h" -#include "wfx_rsi.h" #ifndef _use_the_rsi_defined_functions diff --git a/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c b/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c index b16bbdc47579e0..4db0470538027f 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c +++ b/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c @@ -44,10 +44,10 @@ #include "sl_device_init_hfxo.h" #include "sl_status.h" +#include "WifiInterfaceAbstraction.h" #include "silabs_utils.h" #include "sl_si91x_ncp_utility.h" #include "wfx_host_events.h" -#include "wfx_rsi.h" #if SL_MX25CTRL_MUX sl_status_t sl_wfx_host_spiflash_cs_assert(void); diff --git a/examples/platform/silabs/efr32/rs911x/rs9117.gni b/examples/platform/silabs/efr32/rs911x/rs9117.gni index 1adf21a6168d58..63f027e59f9087 100644 --- a/examples/platform/silabs/efr32/rs911x/rs9117.gni +++ b/examples/platform/silabs/efr32/rs911x/rs9117.gni @@ -1,3 +1,17 @@ +# Copyright (c) 2024 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("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") import("${silabs_sdk_build_root}/efr32_sdk.gni") @@ -7,14 +21,14 @@ rs911x_src_plat = [ "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_interrupt.c", "${examples_plat_dir}/rs911x/hal/sl_si91x_ncp_utility.c", "${examples_plat_dir}/rs911x/hal/efx32_ncp_host.c", - "${silabs_common_plat_dir}/wifi/wfx_notify.cpp", - "${silabs_common_plat_dir}/wifi/wfx_rsi_host.cpp", + "${silabs_common_plat_dir}/wifi/WifiInterfaceAbstraction.cpp", ] rs9117_inc_plat = [ "${examples_plat_dir}/rs911x", "${examples_plat_dir}/rs911x/hal", "${wifi_sdk_root}/components/si91x/ble/inc", + "${silabs_common_plat_dir}/wifi", ] rs911x_cflags = [ "-Wno-empty-body" ] diff --git a/examples/platform/silabs/efr32/rs911x/rs911x.gni b/examples/platform/silabs/efr32/rs911x/rs911x.gni index c2a20607cc67bd..4aedb66dca9f0c 100644 --- a/examples/platform/silabs/efr32/rs911x/rs911x.gni +++ b/examples/platform/silabs/efr32/rs911x/rs911x.gni @@ -1,15 +1,28 @@ +# Copyright (c) 2024 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("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") import("${silabs_sdk_build_root}/efr32_sdk.gni") rs911x_src_plat = [ - "${examples_plat_dir}/rs911x/rsi_if.cpp", + "${examples_plat_dir}/rs911x/Rsi91xWifiInterface.cpp", "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_interrupt.c", "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_ioports.c", "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_timer.c", "${examples_plat_dir}/rs911x/hal/efx_spi.c", - "${silabs_common_plat_dir}/wifi/wfx_notify.cpp", - "${silabs_common_plat_dir}/wifi/wfx_rsi_host.cpp", + "${silabs_common_plat_dir}/wifi/WifiInterfaceAbstraction.cpp", ] # @@ -59,4 +72,5 @@ rs911x_inc_plat = [ "${examples_plat_dir}/rs911x", "${examples_plat_dir}/rs911x/hal", "${wiseconnect_sdk_root}/sapi/include", + "${silabs_common_plat_dir}/wifi", ] diff --git a/examples/platform/silabs/efr32/wf200/host_if.cpp b/examples/platform/silabs/efr32/wf200/Wf200WifiInterface.cpp similarity index 100% rename from examples/platform/silabs/efr32/wf200/host_if.cpp rename to examples/platform/silabs/efr32/wf200/Wf200WifiInterface.cpp diff --git a/examples/platform/silabs/efr32/wf200/sl_wfx_crypto.c b/examples/platform/silabs/efr32/wf200/sl_wfx_crypto.c deleted file mode 100644 index ddad3ec5b95dde..00000000000000 --- a/examples/platform/silabs/efr32/wf200/sl_wfx_crypto.c +++ /dev/null @@ -1,409 +0,0 @@ -/* - * - * Copyright (c) 2022 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. - */ - -#ifdef SL_WFX_USE_SECURE_LINK - -/* Includes */ - -#include "sl_wfx.h" -#include - -#include "mbedtls/ccm.h" -#include "mbedtls/ctr_drbg.h" -#include "mbedtls/ecdh.h" -#include "mbedtls/entropy.h" -#include "mbedtls/md.h" -#include "mbedtls/sha256.h" - -#include "FreeRTOS.h" -#include "queue.h" -#include "semphr.h" -#include "task.h" - -// Secure link MAC key location for WGM160P (in DI page in flash) -#ifdef EFM32GG11B820F2048GM64 // WGM160PX22KGA2 -#define SL_WFX_FCCC_BASE_ADDR ((void *) 0x0fe08000ul) -#define SL_WFX_FCCC_DI_OFFSET 0x1B0ul -#define SL_WFX_FCCC_DI_ADDR ((void *) (SL_WFX_FCCC_BASE_ADDR + SL_WFX_FCCC_DI_OFFSET)) -#define SL_WFX_SECURE_LINK_MAC_KEY_LOCATION ((void *) (SL_WFX_FCCC_BASE_ADDR + 0x3D0)) -#endif -/****************************************************** - * Macros - ******************************************************/ -#define MAC_KEY_FAIL_BYTE 0XFF -#define KEY_DIGEST_SIZE 92 -#define MEMCMP_FAIL 0 -#define MPI_SET 1 -#define SUCCESS_STATUS_WIFI_SECURE_LINK_EXCHANGE 0 -#define SHA224_0 0 -#define HMAC_SIZE 92 -#define MEMSET_LEN 1 -#define LABLE_LEN 24 -#define ADDRESS_LENGTH 0 -#define CCM_STATUS_SUCCESS 0 -/****************************************************** - * Constants - ******************************************************/ - -/* Semaphore to signal wfx driver available */ -extern TaskHandle_t wfx_securelink_task; -extern SemaphoreHandle_t wfx_securelink_rx_mutex; - -/****************************************************** - * Enumerations - ******************************************************/ - -/****************************************************** - * Type Definitions - ******************************************************/ - -/****************************************************** - * Structures - ******************************************************/ - -/****************************************************** - * Function Declarations - ******************************************************/ - -static inline void reverse_bytes(uint8_t * src, uint8_t length); - -/****************************************************** - * Variable Definitions - ******************************************************/ - -#if SL_WFX_SLK_CURVE25519 -static mbedtls_ecdh_context mbedtls_host_context; -static mbedtls_ctr_drbg_context host_drbg_context; -#endif -static mbedtls_entropy_context entropy; -uint8_t temp_key_location[SL_WFX_HOST_PUB_KEY_MAC_SIZE]; -#ifdef EFM32GG11B820F2048GM64 // WGM160PX22KGA2 -static const uint8_t * const secure_link_mac_key = (uint8_t *) SL_WFX_SECURE_LINK_MAC_KEY_LOCATION; -#else -static const uint8_t secure_link_mac_key[SL_WFX_SECURE_LINK_MAC_KEY_LENGTH] = { 0x2B, 0x49, 0xFD, 0x66, 0xCB, 0x74, 0x6D, 0x6B, - 0x4F, 0xDC, 0xC3, 0x79, 0x4E, 0xC5, 0x9A, 0x86, - 0xE5, 0x48, 0x2A, 0x41, 0x22, 0x87, 0x8B, 0x12, - 0x1A, 0x7C, 0x3E, 0xEF, 0xB7, 0x04, 0x9E, 0xB3 }; -#endif -/****************************************************** - * Function Definitions - ******************************************************/ -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_get_secure_link_mac_key(uint8_t *sl_mac_key) - * @brief - * Get secure link mac key - * @param[in] sl_mac_key: - * @return returns SL_STATUS_OK - *****************************************************************************/ -sl_status_t sl_wfx_host_get_secure_link_mac_key(uint8_t * sl_mac_key) -{ - sl_status_t result = SL_STATUS_WIFI_SECURE_LINK_MAC_KEY_ERROR; - - memcpy(sl_mac_key, secure_link_mac_key, SL_WFX_SECURE_LINK_MAC_KEY_LENGTH); - - for (uint8_t index = 0; index < SL_WFX_SECURE_LINK_MAC_KEY_LENGTH; ++index) - { - // Assuming 0xFF... when not written - if (sl_mac_key[index] != MAC_KEY_FAIL_BYTE) - { - result = SL_STATUS_OK; - break; - } - } - - return result; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_compute_pub_key(sl_wfx_securelink_exchange_pub_keys_req_body_t *request, - const uint8_t *sl_mac_key) - * @brief - * compute host public key - * @param[in] request : - * @param[in] sl_mac_key : - * @return returns SL_STATUS_OK - *****************************************************************************/ -sl_status_t sl_wfx_host_compute_pub_key(sl_wfx_securelink_exchange_pub_keys_req_body_t * request, const uint8_t * sl_mac_key) -{ - sl_status_t status = SL_STATUS_OK; - -#if SL_WFX_SLK_CURVE25519 - const char identifier[] = "ecdh"; - - mbedtls_ecdh_init(&mbedtls_host_context); - mbedtls_ctr_drbg_init(&host_drbg_context); - mbedtls_entropy_init(&entropy); - status = mbedtls_ctr_drbg_seed(&host_drbg_context, mbedtls_entropy_func, &entropy, (const unsigned char *) identifier, - sizeof(identifier)); - status += mbedtls_ecp_group_load(&mbedtls_host_context.grp, MBEDTLS_ECP_DP_CURVE25519); - status += mbedtls_ecdh_gen_public(&mbedtls_host_context.grp, &mbedtls_host_context.d, &mbedtls_host_context.Q, - mbedtls_ctr_drbg_random, &host_drbg_context); - status += mbedtls_mpi_write_binary(&mbedtls_host_context.Q.X, request->host_pub_key, SL_WFX_HOST_PUB_KEY_SIZE); -#else - mbedtls_entropy_init(&entropy); - status = mbedtls_entropy_func(&entropy, request->host_pub_key, SL_WFX_HOST_PUB_KEY_SIZE); -#endif - reverse_bytes(request->host_pub_key, SL_WFX_HOST_PUB_KEY_SIZE); - SL_WFX_ERROR_CHECK(status); - - // Generate SHA512 digest of public key - status = mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512), sl_mac_key, SL_WFX_HOST_PUB_KEY_SIZE, - request->host_pub_key, SL_WFX_HOST_PUB_KEY_SIZE, request->host_pub_key_mac); - SL_WFX_ERROR_CHECK(status); - -error_handler: - if (status != SL_STATUS_OK) - { - return SL_STATUS_WIFI_SECURE_LINK_EXCHANGE_FAILED; - } - return status; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_verify_pub_key(sl_wfx_securelink_exchange_pub_keys_ind_t *response_packet, - const uint8_t *sl_mac_key, - uint8_t *sl_host_pub_key) - * @brief - * verify host public key - * @param[in] response_packet: - * @param[in] sl_mac_key: - * @param[in] sl_host_pub_key: - * @return returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_verify_pub_key(sl_wfx_securelink_exchange_pub_keys_ind_t * response_packet, const uint8_t * sl_mac_key, - uint8_t * sl_host_pub_key) -{ - sl_status_t status = SL_STATUS_OK; - uint8_t shared_key_digest[KEY_DIGEST_SIZE]; - - if (xSemaphoreTake(wfx_securelink_rx_mutex, portMAX_DELAY) != pdTRUE) - { - return SL_STATUS_WIFI_SECURE_LINK_EXCHANGE_FAILED; - } - - // Compute the Hash and verify the public key/hashing - status = mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512), sl_mac_key, SL_WFX_NCP_PUB_KEY_SIZE, - response_packet->body.ncp_pub_key, SL_WFX_NCP_PUB_KEY_SIZE, temp_key_location); - SL_WFX_ERROR_CHECK(status); - - // Calculate session key if public key/SHA512 digest matches - if (memcmp(temp_key_location, response_packet->body.ncp_pub_key_mac, SL_WFX_HOST_PUB_KEY_MAC_SIZE) != MEMCMP_FAIL) - { - status = SL_STATUS_WIFI_SECURE_LINK_EXCHANGE_FAILED; - goto error_handler; - } - -#if SL_WFX_SLK_CURVE25519 - SL_WFX_UNUSED_PARAMETER(sl_host_pub_key); - - mbedtls_mpi_lset(&mbedtls_host_context.Qp.Z, MPI_SET); - - // Read Ineo public key - reverse_bytes(response_packet->body.ncp_pub_key, SL_WFX_NCP_PUB_KEY_SIZE); - mbedtls_mpi_read_binary(&mbedtls_host_context.Qp.X, response_packet->body.ncp_pub_key, SL_WFX_NCP_PUB_KEY_SIZE); - - // Calculate shared secret - if (mbedtls_ecdh_compute_shared(&mbedtls_host_context.grp, &mbedtls_host_context.z, &mbedtls_host_context.Qp, - &mbedtls_host_context.d, mbedtls_ctr_drbg_random, - &host_drbg_context) != SUCCESS_STATUS_WIFI_SECURE_LINK_EXCHANGE) - { - status = SL_STATUS_WIFI_SECURE_LINK_EXCHANGE_FAILED; - goto error_handler; - } - - // Generate session key - mbedtls_mpi_write_binary(&mbedtls_host_context.z, temp_key_location, SL_WFX_HOST_PUB_KEY_SIZE); - reverse_bytes(temp_key_location, SL_WFX_HOST_PUB_KEY_SIZE); - mbedtls_sha256(temp_key_location, SL_WFX_HOST_PUB_KEY_SIZE, shared_key_digest, SHA224_0); -#else - uint8_t hmac_input[HMAC_SIZE] = { 0 }; - char label[LABLE_LEN] = "SecureLink!KeyDerivation"; - - memset((uint16_t *) &hmac_input[0], (uint16_t) sl_wfx_htole16(1), MEMSET_LEN); - memcpy((uint8_t *) &hmac_input[2], (uint8_t *) label, LABLE_LEN); - memcpy((uint8_t *) &hmac_input[26], sl_host_pub_key, SL_WFX_NCP_PUB_KEY_SIZE); - memcpy((uint8_t *) &hmac_input[58], (uint8_t *) response_packet->body.ncp_pub_key, SL_WFX_NCP_PUB_KEY_SIZE); - memset((uint16_t *) &hmac_input[90], (uint16_t) sl_wfx_htole16(128), 1); - - // Generate SHA256 digest of hmac_input - status = mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), sl_mac_key, SL_WFX_HOST_PUB_KEY_SIZE, - (uint8_t *) hmac_input, HMAC_SIZE, shared_key_digest); -#endif - - memcpy(sl_wfx_context->secure_link_session_key, shared_key_digest, - SL_WFX_SECURE_LINK_SESSION_KEY_LENGTH); // Use the lower 16 bytes of the sha256 - sl_wfx_context->secure_link_nonce.hp_packet_count = 0; - sl_wfx_context->secure_link_nonce.rx_packet_count = 0; - sl_wfx_context->secure_link_nonce.tx_packet_count = 0; - -error_handler: - if (xSemaphoreGive(wfx_securelink_rx_mutex) != pdTRUE) - { - printf("ERROR: sl_wfx_securelink_rx_mutex. unable to post.\n"); - } - return status; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_free_crypto_context(void) - * @brief - * Free host crypto context - * @param[in] None - * @return returns SL_STATUS_OK - *****************************************************************************/ -sl_status_t sl_wfx_host_free_crypto_context(void) -{ -#if SL_WFX_SLK_CURVE25519 - mbedtls_ecdh_free(&mbedtls_host_context); - mbedtls_ctr_drbg_free(&host_drbg_context); -#endif - mbedtls_entropy_free(&entropy); - - return SL_STATUS_OK; -} - -/******************************************************************************** - * @fn sl_status_t sl_wfx_host_decode_secure_link_data(uint8_t *buffer, uint32_t length, uint8_t *session_key) - * @brief - * Decode receive data - * Length excludes size of CCM tag and secure link header - * @param[in] buffer: - * @param[in] length: - * @param[in] session_key: - * @return returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - ********************************************************************************/ -sl_status_t sl_wfx_host_decode_secure_link_data(uint8_t * buffer, uint32_t length, uint8_t * session_key) -{ - mbedtls_ccm_context ccm_context; - sl_status_t status = SL_STATUS_SECURITY_DECRYPT_ERROR; - int crypto_status; - sl_wfx_nonce_t nonce = { 0, 0, 0 }; - - if (xSemaphoreTake(wfx_securelink_rx_mutex, portMAX_DELAY) != pdTRUE) - { - return SL_STATUS_FAIL; - } - - // Nonce for decryption should have TX and HP counters 0, only use RX counter - nonce.rx_packet_count = sl_wfx_context->secure_link_nonce.rx_packet_count; - - // Init context - mbedtls_ccm_init(&ccm_context); - - // Set the crypto key - crypto_status = mbedtls_ccm_setkey(&ccm_context, MBEDTLS_CIPHER_ID_AES, session_key, SL_WFX_SECURE_LINK_SESSION_KEY_BIT_COUNT); - SL_WFX_ERROR_CHECK(crypto_status); - - // Decrypt the data - if (!mbedtls_ccm_auth_decrypt(&ccm_context, length, (uint8_t *) &nonce, SL_WFX_SECURE_LINK_NONCE_SIZE_BYTES, NULL, - ADDRESS_LENGTH, (uint8_t *) buffer, (uint8_t *) buffer, (uint8_t *) buffer + length, - SL_WFX_SECURE_LINK_CCM_TAG_SIZE)) - { - status = SL_STATUS_OK; - } - -error_handler: - mbedtls_ccm_free(&ccm_context); - if (xSemaphoreGive(wfx_securelink_rx_mutex) != pdTRUE) - { - printf("ERROR: sl_wfx_securelink_rx_mutex. unable to post.\n"); - } - return status; -} - -/********************************************************************* - * @fn sl_status_t sl_wfx_host_encode_secure_link_data(sl_wfx_generic_message_t *buffer, - uint32_t data_length, - uint8_t *session_key, - uint8_t *nonce) - * @brief - * Encode transmit data - * Length excludes size of CCM tag and secure link header - * @param[in] buffer: - * @param[in] data_length: - * @param[in] session_key: - * @param[in] nonce: - * @return returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise -*************************************************************************/ -sl_status_t sl_wfx_host_encode_secure_link_data(sl_wfx_generic_message_t * buffer, uint32_t data_length, uint8_t * session_key, - uint8_t * nonce) -{ - mbedtls_ccm_context ccm_context; - sl_status_t status = SL_STATUS_FAIL; - - mbedtls_ccm_init(&ccm_context); - if (mbedtls_ccm_setkey(&ccm_context, MBEDTLS_CIPHER_ID_AES, session_key, SL_WFX_SECURE_LINK_SESSION_KEY_BIT_COUNT) == - CCM_STATUS_SUCCESS) - { - mbedtls_ccm_encrypt_and_tag(&ccm_context, data_length, nonce, SL_WFX_SECURE_LINK_NONCE_SIZE_BYTES, NULL, ADDRESS_LENGTH, - (uint8_t *) &buffer->header.id, (uint8_t *) &buffer->header.id, - (uint8_t *) &buffer->header.id + data_length, SL_WFX_SECURE_LINK_CCM_TAG_SIZE); - status = SL_STATUS_OK; - } - - mbedtls_ccm_free(&ccm_context); - - return status; -} - -/**************************************************************************** - * @fn sl_status_t sl_wfx_host_schedule_secure_link_renegotiation(void) - * @brief - * Called when the driver needs to schedule secure link renegotiation - * @param[in] None - * @returns Returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - *****************************************************************************/ -sl_status_t sl_wfx_host_schedule_secure_link_renegotiation(void) -{ - // call sl_wfx_secure_link_renegotiate_session_key() as soon as it makes sense for the host to do so - xTaskNotifyGive(wfx_securelink_task); - return SL_STATUS_OK; -} - -/**************************************************************************** - * @fn static inline void reverse_bytes(uint8_t *src, uint8_t length) - * @brief - * reverse the bytes - * @param[in] src: source - * @param[in] length: - * @returns None - *****************************************************************************/ -static inline void reverse_bytes(uint8_t * src, uint8_t length) -{ - uint8_t * lo = src; - uint8_t * hi = src + length - 1; - uint8_t swap; - - while (lo < hi) - { - swap = *lo; - *lo++ = *hi; - *hi-- = swap; - } -} - -/******************************************************************************************************** - ******************************************************************************************************** - * DEPENDENCIES & AVAIL CHECK(S) - ******************************************************************************************************** - *******************************************************************************************************/ - -#endif // SL_WFX_USE_SECURE_LINK diff --git a/examples/platform/silabs/efr32/wf200/sl_wfx_securelink_task.c b/examples/platform/silabs/efr32/wf200/sl_wfx_securelink_task.c deleted file mode 100644 index 28ffdda2c3852f..00000000000000 --- a/examples/platform/silabs/efr32/wf200/sl_wfx_securelink_task.c +++ /dev/null @@ -1,85 +0,0 @@ -/* - * - * Copyright (c) 2022 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. - */ - -#ifdef SL_WFX_USE_SECURE_LINK -#include "secure_link/sl_wfx_secure_link.h" - -#include "FreeRTOS.h" -#include "queue.h" -#include "semphr.h" -#include "task.h" -#include -#include -#include - -// Securelink Task Configurations -#define WFX_SECURELINK_TASK_PRIO 1u -#define WFX_SECURELINK_TASK_STK_SIZE 512u - -TaskHandle_t secureLinkTaskHandle; -SemaphoreHandle_t s_xSLSemaphore; -StackType_t secureLinkStack[WFX_SECURELINK_TASK_STK_SIZE]; -StaticTask_t secureLinkTaskStruct; - -StaticSemaphore_t xSlMutexBuffer; - -/********************************************************************* - * @fn static void prvSecureLinkTask(void *p_arg) - * @brief - * The task that implements the Secure Link renegotiation with WFX. - * @param[in] p_arg: - * @return None - *************************************************************************/ -static void prvSecureLinkTask(void * p_arg) -{ - sl_status_t result; - (void) p_arg; - - /* Create a mutex used for making Secure Link renegotiations atomic */ - s_xSLSemaphore = xSemaphoreCreateMutexStatic(&xSlMutexBuffer); - - for (;;) - { - /* Wait for a key renegotiation request */ - ulTaskNotifyTake(pdTRUE, portMAX_DELAY); - - result = sl_wfx_secure_link_renegotiate_session_key(); - if (result != SL_STATUS_OK) - { - printf("session key negotiation error %lu\n", result); - } - } -} - -/**************************************************************************** - * @fn void wfx_securelink_task_start(void) - * @brief - * Creates WFX securelink key renegotiation task. - * @param[in] None - * @return None - ******************************************************************************/ -void wfx_securelink_task_start(void) -{ - secureLinkTaskHandle = xTaskCreateStatic(prvSecureLinkTask, "secureLinkTask", WFX_SECURELINK_TASK_STK_SIZE, NULL, - WFX_SECURELINK_TASK_PRIO, secureLinkStack, &secureLinkTaskStruct); - if (secureLinkTaskHandle == NULL) - { - printf("Failed to create WFX secureLinkTask"); - } -} - -#endif diff --git a/examples/platform/silabs/efr32/wf200/wf200.gni b/examples/platform/silabs/efr32/wf200/wf200.gni index f904f74495c632..c7ebbb8647788c 100644 --- a/examples/platform/silabs/efr32/wf200/wf200.gni +++ b/examples/platform/silabs/efr32/wf200/wf200.gni @@ -1,12 +1,30 @@ +# Copyright (c) 2024 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("//build_overrides/chip.gni") import("//build_overrides/efr32_sdk.gni") import("${silabs_sdk_build_root}/efr32_sdk.gni") -wf200_plat_incs = [ "${examples_plat_dir}/wf200" ] +wf200_plat_incs = [ + "${examples_plat_dir}/wf200", + "${silabs_common_plat_dir}/wifi", +] + wf200_plat_src = [ - "${silabs_common_plat_dir}/wifi/wfx_notify.cpp", "${examples_plat_dir}/wf200/sl_wfx_task.c", "${examples_plat_dir}/wf200/wf200_init.c", "${examples_plat_dir}/wf200/efr_spi.c", - "${examples_plat_dir}/wf200/host_if.cpp", + "${examples_plat_dir}/wf200/Wf200WifiInterface.cpp", + "${silabs_common_plat_dir}/wifi/WifiInterfaceAbstraction.cpp", ] diff --git a/examples/platform/silabs/wifi/wfx_rsi_host.cpp b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp similarity index 64% rename from examples/platform/silabs/wifi/wfx_rsi_host.cpp rename to examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp index 3263d884c70af3..0a21244f342194 100644 --- a/examples/platform/silabs/wifi/wfx_rsi_host.cpp +++ b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp @@ -17,30 +17,38 @@ // SL MATTER WI-FI INTERFACE +#include "WifiInterfaceAbstraction.h" +#include "silabs_utils.h" +#include "wfx_host_events.h" +#include +#include +#include +#include +#include +#include #include #include #include #include -#include "FreeRTOS.h" -#include "event_groups.h" -#include "task.h" - -#include -#include -#include -#include +using namespace chip; +using namespace chip::DeviceLayer; -#include "wfx_host_events.h" -#include "wfx_rsi.h" +namespace { -#include +constexpr uint8_t kWlanMinRetryIntervalsInSec = 1; +constexpr uint8_t kWlanMaxRetryIntervalsInSec = 60; +constexpr uint8_t kWlanRetryIntervalInSec = 5; +uint8_t retryInterval = kWlanMinRetryIntervalsInSec; +osTimerId_t sRetryTimer; +// TODO: Remove this when the full abstraction is implemented +#ifdef RS911X_WIFI // Thread for the WLAN RSI -static osThreadId_t sWlanThread; +osThreadId_t sWlanThread; constexpr uint32_t kWlanTaskSize = 2048; -static uint8_t wlanStack[kWlanTaskSize]; -static osThread_t sWlanTaskControlBlock; +uint8_t wlanStack[kWlanTaskSize]; +osThread_t sWlanTaskControlBlock; constexpr osThreadAttr_t kWlanTaskAttr = { .name = "wlan_rsi", .attr_bits = osThreadDetached, .cb_mem = &sWlanTaskControlBlock, @@ -48,7 +56,27 @@ constexpr osThreadAttr_t kWlanTaskAttr = { .name = "wlan_rsi", .stack_mem = wlanStack, .stack_size = kWlanTaskSize, .priority = osPriorityAboveNormal7 }; +#endif // RS911X_WIFI +/* + * Notifications to the upper-layer + * All done in the context of the RSI/WiFi task (rsi_if.c) + */ +void RetryConnectionTimerHandler(void * arg) +{ +#if CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE + wfx_rsi_power_save(RSI_ACTIVE, HIGH_PERFORMANCE); +#endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE + if (wfx_connect_to_ap() != SL_STATUS_OK) + { + ChipLogError(DeviceLayer, "wfx_connect_to_ap() failed."); + } +} + +} // namespace + +// TODO: Remove this when the full abstraction is implemented +#ifdef RS911X_WIFI /********************************************************************* * @fn sl_status_t wfx_wifi_start(void) * @brief @@ -397,3 +425,172 @@ void wfx_cancel_scan(void) ChipLogError(DeviceLayer, "cannot cancel scan"); } #endif /* SL_WFX_CONFIG_SCAN */ +#endif // RS911X_WIFI + +/*********************************************************************************** + * @fn sl_matter_wifi_task_started(void) + * @brief + * Wifi device started notification + * @param[in]: None + * @return None + *************************************************************************************/ +void sl_matter_wifi_task_started(void) +{ + sl_wfx_startup_ind_t evt; + sl_wfx_mac_address_t mac; + + // Creating a timer which will be used to retry connection with AP + sRetryTimer = osTimerNew(RetryConnectionTimerHandler, osTimerOnce, NULL, NULL); + VerifyOrReturn(sRetryTimer != NULL); + + memset(&evt, 0, sizeof(evt)); + evt.header.id = SL_WFX_STARTUP_IND_ID; + evt.header.length = sizeof evt; + evt.body.status = 0; + wfx_get_wifi_mac_addr(SL_WFX_STA_INTERFACE, &mac); + memcpy(&evt.body.mac_addr[0], &mac.octet[0], MAC_ADDRESS_FIRST_OCTET); + + PlatformMgrImpl().HandleWFXSystemEvent(WIFI_EVENT, (sl_wfx_generic_message_t *) &evt); +} + +/*********************************************************************************** + * @fn void wfx_connected_notify(int32_t status, sl_wfx_mac_address_t *ap) + * @brief + * For now we are not notifying anything other than AP Mac - + * Other stuff such as DTIM etc. may be required for later + * @param[in] status: + * @param[in] ap: access point + * @return None + *************************************************************************************/ +void wfx_connected_notify(int32_t status, sl_wfx_mac_address_t * ap) +{ + sl_wfx_connect_ind_t evt; + + VerifyOrReturn(status == SUCCESS_STATUS); + + memset(&evt, 0, sizeof(evt)); + evt.header.id = SL_WFX_CONNECT_IND_ID; + evt.header.length = sizeof evt; + +#ifdef RS911X_WIFI + evt.body.channel = wfx_rsi.ap_chan; +#endif + memcpy(&evt.body.mac[0], &ap->octet[0], MAC_ADDRESS_FIRST_OCTET); + + PlatformMgrImpl().HandleWFXSystemEvent(WIFI_EVENT, (sl_wfx_generic_message_t *) &evt); +} + +/************************************************************************************** + * @fn void wfx_disconnected_notify(int32_t status) + * @brief + * notification of disconnection + * @param[in] status: + * @return None + ********************************************************************************************/ +void wfx_disconnected_notify(int32_t status) +{ + sl_wfx_disconnect_ind_t evt; + + memset(&evt, 0, sizeof(evt)); + evt.header.id = SL_WFX_DISCONNECT_IND_ID; + evt.header.length = sizeof evt; + evt.body.reason = status; + PlatformMgrImpl().HandleWFXSystemEvent(WIFI_EVENT, (sl_wfx_generic_message_t *) &evt); +} + +/************************************************************************************** + * @fn void wfx_ipv6_notify(int got_ip) + * @brief + * notification of ipv6 + * @param[in] got_ip: + * @return None + ********************************************************************************************/ +void wfx_ipv6_notify(int got_ip) +{ + sl_wfx_generic_message_t eventData; + + memset(&eventData, 0, sizeof(eventData)); + eventData.header.id = got_ip ? IP_EVENT_GOT_IP6 : IP_EVENT_STA_LOST_IP; + eventData.header.length = sizeof(eventData.header); + PlatformMgrImpl().HandleWFXSystemEvent(IP_EVENT, &eventData); +} + +/************************************************************************************** + * @fn void wfx_ip_changed_notify(int got_ip) + * @brief + * notification of ip change + * @param[in] got_ip: + * @return None + ********************************************************************************************/ +void wfx_ip_changed_notify(int got_ip) +{ + sl_wfx_generic_message_t eventData; + + memset(&eventData, 0, sizeof(eventData)); + eventData.header.id = got_ip ? IP_EVENT_STA_GOT_IP : IP_EVENT_STA_LOST_IP; + eventData.header.length = sizeof(eventData.header); + PlatformMgrImpl().HandleWFXSystemEvent(IP_EVENT, &eventData); +} + +/************************************************************************************** + * @fn void wfx_retry_connection(uint16_t retryAttempt) + * @brief + * During commissioning, we retry to join the network MAX_JOIN_RETRIES_COUNT times. + * If DUT is disconnected from the AP or device is power cycled, then retry connection + * with AP continously after a certain time interval. + * @param[in] retryAttempt + * @return None + ********************************************************************************************/ +void wfx_retry_connection(uint16_t retryAttempt) +{ + // During commissioning, we retry to join the network MAX_JOIN_RETRIES_COUNT + if (/*BaseApplication::sAppDelegate.isCommissioningInProgress()*/ true) + { + if (retryAttempt < MAX_JOIN_RETRIES_COUNT) + { + ChipLogProgress(DeviceLayer, "wfx_retry_connection : Next attempt after %d Seconds", kWlanRetryIntervalInSec); + if (osTimerStart(sRetryTimer, pdMS_TO_TICKS(CONVERT_SEC_TO_MS(kWlanRetryIntervalInSec))) != osOK) + { + ChipLogProgress(DeviceLayer, "Failed to start retry timer"); + // Sending the join command if retry timer failed to start + if (wfx_connect_to_ap() != SL_STATUS_OK) + { + ChipLogError(DeviceLayer, "wfx_connect_to_ap() failed."); + } + return; + } + } + else + { + ChipLogProgress(DeviceLayer, "Connect failed after max %d tries", retryAttempt); + } + } + else + { + /* After disconnection or power cycle the DUT + * At the telescopic time interval device try to reconnect with AP, upto WLAN_MAX_RETRY_TIMER_MS intervals + * are telescopic. If interval exceed WLAN_MAX_RETRY_TIMER_MS then it will try to reconnect at + * WLAN_MAX_RETRY_TIMER_MS intervals. + */ + if (retryInterval > kWlanMaxRetryIntervalsInSec) + { + retryInterval = kWlanMaxRetryIntervalsInSec; + } + if (osTimerStart(sRetryTimer, pdMS_TO_TICKS(CONVERT_SEC_TO_MS(retryInterval))) != osOK) + { + ChipLogProgress(DeviceLayer, "Failed to start retry timer"); + // Sending the join command if retry timer failed to start + if (wfx_connect_to_ap() != SL_STATUS_OK) + { + ChipLogError(DeviceLayer, "wfx_connect_to_ap() failed."); + } + return; + } +#if CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE + wfx_rsi_power_save(RSI_SLEEP_MODE_8, STANDBY_POWER_SAVE_WITH_RAM_RETENTION); +#endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE + ChipLogProgress(DeviceLayer, "wfx_retry_connection : Next attempt after %d Seconds", retryInterval); + retryInterval += retryInterval; + return; + } +} diff --git a/examples/platform/silabs/wfx_rsi.h b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h similarity index 98% rename from examples/platform/silabs/wfx_rsi.h rename to examples/platform/silabs/wifi/WifiInterfaceAbstraction.h index 4ef6bd224fdfb5..a26ead2579b16a 100644 --- a/examples/platform/silabs/wfx_rsi.h +++ b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h @@ -18,14 +18,9 @@ #include #include -#include #include #include -#ifndef RSI_BLE_ENABLE -#define RSI_BLE_ENABLE (1) -#endif - /* * Interface to RSI Sapis */ diff --git a/examples/platform/silabs/wifi/wfx_notify.cpp b/examples/platform/silabs/wifi/wfx_notify.cpp deleted file mode 100644 index fe097a60983e7f..00000000000000 --- a/examples/platform/silabs/wifi/wfx_notify.cpp +++ /dev/null @@ -1,228 +0,0 @@ -/* - * - * Copyright (c) 2022 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. - */ - -#include "AppConfig.h" -#include "BaseApplication.h" -#include -#include -#include -#include - -#include "FreeRTOS.h" -#include "event_groups.h" -#include "silabs_utils.h" -#include "task.h" -#include "wfx_host_events.h" - -#ifdef RS911X_WIFI -#include "wfx_rsi.h" -#endif - -#include - -using namespace ::chip; -using namespace ::chip::DeviceLayer; - -namespace { -constexpr uint8_t kWlanMinRetryIntervalsInSec = 1; -constexpr uint8_t kWlanMaxRetryIntervalsInSec = 60; -constexpr uint8_t kWlanRetryIntervalInSec = 5; -uint8_t retryInterval = kWlanMinRetryIntervalsInSec; -osTimerId_t sRetryTimer; -} // namespace -/* - * Notifications to the upper-layer - * All done in the context of the RSI/WiFi task (rsi_if.c) - */ - -static void RetryConnectionTimerHandler(void * arg) -{ -#if CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE - wfx_rsi_power_save(RSI_ACTIVE, HIGH_PERFORMANCE); -#endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE - if (wfx_connect_to_ap() != SL_STATUS_OK) - { - ChipLogError(DeviceLayer, "wfx_connect_to_ap() failed."); - } -} -/*********************************************************************************** - * @fn sl_matter_wifi_task_started(void) - * @brief - * Wifi device started notification - * @param[in]: None - * @return None - *************************************************************************************/ -void sl_matter_wifi_task_started(void) -{ - sl_wfx_startup_ind_t evt; - sl_wfx_mac_address_t mac; - - // Creating a timer which will be used to retry connection with AP - sRetryTimer = osTimerNew(RetryConnectionTimerHandler, osTimerOnce, NULL, NULL); - VerifyOrReturn(sRetryTimer != NULL); - - memset(&evt, 0, sizeof(evt)); - evt.header.id = SL_WFX_STARTUP_IND_ID; - evt.header.length = sizeof evt; - evt.body.status = 0; - wfx_get_wifi_mac_addr(SL_WFX_STA_INTERFACE, &mac); - memcpy(&evt.body.mac_addr[0], &mac.octet[0], MAC_ADDRESS_FIRST_OCTET); - - PlatformMgrImpl().HandleWFXSystemEvent(WIFI_EVENT, (sl_wfx_generic_message_t *) &evt); -} - -/*********************************************************************************** - * @fn void wfx_connected_notify(int32_t status, sl_wfx_mac_address_t *ap) - * @brief - * For now we are not notifying anything other than AP Mac - - * Other stuff such as DTIM etc. may be required for later - * @param[in] status: - * @param[in] ap: access point - * @return None - *************************************************************************************/ -void wfx_connected_notify(int32_t status, sl_wfx_mac_address_t * ap) -{ - sl_wfx_connect_ind_t evt; - - VerifyOrReturn(status == SUCCESS_STATUS); - - memset(&evt, 0, sizeof(evt)); - evt.header.id = SL_WFX_CONNECT_IND_ID; - evt.header.length = sizeof evt; - -#ifdef RS911X_WIFI - evt.body.channel = wfx_rsi.ap_chan; -#endif - memcpy(&evt.body.mac[0], &ap->octet[0], MAC_ADDRESS_FIRST_OCTET); - - PlatformMgrImpl().HandleWFXSystemEvent(WIFI_EVENT, (sl_wfx_generic_message_t *) &evt); -} - -/************************************************************************************** - * @fn void wfx_disconnected_notify(int32_t status) - * @brief - * notification of disconnection - * @param[in] status: - * @return None - ********************************************************************************************/ -void wfx_disconnected_notify(int32_t status) -{ - sl_wfx_disconnect_ind_t evt; - - memset(&evt, 0, sizeof(evt)); - evt.header.id = SL_WFX_DISCONNECT_IND_ID; - evt.header.length = sizeof evt; - evt.body.reason = status; - PlatformMgrImpl().HandleWFXSystemEvent(WIFI_EVENT, (sl_wfx_generic_message_t *) &evt); -} - -/************************************************************************************** - * @fn void wfx_ipv6_notify(int got_ip) - * @brief - * notification of ipv6 - * @param[in] got_ip: - * @return None - ********************************************************************************************/ -void wfx_ipv6_notify(int got_ip) -{ - sl_wfx_generic_message_t eventData; - - memset(&eventData, 0, sizeof(eventData)); - eventData.header.id = got_ip ? IP_EVENT_GOT_IP6 : IP_EVENT_STA_LOST_IP; - eventData.header.length = sizeof(eventData.header); - PlatformMgrImpl().HandleWFXSystemEvent(IP_EVENT, &eventData); -} - -/************************************************************************************** - * @fn void wfx_ip_changed_notify(int got_ip) - * @brief - * notification of ip change - * @param[in] got_ip: - * @return None - ********************************************************************************************/ -void wfx_ip_changed_notify(int got_ip) -{ - sl_wfx_generic_message_t eventData; - - memset(&eventData, 0, sizeof(eventData)); - eventData.header.id = got_ip ? IP_EVENT_STA_GOT_IP : IP_EVENT_STA_LOST_IP; - eventData.header.length = sizeof(eventData.header); - PlatformMgrImpl().HandleWFXSystemEvent(IP_EVENT, &eventData); -} - -/************************************************************************************** - * @fn void wfx_retry_connection(uint16_t retryAttempt) - * @brief - * During commissioning, we retry to join the network MAX_JOIN_RETRIES_COUNT times. - * If DUT is disconnected from the AP or device is power cycled, then retry connection - * with AP continously after a certain time interval. - * @param[in] retryAttempt - * @return None - ********************************************************************************************/ -void wfx_retry_connection(uint16_t retryAttempt) -{ - // During commissioning, we retry to join the network MAX_JOIN_RETRIES_COUNT - if (BaseApplication::sAppDelegate.isCommissioningInProgress()) - { - if (retryAttempt < MAX_JOIN_RETRIES_COUNT) - { - ChipLogProgress(DeviceLayer, "wfx_retry_connection : Next attempt after %d Seconds", kWlanRetryIntervalInSec); - if (osTimerStart(sRetryTimer, pdMS_TO_TICKS(CONVERT_SEC_TO_MS(kWlanRetryIntervalInSec))) != osOK) - { - ChipLogProgress(DeviceLayer, "Failed to start retry timer"); - // Sending the join command if retry timer failed to start - if (wfx_connect_to_ap() != SL_STATUS_OK) - { - ChipLogError(DeviceLayer, "wfx_connect_to_ap() failed."); - } - return; - } - } - else - { - ChipLogProgress(DeviceLayer, "Connect failed after max %d tries", retryAttempt); - } - } - else - { - /* After disconnection or power cycle the DUT - * At the telescopic time interval device try to reconnect with AP, upto WLAN_MAX_RETRY_TIMER_MS intervals - * are telescopic. If interval exceed WLAN_MAX_RETRY_TIMER_MS then it will try to reconnect at - * WLAN_MAX_RETRY_TIMER_MS intervals. - */ - if (retryInterval > kWlanMaxRetryIntervalsInSec) - { - retryInterval = kWlanMaxRetryIntervalsInSec; - } - if (osTimerStart(sRetryTimer, pdMS_TO_TICKS(CONVERT_SEC_TO_MS(retryInterval))) != osOK) - { - ChipLogProgress(DeviceLayer, "Failed to start retry timer"); - // Sending the join command if retry timer failed to start - if (wfx_connect_to_ap() != SL_STATUS_OK) - { - ChipLogError(DeviceLayer, "wfx_connect_to_ap() failed."); - } - return; - } -#if CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE - wfx_rsi_power_save(RSI_SLEEP_MODE_8, STANDBY_POWER_SAVE_WITH_RAM_RETENTION); -#endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE - ChipLogProgress(DeviceLayer, "wfx_retry_connection : Next attempt after %d Seconds", retryInterval); - retryInterval += retryInterval; - return; - } -} diff --git a/src/platform/silabs/rs911x/wfx_sl_ble_init.h b/src/platform/silabs/rs911x/wfx_sl_ble_init.h index 54351674ef121e..7fd9fc94b9d58e 100644 --- a/src/platform/silabs/rs911x/wfx_sl_ble_init.h +++ b/src/platform/silabs/rs911x/wfx_sl_ble_init.h @@ -22,14 +22,10 @@ */ #pragma once -/** - * Include files - * */ // BLE include file to refer BLE APIs #include "ble_config.h" #include "cmsis_os2.h" #include "wfx_host_events.h" -#include "wfx_rsi.h" #include #include #include From aff2e17c6465caa0e3c03a0c1ab6c65a5072f30a Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Thu, 31 Oct 2024 18:14:03 +0100 Subject: [PATCH 033/121] [darwin-framework-tool][interactive] Add Ctrl+Z as a shortcut key to suspend or resume the running controllers (#36302) --- .../commands/common/CHIPCommandBridge.h | 2 ++ .../commands/common/CHIPCommandBridge.mm | 10 ++++++ .../interactive/InteractiveCommands.mm | 31 +++++++++++++++++-- 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h index 90f3a6c56415f6..a71f18ed301f9f 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h +++ b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h @@ -128,6 +128,8 @@ class CHIPCommandBridge : public Command { void RestartCommissioners(); + void SuspendOrResumeCommissioners(); + private: CHIP_ERROR InitializeCommissioner( std::string key, chip::FabricId fabricId, const chip::Credentials::AttestationTrustStore * trustStore); diff --git a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm index 6472d2cae77f5e..4a6e279d03fe66 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm +++ b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm @@ -358,6 +358,16 @@ [[MTRDeviceControllerFactory sharedInstance] stopControllerFactory]; } +void CHIPCommandBridge::SuspendOrResumeCommissioners() +{ + for (auto & pair : mControllers) { + __auto_type * commissioner = pair.second; + if (commissioner.running) { + commissioner.suspended ? [commissioner resume] : [commissioner suspend]; + } + } +} + CHIP_ERROR CHIPCommandBridge::StartWaiting(chip::System::Clock::Timeout duration) { auto waitingUntil = std::chrono::system_clock::now() + std::chrono::duration_cast(duration); diff --git a/examples/darwin-framework-tool/commands/interactive/InteractiveCommands.mm b/examples/darwin-framework-tool/commands/interactive/InteractiveCommands.mm index cfad15b781e129..b5bdcc9c2c531d 100644 --- a/examples/darwin-framework-tool/commands/interactive/InteractiveCommands.mm +++ b/examples/darwin-framework-tool/commands/interactive/InteractiveCommands.mm @@ -30,9 +30,10 @@ constexpr char kInteractiveModeInstruction[] = "╔══════════════════════════════════════════════════════════════════╗\n" "║ Interactive Mode ║\n" "╠══════════════════════════════════════════════════════════════════╣\n" - "║ Stop and restart stack: [Ctrl+_] & [Ctrl+^ ] ║\n" - "║ Trigger exit(0) : [Ctrl+@] ║\n" - "║ Quit Interactive : 'quit()' or `quit` ║\n" + "║ Stop and restart stack : [Ctrl+_] & [Ctrl+^ ] ║\n" + "║ Suspend/Resume controllers: [Ctrl+Z] ║\n" + "║ Trigger exit(0) : [Ctrl+@] ║\n" + "║ Quit Interactive : 'quit()' or `quit` ║\n" "╚══════════════════════════════════════════════════════════════════╝\n"; constexpr char kInteractiveModePrompt[] = ">>> "; constexpr char kInteractiveModeHistoryFilePath[] = "/tmp/darwin_framework_tool_history"; @@ -76,6 +77,22 @@ CHIP_ERROR RunCommand() override chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::Seconds16(0); } }; +class SuspendOrResumeCommand : public CHIPCommandBridge { +public: + SuspendOrResumeCommand() + : CHIPCommandBridge("suspend") + { + } + + CHIP_ERROR RunCommand() override + { + SuspendOrResumeCommissioners(); + return CHIP_NO_ERROR; + } + + chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::Seconds16(0); } +}; + void ClearLine() { printf("\r\x1B[0J"); // Move cursor to the beginning of the line and clear from cursor to end of the screen @@ -312,6 +329,13 @@ el_status_t StopFunction() return CSstay; } +el_status_t SuspendOrResumeFunction() +{ + SuspendOrResumeCommand cmd; + cmd.RunCommand(); + return CSstay; +} + el_status_t ExitFunction() { exit(0); @@ -333,6 +357,7 @@ el_status_t ExitFunction() el_bind_key(CTL('^'), RestartFunction); el_bind_key(CTL('_'), StopFunction); el_bind_key(CTL('@'), ExitFunction); + el_bind_key(CTL('Z'), SuspendOrResumeFunction); char * command = nullptr; int status; From edd92020d0a7290d84e79b9d06e42a357d2d4877 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 31 Oct 2024 13:27:11 -0400 Subject: [PATCH 034/121] Remove "run on work queue" bits from non-concrete controllers. (#36320) * Remove "run on work queue" bits from non-concrete controllers. There is no "work queue" in the sense of the Matter queue involved unless we have a concrete controller. * syncRunOnWorkQueueWithReturnValue was unused on MTRDeviceController, so can just be removed. * syncRunOnWorkQueueWithBoolReturnValue was unused on MTRDeviceController, so can just be removed. * After that syncRunOnWorkQueue becomes unused and can be removed. * At this point chipWorkQueue is not used on the base class and can be moved into the subclasses as needed. * Apply suggestion from code review. --- .../Framework/CHIP/MTRDeviceController.mm | 34 ------------------- .../CHIP/MTRDeviceController_Internal.h | 3 -- .../Framework/CHIP/MTRDeviceController_XPC.mm | 7 ++-- 3 files changed, 4 insertions(+), 40 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index 5850d88601a4f3..ce2668538c7e02 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -542,40 +542,6 @@ - (void)asyncDispatchToMatterQueue:(dispatch_block_t)block errorHandler:(nullabl errorHandler([MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]); } -- (void)syncRunOnWorkQueue:(SyncWorkQueueBlock)block error:(NSError * __autoreleasing *)error -{ - VerifyOrDie(!chip::DeviceLayer::PlatformMgrImpl().IsWorkQueueCurrentQueue()); - VerifyOrReturn([self checkIsRunning:error]); - - dispatch_sync(_chipWorkQueue, ^{ - VerifyOrReturn([self checkIsRunning:error]); - block(); - }); -} - -- (id)syncRunOnWorkQueueWithReturnValue:(SyncWorkQueueBlockWithReturnValue)block error:(NSError * __autoreleasing *)error -{ - __block id rv = nil; - auto adapter = ^{ - rv = block(); - }; - - [self syncRunOnWorkQueue:adapter error:error]; - - return rv; -} - -- (BOOL)syncRunOnWorkQueueWithBoolReturnValue:(SyncWorkQueueBlockWithBoolReturnValue)block error:(NSError * __autoreleasing *)error -{ - __block BOOL success = NO; - auto adapter = ^{ - success = block(); - }; - [self syncRunOnWorkQueue:adapter error:error]; - - return success; -} - - (chip::FabricIndex)fabricIndex { return _storedFabricIndex; diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h index 145f32940941d8..585b292b5a369d 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h @@ -68,10 +68,7 @@ NS_ASSUME_NONNULL_BEGIN @property (readonly, assign) os_unfair_lock_t deviceMapLock; @property (readwrite, nonatomic) NSUUID * uniqueIdentifier; - -// queue used to serialize all work performed by the MTRDeviceController // (moved here so subclasses can initialize differently) -@property (readwrite, retain) dispatch_queue_t chipWorkQueue; - (instancetype)initForSubclasses:(BOOL)startSuspended; diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm index d737e4d95d9856..2fdbef529cf832 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -37,6 +37,7 @@ @interface MTRDeviceController_XPC () @property (nonnull, atomic, readwrite, retain) MTRXPCDeviceControllerParameters * xpcParameters; @property (atomic, readwrite, assign) NSTimeInterval xpcRetryTimeInterval; @property (atomic, readwrite, assign) BOOL xpcConnectedOrConnecting; +@property (nonatomic, readonly, retain) dispatch_queue_t workQueue; @end @@ -194,7 +195,7 @@ - (void)_startXPCConnectionRetry self.xpcRetryTimeInterval = 0.5; mtr_weakify(self); - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (self.xpcRetryTimeInterval * NSEC_PER_SEC)), self.chipWorkQueue, ^{ + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (self.xpcRetryTimeInterval * NSEC_PER_SEC)), self.workQueue, ^{ mtr_strongify(self); [self _xpcConnectionRetry]; }); @@ -214,7 +215,7 @@ - (void)_xpcConnectionRetry self.xpcRetryTimeInterval = MIN(60.0, self.xpcRetryTimeInterval); mtr_weakify(self); - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.xpcRetryTimeInterval * NSEC_PER_SEC)), self.chipWorkQueue, ^{ + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.xpcRetryTimeInterval * NSEC_PER_SEC)), self.workQueue, ^{ mtr_strongify(self); [self _xpcConnectionRetry]; }); @@ -302,7 +303,7 @@ - (nullable instancetype)initWithParameters:(MTRDeviceControllerAbstractParamete self.uniqueIdentifier = UUID; self.xpcParameters = xpcParameters; - self.chipWorkQueue = dispatch_queue_create("MTRDeviceController_XPC_queue", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + _workQueue = dispatch_queue_create("MTRDeviceController_XPC_queue", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); if (![self _setupXPCConnection]) { return nil; From c4c9ccf52c01dbe0d76b4cfa06f4ddeb80c08d8d Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 31 Oct 2024 13:28:59 -0400 Subject: [PATCH 035/121] Remove various ivars and headers no longer needed in MTRDeviceController. (#36321) The functionality that used them has been moved out. --- .../Framework/CHIP/MTRDeviceController.mm | 43 +------------------ 1 file changed, 2 insertions(+), 41 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index ce2668538c7e02..102e4801bbfd12 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -14,20 +14,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#import #import #import #import "MTRDeviceController_Internal.h" #import "MTRAsyncWorkQueue.h" -#import "MTRAttestationTrustStoreBridge.h" #import "MTRBaseDevice_Internal.h" -#import "MTRCommissionableBrowser.h" -#import "MTRCommissionableBrowserResult_Internal.h" #import "MTRCommissioningParameters.h" #import "MTRConversion.h" #import "MTRDefines_Internal.h" -#import "MTRDeviceControllerDelegateBridge.h" #import "MTRDeviceControllerFactory_Internal.h" #import "MTRDeviceControllerLocalTestStorage.h" #import "MTRDeviceControllerStartupParams.h" @@ -43,40 +40,16 @@ #import "MTRLogging_Internal.h" #import "MTRMetricKeys.h" #import "MTRMetricsCollector.h" -#import "MTRP256KeypairBridge.h" #import "MTRPersistentStorageDelegateBridge.h" -#import "MTRServerEndpoint_Internal.h" #import "MTRSetupPayload.h" #import "MTRTimeUtils.h" #import "MTRUnfairLock.h" #import "MTRUtilities.h" #import "NSDataSpanConversion.h" #import "NSStringSpanConversion.h" -#import -#import -#import -#import "MTRDeviceAttestationDelegateBridge.h" -#import "MTRDeviceConnectionBridge.h" - -#include - -#include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include #include @@ -119,22 +92,10 @@ - (instancetype)initWithDelegate:(id)delegate queue @end @implementation MTRDeviceController { - chip::Credentials::PartialDACVerifier * _partialDACVerifier; - chip::Credentials::DefaultDACVerifier * _defaultDACVerifier; - MTRDeviceControllerDelegateBridge * _deviceControllerDelegateBridge; - MTRDeviceAttestationDelegateBridge * _deviceAttestationDelegateBridge; os_unfair_lock _underlyingDeviceMapLock; - MTRCommissionableBrowser * _commissionableBrowser; - MTRAttestationTrustStoreBridge * _attestationTrustStoreBridge; - - // _serverEndpoints is only touched on the Matter queue. - NSMutableArray * _serverEndpoints; - MTRDeviceStorageBehaviorConfiguration * _storageBehaviorConfiguration; std::atomic _storedFabricIndex; std::atomic> _storedCompressedFabricID; - MTRP256KeypairBridge _signingKeypairBridge; - MTRP256KeypairBridge _operationalKeypairBridge; // For now, we just ensure that access to _suspended is atomic, but don't // guarantee atomicity of the the entire suspend/resume operation. The From f0e3672f297b4477eef4bee6f04de14a503a1287 Mon Sep 17 00:00:00 2001 From: Jeff Tung <100387939+jtung-apple@users.noreply.github.com> Date: Thu, 31 Oct 2024 11:11:04 -0700 Subject: [PATCH 036/121] [Darwin] MTRDeviceController_XPC should fetch compressedFabricID (#36323) --- .../Framework/CHIP/MTRDeviceController_XPC.mm | 15 ++++++++++++--- .../CHIP/XPC Protocol/MTRXPCServerProtocol.h | 1 + 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm index 2fdbef529cf832..e9286a69034b60 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -47,6 +47,7 @@ @interface MTRDeviceController_XPC () NSString * const MTRDeviceControllerRegistrationControllerNodeIDKey = @"MTRDeviceControllerRegistrationControllerNodeID"; NSString * const MTRDeviceControllerRegistrationControllerIsRunningKey = @"MTRDeviceControllerRegistrationControllerIsRunning"; NSString * const MTRDeviceControllerRegistrationDeviceInternalStateKey = @"MTRDeviceControllerRegistrationDeviceInternalState"; +NSString * const MTRDeviceControllerRegistrationControllerCompressedFabricIDKey = @"MTRDeviceControllerRegistrationControllerCompressedFabricID"; // #define MTR_HAVE_MACH_SERVICE_NAME_CONSTRUCTOR @@ -95,6 +96,7 @@ - (void)removeDevice:(MTRDevice *)device #pragma mark - XPC @synthesize controllerNodeID = _controllerNodeID; +@synthesize compressedFabricID = _compressedFabricID; + (NSMutableSet *)_allowedClasses { @@ -450,9 +452,16 @@ - (oneway void)controller:(NSUUID *)controller controllerConfigurationUpdated:(N // } NSDictionary * controllerContext = MTR_SAFE_CAST(configuration[MTRDeviceControllerRegistrationControllerContextKey], NSDictionary); - NSNumber * controllerNodeID = MTR_SAFE_CAST(controllerContext[MTRDeviceControllerRegistrationControllerNodeIDKey], NSNumber); - if (controllerContext && controllerNodeID) { - _controllerNodeID = controllerContext[MTRDeviceControllerRegistrationControllerNodeIDKey]; + if (controllerContext) { + NSNumber * controllerNodeID = MTR_SAFE_CAST(controllerContext[MTRDeviceControllerRegistrationControllerNodeIDKey], NSNumber); + if (controllerNodeID) { + _controllerNodeID = controllerNodeID; + } + + NSNumber * compressedFabricID = MTR_SAFE_CAST(controllerContext[MTRDeviceControllerRegistrationControllerCompressedFabricIDKey], NSNumber); + if (compressedFabricID) { + _compressedFabricID = compressedFabricID; + } } NSArray * deviceInfoList = MTR_SAFE_CAST(configuration[MTRDeviceControllerRegistrationNodeIDsKey], NSArray); diff --git a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h index 8290078765f471..6daec1bb9d05bf 100644 --- a/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h +++ b/src/darwin/Framework/CHIP/XPC Protocol/MTRXPCServerProtocol.h @@ -24,6 +24,7 @@ MTR_EXTERN NSString * const MTRDeviceControllerRegistrationControllerContextKey MTR_EXTERN NSString * const MTRDeviceControllerRegistrationControllerNodeIDKey MTR_NEWLY_AVAILABLE; MTR_EXTERN NSString * const MTRDeviceControllerRegistrationControllerIsRunningKey MTR_NEWLY_AVAILABLE; MTR_EXTERN NSString * const MTRDeviceControllerRegistrationDeviceInternalStateKey MTR_NEWLY_AVAILABLE; +MTR_EXTERN NSString * const MTRDeviceControllerRegistrationControllerCompressedFabricIDKey MTR_NEWLY_AVAILABLE; MTR_AVAILABLE(ios(18.2), macos(15.2), watchos(11.2), tvos(18.2)) @protocol MTRXPCServerProtocol_MTRDevice From 7826146158502166dc8bac3d0a7497f9edd7a11c Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Thu, 31 Oct 2024 20:36:54 +0100 Subject: [PATCH 037/121] [darwin-framework-tool][interactive] Add Ctrl+G as a shortcut key to trigger a resubscription to the last used MTRDevice (#36325) --- .../commands/common/CHIPCommandBridge.h | 2 ++ .../commands/common/CHIPCommandBridge.mm | 7 ++++ .../configuration/SetUpDeviceCommand.h | 3 ++ .../interactive/InteractiveCommands.mm | 32 +++++++++++++++++++ 4 files changed, 44 insertions(+) diff --git a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h index a71f18ed301f9f..7f9f3f9b6efc2c 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h +++ b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.h @@ -130,6 +130,8 @@ class CHIPCommandBridge : public Command { void SuspendOrResumeCommissioners(); + MTRDevice * GetLastUsedDevice(); + private: CHIP_ERROR InitializeCommissioner( std::string key, chip::FabricId fabricId, const chip::Credentials::AttestationTrustStore * trustStore); diff --git a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm index 4a6e279d03fe66..69071d4c423776 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm +++ b/examples/darwin-framework-tool/commands/common/CHIPCommandBridge.mm @@ -35,6 +35,7 @@ #include static CHIPToolPersistentStorageDelegate * storage = nil; +static MTRDevice * sLastUsedDevice = nil; static DeviceDelegate * sDeviceDelegate = nil; static dispatch_queue_t sDeviceDelegateDispatchQueue = nil; std::set CHIPCommandBridge::sDeferredCleanups; @@ -312,6 +313,7 @@ } [device addDelegate:sDeviceDelegate queue:sDeviceDelegateDispatchQueue]; + sLastUsedDevice = device; return device; } @@ -368,6 +370,11 @@ } } +MTRDevice * CHIPCommandBridge::GetLastUsedDevice() +{ + return sLastUsedDevice; +} + CHIP_ERROR CHIPCommandBridge::StartWaiting(chip::System::Clock::Timeout duration) { auto waitingUntil = std::chrono::system_clock::now() + std::chrono::duration_cast(duration); diff --git a/examples/darwin-framework-tool/commands/configuration/SetUpDeviceCommand.h b/examples/darwin-framework-tool/commands/configuration/SetUpDeviceCommand.h index 8df842cf5769ae..14275b8c7b24b1 100644 --- a/examples/darwin-framework-tool/commands/configuration/SetUpDeviceCommand.h +++ b/examples/darwin-framework-tool/commands/configuration/SetUpDeviceCommand.h @@ -50,6 +50,9 @@ class SetUpDeviceCommand : public CHIPCommandBridge { __auto_type queue = dispatch_queue_create("com.chip.devicedelegate", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); [device addDelegate:delegate queue:queue]; + // Make sure the device is registered as the latest MTRDevice. + DeviceWithNodeId(mNodeId); + mDelegate = delegate; SetCommandExitStatus(CHIP_NO_ERROR); return CHIP_NO_ERROR; diff --git a/examples/darwin-framework-tool/commands/interactive/InteractiveCommands.mm b/examples/darwin-framework-tool/commands/interactive/InteractiveCommands.mm index b5bdcc9c2c531d..a4bfbc234cc831 100644 --- a/examples/darwin-framework-tool/commands/interactive/InteractiveCommands.mm +++ b/examples/darwin-framework-tool/commands/interactive/InteractiveCommands.mm @@ -32,6 +32,7 @@ "╠══════════════════════════════════════════════════════════════════╣\n" "║ Stop and restart stack : [Ctrl+_] & [Ctrl+^ ] ║\n" "║ Suspend/Resume controllers: [Ctrl+Z] ║\n" + "║ Trigger Resubscription : [Ctrl+G] ║\n" "║ Trigger exit(0) : [Ctrl+@] ║\n" "║ Quit Interactive : 'quit()' or `quit` ║\n" "╚══════════════════════════════════════════════════════════════════╝\n"; @@ -43,6 +44,10 @@ constexpr char kCategoryProgress[] = "Info"; constexpr char kCategoryDetail[] = "Debug"; +@interface MTRDevice () +- (void)_deviceMayBeReachable; +@end + namespace { class RestartCommand : public CHIPCommandBridge { @@ -93,6 +98,25 @@ CHIP_ERROR RunCommand() override chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::Seconds16(0); } }; +class TriggerResubscriptionCommand : public CHIPCommandBridge { +public: + TriggerResubscriptionCommand() + : CHIPCommandBridge("trigger-resubscription") + { + } + + CHIP_ERROR RunCommand() override + { + __auto_type * device = GetLastUsedDevice(); + if (nil != device) { + [device _deviceMayBeReachable]; + } + return CHIP_NO_ERROR; + } + + chip::System::Clock::Timeout GetWaitDuration() const override { return chip::System::Clock::Seconds16(0); } +}; + void ClearLine() { printf("\r\x1B[0J"); // Move cursor to the beginning of the line and clear from cursor to end of the screen @@ -336,6 +360,13 @@ el_status_t SuspendOrResumeFunction() return CSstay; } +el_status_t TriggerResubscriptionFunction() +{ + TriggerResubscriptionCommand cmd; + cmd.RunCommand(); + return CSstay; +} + el_status_t ExitFunction() { exit(0); @@ -358,6 +389,7 @@ el_status_t ExitFunction() el_bind_key(CTL('_'), StopFunction); el_bind_key(CTL('@'), ExitFunction); el_bind_key(CTL('Z'), SuspendOrResumeFunction); + el_bind_key(CTL('G'), TriggerResubscriptionFunction); char * command = nullptr; int status; From a7ee9d49f39697aa3e7dbfd1464bbf15dc48d306 Mon Sep 17 00:00:00 2001 From: Shao Ling Tan <161761051+shaoltan-amazon@users.noreply.github.com> Date: Thu, 31 Oct 2024 16:20:42 -0400 Subject: [PATCH 038/121] Fix and re-enable Linux TV commissioner-generated-passcode CI test (#36291) --- .../examples-linux-tv-casting-app.yaml | 17 ++-- scripts/tests/linux/log_line_processing.py | 84 +++++++++++-------- .../tests/linux/tv_casting_test_sequences.py | 9 +- 3 files changed, 61 insertions(+), 49 deletions(-) diff --git a/.github/workflows/examples-linux-tv-casting-app.yaml b/.github/workflows/examples-linux-tv-casting-app.yaml index e2617aeec7f42e..31275c78501f5c 100644 --- a/.github/workflows/examples-linux-tv-casting-app.yaml +++ b/.github/workflows/examples-linux-tv-casting-app.yaml @@ -72,16 +72,13 @@ jobs: "python3 ./scripts/tests/run_tv_casting_test.py" timeout-minutes: 2 # Comment this out to debug if GitHub Action times out. - # TODO: this test is flaky and was disabled - # https://github.com/project-chip/connectedhomeip/issues/34598 - # - # - name: - # Test casting from Linux tv-casting-app to Linux tv-app - - # Commissioner Generated Passcode - # run: | - # ./scripts/run_in_build_env.sh \ - # "python3 ./scripts/tests/run_tv_casting_test.py --commissioner-generated-passcode=True" - # timeout-minutes: 2 # Comment this out to debug if GitHub Action times out. + - name: + Test casting from Linux tv-casting-app to Linux tv-app - + Commissioner Generated Passcode + run: | + ./scripts/run_in_build_env.sh \ + "python3 ./scripts/tests/run_tv_casting_test.py --commissioner-generated-passcode=True" + timeout-minutes: 2 # Comment this out to debug if GitHub Action times out. - name: Uploading Size Reports uses: ./.github/actions/upload-size-reports diff --git a/scripts/tests/linux/log_line_processing.py b/scripts/tests/linux/log_line_processing.py index e7624c12d5f2f2..fa60db7b9193d7 100644 --- a/scripts/tests/linux/log_line_processing.py +++ b/scripts/tests/linux/log_line_processing.py @@ -14,7 +14,6 @@ import logging import queue -import select import subprocess import threading import time @@ -45,44 +44,47 @@ class ProcessOutputCapture: def __init__(self, command: List[str], output_path: str): # in/out/err are pipes self.command = command + self.output_file = None # Output file handle self.output_path = output_path self.output_lines = queue.Queue() self.process = None - self.io_thread = None + self.stdout_thread = None + self.stderr_thread = None + self.lock = threading.Lock() self.done = False - def _io_thread(self): - """Reads process lines and writes them to an output file. + def _write_to_file(self, line: str, is_error_line=False): + """Writes a line to an output file in a thread-safe manner.""" + with self.lock: + if is_error_line: + self.output_file.write(f"!!STDERR!! : {line}") + else: + self.output_file.write(line) + self.output_file.flush() + + def _stdout_thread(self): + """Reads stdout process lines and writes them to an output file. It also sends the output lines to `self.output_lines` for later - reading + reading. + """ + while not self.done: + out_line = self.process.stdout.readline() + if not out_line: + break + self._write_to_file(out_line) + self.output_lines.put(out_line) + + def _stderr_thread(self): + """Reads stderr process lines and writes them to an output file. + + The lines are marked as error lines when written to the file. """ - out_wait = select.poll() - out_wait.register(self.process.stdout, select.POLLIN | select.POLLHUP) - - err_wait = select.poll() - err_wait.register(self.process.stderr, select.POLLIN | select.POLLHUP) - - with open(self.output_path, "wt") as f: - f.write("PROCESS START: %s\n" % time.ctime()) - while not self.done: - changes = out_wait.poll(0.1) - if changes: - out_line = self.process.stdout.readline() - if not out_line: - # stdout closed (otherwise readline should have at least \n) - continue - f.write(out_line) - self.output_lines.put(out_line) - - changes = err_wait.poll(0) - if changes: - err_line = self.process.stderr.readline() - if not err_line: - # stderr closed (otherwise readline should have at least \n) - continue - f.write(f"!!STDERR!! : {err_line}") - f.write("PROCESS END: %s\n" % time.ctime()) + while not self.done: + err_line = self.process.stderr.readline() + if not err_line: + break + self._write_to_file(err_line, is_error_line=True) def __enter__(self): self.done = False @@ -92,9 +94,14 @@ def __enter__(self): stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + bufsize=1, # Enable line buffering for immediate output from subprocess ) - self.io_thread = threading.Thread(target=self._io_thread) - self.io_thread.start() + self.output_file = open(self.output_path, "wt", buffering=1) # Enable line buffering for immediate output + self._write_to_file(f"### PROCESS START: {time.ctime()} ###\n") + self.stdout_thread = threading.Thread(target=self._stdout_thread) + self.stderr_thread = threading.Thread(target=self._stderr_thread) + self.stdout_thread.start() + self.stderr_thread.start() return self def __exit__(self, exception_type, exception_value, traceback): @@ -103,8 +110,15 @@ def __exit__(self, exception_type, exception_value, traceback): self.process.terminate() self.process.wait() - if self.io_thread: - self.io_thread.join() + if self.stdout_thread: + self.stdout_thread.join() + + if self.stderr_thread: + self.stderr_thread.join() + + if self.output_file: + self._write_to_file(f"### PROCESS END: {time.ctime()} ###\n") + self.output_file.close() if exception_value: # When we fail because of an exception, report the entire log content diff --git a/scripts/tests/linux/tv_casting_test_sequences.py b/scripts/tests/linux/tv_casting_test_sequences.py index fe1b0ab17f3263..c4ca182f5583d2 100644 --- a/scripts/tests/linux/tv_casting_test_sequences.py +++ b/scripts/tests/linux/tv_casting_test_sequences.py @@ -235,15 +235,16 @@ # Validate that commissioning succeeded in the tv-app output. Step(app=App.TV_APP, output_msg=['------PROMPT USER: commissioning success']), + # TODO: Enable the following steps once we fix https://github.com/project-chip/connectedhomeip/issues/36289 # Validate that we are able to subscribe to the media playback cluster by reading the CurrentState value and that it matches {ATTRIBUTE_CURRENT_PLAYBACK_STATE}. - Step(app=App.TV_CASTING_APP, output_msg=[f'Read CurrentState value: {ATTRIBUTE_CURRENT_PLAYBACK_STATE}']), + # Step(app=App.TV_CASTING_APP, output_msg=[f'Read CurrentState value: {ATTRIBUTE_CURRENT_PLAYBACK_STATE}']), # Validate the LaunchURL in the tv-app output. - Step(app=App.TV_APP, - output_msg=['ContentLauncherManager::HandleLaunchUrl TEST CASE ContentURL=https://www.test.com/videoid DisplayString=Test video']), + # Step(app=App.TV_APP, + # output_msg=['ContentLauncherManager::HandleLaunchUrl TEST CASE ContentURL=https://www.test.com/videoid DisplayString=Test video']), # Validate the LaunchURL in the tv-casting-app output. - Step(app=App.TV_CASTING_APP, output_msg=['LaunchURL Success with response.data: exampleData']), + # Step(app=App.TV_CASTING_APP, output_msg=['LaunchURL Success with response.data: exampleData']), # Signal to stop the tv-casting-app as we finished validation. Step(app=App.TV_CASTING_APP, input_cmd=STOP_APP), From 6a31fc2297d5a831af7a99198f91f2e555785fb8 Mon Sep 17 00:00:00 2001 From: Ethan Zhou <73028112+ethanzhouyc@users.noreply.github.com> Date: Thu, 31 Oct 2024 16:27:04 -0400 Subject: [PATCH 039/121] remove MinLevel from requireAttribute (#36326) --- .../zap-templates/zcl/data-model/chip/matter-devices.xml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml b/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml index bdccfbe39e1582..8e1feb4fb30c55 100644 --- a/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml +++ b/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml @@ -293,7 +293,6 @@ limitations under the License. CURRENT_LEVEL OPTIONS LEVEL_CONTROL_REMAINING_TIME - MINIMUM_LEVEL ON_LEVEL START_UP_CURRENT_LEVEL MoveToLevel @@ -394,7 +393,6 @@ limitations under the License. CURRENT_LEVEL OPTIONS LEVEL_CONTROL_REMAINING_TIME - MINIMUM_LEVEL ON_LEVEL START_UP_CURRENT_LEVEL MoveToLevel @@ -492,7 +490,6 @@ limitations under the License. CURRENT_LEVEL OPTIONS LEVEL_CONTROL_REMAINING_TIME - MINIMUM_LEVEL ON_LEVEL START_UP_CURRENT_LEVEL MoveToLevel @@ -609,7 +606,6 @@ limitations under the License. CURRENT_LEVEL OPTIONS LEVEL_CONTROL_REMAINING_TIME - MINIMUM_LEVEL ON_LEVEL START_UP_CURRENT_LEVEL MoveToLevel @@ -742,7 +738,6 @@ limitations under the License. CURRENT_LEVEL OPTIONS LEVEL_CONTROL_REMAINING_TIME - MINIMUM_LEVEL ON_LEVEL START_UP_CURRENT_LEVEL MoveToLevel @@ -836,7 +831,6 @@ limitations under the License. CURRENT_LEVEL OPTIONS LEVEL_CONTROL_REMAINING_TIME - MINIMUM_LEVEL ON_LEVEL START_UP_CURRENT_LEVEL MoveToLevel From bc83fc2a7794c568e1ae9daf00f9e429ef3fba84 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 31 Oct 2024 16:29:20 -0400 Subject: [PATCH 040/121] Move fabricIndex property to MTRDeviceController_Concrete. (#36324) This doesn't really make sense for non-concrete controllers. Also removes some unnecessary declarations and includes from MTRDeviceController_Internal. --- .../Framework/CHIP/MTRDeviceController.mm | 6 ------ .../CHIP/MTRDeviceController_Concrete.h | 5 +++++ .../CHIP/MTRDeviceController_Internal.h | 19 ------------------- .../Framework/CHIP/MTRDeviceController_XPC.mm | 1 + .../CHIP/MTROTAProviderDelegateBridge.h | 4 +++- .../CHIP/MTROTAProviderDelegateBridge.mm | 4 ++-- .../CHIP/MTRSessionResumptionStorageBridge.mm | 3 ++- 7 files changed, 13 insertions(+), 29 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index 102e4801bbfd12..1085595a3ebd19 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -94,7 +94,6 @@ - (instancetype)initWithDelegate:(id)delegate queue @implementation MTRDeviceController { os_unfair_lock _underlyingDeviceMapLock; - std::atomic _storedFabricIndex; std::atomic> _storedCompressedFabricID; // For now, we just ensure that access to _suspended is atomic, but don't @@ -503,11 +502,6 @@ - (void)asyncDispatchToMatterQueue:(dispatch_block_t)block errorHandler:(nullabl errorHandler([MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]); } -- (chip::FabricIndex)fabricIndex -{ - return _storedFabricIndex; -} - - (nullable NSNumber *)compressedFabricID { auto storedValue = _storedCompressedFabricID.load(); diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h index 80f5b222bd5cd8..6e6e504d475295 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h @@ -221,6 +221,11 @@ NS_ASSUME_NONNULL_BEGIN queue:(dispatch_queue_t)queue completion:(void (^)(NSURL * _Nullable url, NSError * _Nullable error))completion; +/** + * Will return chip::kUndefinedFabricIndex if we do not have a fabric index. + */ +@property (readonly) chip::FabricIndex fabricIndex; + @end NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h index 585b292b5a369d..102eaa4af916db 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h @@ -25,9 +25,6 @@ #import "MTRDeviceConnectionBridge.h" // For MTRInternalDeviceConnectionCallback #import "MTRDeviceController.h" -#include -#include - #import #import "MTRBaseDevice.h" @@ -37,11 +34,8 @@ #import "MTRDeviceControllerDelegate.h" #import "MTRDeviceStorageBehaviorConfiguration.h" -#import - #import #import -#import #import @class MTRDeviceControllerParameters; @@ -52,14 +46,6 @@ @protocol MTRDeviceControllerDelegate; @class MTRDevice_Concrete; -namespace chip { -class FabricTable; - -namespace Controller { - class DeviceCommissioner; -} -} // namespace chip - NS_ASSUME_NONNULL_BEGIN @interface MTRDeviceController () @@ -74,11 +60,6 @@ NS_ASSUME_NONNULL_BEGIN #pragma mark - MTRDeviceControllerFactory methods -/** - * Will return chip::kUndefinedFabricIndex if we do not have a fabric index. - */ -@property (readonly) chip::FabricIndex fabricIndex; - /** * Will return the compressed fabric id of the fabric if the controller is * running, else nil. diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm index e9286a69034b60..53a04b1e206b98 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -20,6 +20,7 @@ #import "MTRDeviceController_Internal.h" #import "MTRDevice_XPC.h" #import "MTRDevice_XPC_Internal.h" +#import "MTRError_Internal.h" #import "MTRLogging_Internal.h" #import "MTRXPCClientProtocol.h" #import "MTRXPCServerProtocol.h" diff --git a/src/darwin/Framework/CHIP/MTROTAProviderDelegateBridge.h b/src/darwin/Framework/CHIP/MTROTAProviderDelegateBridge.h index f74fb32a08bd19..3d70954bb97200 100644 --- a/src/darwin/Framework/CHIP/MTROTAProviderDelegateBridge.h +++ b/src/darwin/Framework/CHIP/MTROTAProviderDelegateBridge.h @@ -17,6 +17,8 @@ #import +#import "MTRDeviceController_Concrete.h" + #include NS_ASSUME_NONNULL_BEGIN @@ -35,7 +37,7 @@ class MTROTAProviderDelegateBridge : public chip::app::Clusters::OTAProviderDele // ControllerShuttingDown must be called on the Matter work queue, since it // touches Matter objects. - void ControllerShuttingDown(MTRDeviceController * controller); + void ControllerShuttingDown(MTRDeviceController_Concrete * controller); void HandleQueryImage( chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, diff --git a/src/darwin/Framework/CHIP/MTROTAProviderDelegateBridge.mm b/src/darwin/Framework/CHIP/MTROTAProviderDelegateBridge.mm index e191b15acc6cf0..8729ac2a0f0a55 100644 --- a/src/darwin/Framework/CHIP/MTROTAProviderDelegateBridge.mm +++ b/src/darwin/Framework/CHIP/MTROTAProviderDelegateBridge.mm @@ -112,7 +112,7 @@ CHIP_ERROR Shutdown() return CHIP_NO_ERROR; } - void ControllerShuttingDown(MTRDeviceController * controller) + void ControllerShuttingDown(MTRDeviceController_Concrete * controller) { assertChipStackLockedByCurrentThread(); @@ -506,7 +506,7 @@ CHIP_ERROR ConfigureState(chip::FabricIndex fabricIndex, chip::NodeId nodeId) void MTROTAProviderDelegateBridge::Shutdown() { gOtaSender->Shutdown(); } -void MTROTAProviderDelegateBridge::ControllerShuttingDown(MTRDeviceController * controller) +void MTROTAProviderDelegateBridge::ControllerShuttingDown(MTRDeviceController_Concrete * controller) { gOtaSender->ControllerShuttingDown(controller); } diff --git a/src/darwin/Framework/CHIP/MTRSessionResumptionStorageBridge.mm b/src/darwin/Framework/CHIP/MTRSessionResumptionStorageBridge.mm index 65e8eac55ed830..e79e565e14ec0f 100644 --- a/src/darwin/Framework/CHIP/MTRSessionResumptionStorageBridge.mm +++ b/src/darwin/Framework/CHIP/MTRSessionResumptionStorageBridge.mm @@ -18,6 +18,7 @@ #import "MTRConversion.h" #import "MTRDeviceControllerFactory_Internal.h" +#import "MTRDeviceController_Concrete.h" #import "MTRDeviceController_Internal.h" #import "MTRLogging_Internal.h" #import "NSDataSpanConversion.h" @@ -58,7 +59,7 @@ auto * resumptionIDData = AsData(resumptionId); auto * controllerList = [mFactory getRunningControllers]; - for (MTRDeviceController * controller in controllerList) { + for (MTRDeviceController_Concrete * controller in controllerList) { FabricIndex fabricIndex = controller.fabricIndex; if (!IsValidFabricIndex(fabricIndex)) { // This controller is not sufficiently "running"; it does not have a From d93f3f6077f34e19665a25b2b93d7e08a0468986 Mon Sep 17 00:00:00 2001 From: Amine Alami <43780877+Alami-Amine@users.noreply.github.com> Date: Thu, 31 Oct 2024 21:53:20 +0100 Subject: [PATCH 041/121] Improve formatting of Error Logs related to CHIP_ERROR in GoogleTest (#36265) * Improve formatting of errors related to CHIP_ERROR in GoogleTest * Improve formatting of errors related to CHIP_ERROR in GoogleTest * Add a buildconfig header for GoogleTest * Activating CHIP_ERROR log formatter for pw_fuzzer fuzztests * Restyled by clang-format --------- Co-authored-by: Restyled.io --- build/chip/tests.gni | 4 ++++ build/toolchain/pw_fuzzer/BUILD.gn | 3 +++ scripts/build/builders/host.py | 1 + src/lib/core/BUILD.gn | 2 ++ src/lib/core/CHIPConfig.h | 11 +++++++++++ src/lib/core/StringBuilderAdapters.cpp | 15 +++++++++++++++ src/lib/core/StringBuilderAdapters.h | 20 ++++++++++++++++++++ 7 files changed, 56 insertions(+) diff --git a/build/chip/tests.gni b/build/chip/tests.gni index 0c2c742d646a15..57d0311694f9be 100755 --- a/build/chip/tests.gni +++ b/build/chip/tests.gni @@ -26,6 +26,10 @@ declare_args() { declare_args() { # Enable building tests. chip_build_tests = current_os != "freertos" + + # Enabling useful support functions when building using GoogleTest framework (used in unit tests and pw_fuzzer FuzzTests) + # For unit tests: this should only be enabled through build_examples.py, see PR #36268 + chip_build_tests_googletest = false } declare_args() { diff --git a/build/toolchain/pw_fuzzer/BUILD.gn b/build/toolchain/pw_fuzzer/BUILD.gn index 468a615448312a..b5a751bc98a903 100644 --- a/build/toolchain/pw_fuzzer/BUILD.gn +++ b/build/toolchain/pw_fuzzer/BUILD.gn @@ -64,6 +64,9 @@ gcc_toolchain("chip_pw_fuzztest") { dir_pw_third_party_fuzztest = "//third_party/fuzztest" dir_pw_third_party_googletest = "$dir_googletest" + # Since pw_fuzzer uses GoogleTest, activating this allows us to benefit from supporting functions + chip_build_tests_googletest = true + # TODO: Seems that re2 support within FuzzTest was deprecated, keeping it defined is triggering warning # Remove if re2 is indeed not needed # dir_pw_third_party_re2 = "//third_party/re2/src" diff --git a/scripts/build/builders/host.py b/scripts/build/builders/host.py index 114f47f971f1df..dbb85f99e87d16 100644 --- a/scripts/build/builders/host.py +++ b/scripts/build/builders/host.py @@ -502,6 +502,7 @@ def __init__(self, root, runner, app: HostApp, board=HostBoard.NATIVE, self.extra_gn_options.append('import("//build_overrides/googletest.gni")') self.extra_gn_options.append('pw_unit_test_BACKEND="$dir_pw_unit_test:googletest"') self.extra_gn_options.append('dir_pw_third_party_googletest="$dir_googletest"') + self.extra_gn_options.append('chip_build_tests_googletest=true') def GnBuildArgs(self): if self.board == HostBoard.NATIVE: diff --git a/src/lib/core/BUILD.gn b/src/lib/core/BUILD.gn index 70680640b025b2..5a6e6e114e4aae 100644 --- a/src/lib/core/BUILD.gn +++ b/src/lib/core/BUILD.gn @@ -71,6 +71,7 @@ buildconfig_header("chip_buildconfig") { "CHIP_CONFIG_TLV_VALIDATE_CHAR_STRING_ON_WRITE=${chip_tlv_validate_char_string_on_write}", "CHIP_CONFIG_TLV_VALIDATE_CHAR_STRING_ON_READ=${chip_tlv_validate_char_string_on_read}", "CHIP_CONFIG_COMMAND_SENDER_BUILTIN_SUPPORT_FOR_BATCHED_COMMANDS=${chip_enable_sending_batch_commands}", + "CHIP_CONFIG_TEST_GOOGLETEST=${chip_build_tests_googletest}", ] visibility = [ ":chip_config_header" ] @@ -116,6 +117,7 @@ source_set("string-builder-adapters") { public_deps = [ ":error", "$dir_pw_string", + "$dir_pw_unit_test", ] } diff --git a/src/lib/core/CHIPConfig.h b/src/lib/core/CHIPConfig.h index 382c63497da51d..fca3472826a310 100644 --- a/src/lib/core/CHIPConfig.h +++ b/src/lib/core/CHIPConfig.h @@ -1845,6 +1845,17 @@ extern const char CHIP_NON_PRODUCTION_MARKER[]; #define CHIP_CONFIG_MAX_BDX_LOG_TRANSFERS 5 #endif // CHIP_CONFIG_MAX_BDX_LOG_TRANSFERS +/** + * @def CHIP_CONFIG_TEST_GOOGLETEST + * + * @brief + * If asserted (1), enable APIs that support unit tests built with the GoogleTest framework + * + */ +#ifndef CHIP_CONFIG_TEST_GOOGLETEST +#define CHIP_CONFIG_TEST_GOOGLETEST 0 +#endif // CHIP_CONFIG_TEST_GOOGLETEST + /** * @} */ diff --git a/src/lib/core/StringBuilderAdapters.cpp b/src/lib/core/StringBuilderAdapters.cpp index d072c1ee905ab7..be07ae92cf7923 100644 --- a/src/lib/core/StringBuilderAdapters.cpp +++ b/src/lib/core/StringBuilderAdapters.cpp @@ -29,3 +29,18 @@ StatusWithSize ToString(const CHIP_ERROR & err, pw::span buffe } } // namespace pw + +#if CHIP_CONFIG_TEST_GOOGLETEST +namespace chip { + +void PrintTo(const CHIP_ERROR & err, std::ostream * os) +{ + if (CHIP_ERROR::IsSuccess(err)) + { + *os << "CHIP_NO_ERROR"; + return; + } + *os << "CHIP_ERROR:<" << err.Format() << ">"; +} +} // namespace chip +#endif // CHIP_CONFIG_TEST_GOOGLETEST diff --git a/src/lib/core/StringBuilderAdapters.h b/src/lib/core/StringBuilderAdapters.h index f173d56b46e6a1..ad3bfb71e2299a 100644 --- a/src/lib/core/StringBuilderAdapters.h +++ b/src/lib/core/StringBuilderAdapters.h @@ -42,6 +42,7 @@ /// Actual: CHIP_ERROR: == CHIP_NO_ERROR #include +#include #include @@ -51,3 +52,22 @@ template <> StatusWithSize ToString(const CHIP_ERROR & err, pw::span buffer); } // namespace pw +#if CHIP_CONFIG_TEST_GOOGLETEST + +namespace chip { + +/// The following function is for usage with GoogleTest. +/// This implementation of PrintTo allows GoogleTest to print CHIP_ERROR for better logs in the event of a failure. +/// Example output with PrintTo(): +/// +/// src/lib/core/tests/TestTLV.cpp:382: Failure +/// Expected equality of these values: +/// err +/// Which is: CHIP_ERROR: +/// CHIP_ERROR(0, "src/lib/core/tests/TestTLV.cpp", 382) +/// Which is: CHIP_NO_ERROR +/// +/// This enhances the readability and diagnostic information in GoogleTest test logs. +void PrintTo(const CHIP_ERROR & err, std::ostream * os); +} // namespace chip +#endif // CHIP_CONFIG_TEST_GOOGLETEST From e5ae0650624dc512ec945a589d39408369eb446c Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 31 Oct 2024 19:19:20 -0400 Subject: [PATCH 042/121] Move concurrentSubscriptionPool property to MTRDeviceController_Concrete. (#36328) The non-concrete case does not directly create subscriptions, so has no need of a pool for them. --- src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h | 7 +++++++ src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm | 2 -- src/darwin/Framework/CHIP/MTRDeviceController_Internal.h | 7 ------- src/darwin/Framework/CHIP/MTRDevice_Concrete.mm | 2 +- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h index 6e6e504d475295..0f2b113af248aa 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h @@ -26,6 +26,7 @@ #import #import +#import "MTRAsyncWorkQueue.h" #import "MTRDeviceConnectionBridge.h" #import "MTRDeviceControllerStartupParams_Internal.h" @@ -226,6 +227,12 @@ NS_ASSUME_NONNULL_BEGIN */ @property (readonly) chip::FabricIndex fabricIndex; +/** + * A queue with a fixed width that allows a number of MTRDevice objects to perform + * subscription at the same time. + */ +@property (nonatomic, readonly) MTRAsyncWorkQueue * concurrentSubscriptionPool; + @end NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm index 1a164e50b14b5c..4dfffcbb8907b3 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.mm @@ -106,8 +106,6 @@ @interface MTRDeviceController_Concrete () @property (nonatomic, readonly, nullable) MTRAttestationTrustStoreBridge * attestationTrustStoreBridge; @property (nonatomic, readonly, nullable) NSMutableArray * serverEndpoints; -@property (nonatomic, readonly) MTRAsyncWorkQueue * concurrentSubscriptionPool; - @property (nonatomic, readonly) MTRDeviceStorageBehaviorConfiguration * storageBehaviorConfiguration; // Whether we should be advertising our operational identity when we are not suspended. diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h index 102eaa4af916db..6a8539d980c1f3 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h @@ -41,7 +41,6 @@ @class MTRDeviceControllerParameters; @class MTRDeviceControllerFactory; @class MTRDevice; -@class MTRAsyncWorkQueue; @protocol MTRDevicePairingDelegate; @protocol MTRDeviceControllerDelegate; @class MTRDevice_Concrete; @@ -78,12 +77,6 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic, readonly, nullable) id otaProviderDelegate; @property (nonatomic, readonly, nullable) dispatch_queue_t otaProviderDelegateQueue; -/** - * A queue with a fixed width that allows a number of MTRDevice objects to perform - * subscription at the same time. - */ -@property (nonatomic, readonly) MTRAsyncWorkQueue * concurrentSubscriptionPool; - /** * Fabric ID tied to controller */ diff --git a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm index 61e8ab68ea89f8..a613240fd76fa3 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm @@ -1245,7 +1245,7 @@ - (void)_scheduleSubscriptionPoolWork:(dispatch_block_t)workBlock inNanoseconds: workBlock(); }]; - [self->_deviceController.concurrentSubscriptionPool enqueueWorkItem:workItem description:description]; + [[[self _concreteController] concurrentSubscriptionPool] enqueueWorkItem:workItem description:description]; MTR_LOG("%@ - enqueued in the subscription pool", self); }; From 4efe777c7e7696210c119d28f33351e45034280f Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 31 Oct 2024 19:43:03 -0400 Subject: [PATCH 043/121] Enforce `DataModel::Provider` everywhere (#36319) * Pass 1: remove a large set of ifdefs * More flags removes * Remove more flags * More flags removes * Clean up a few more builders * Clean up references from ember compatibility functions and make the data model implementation of reporting and attribute path expand iterator be the only implemented versions * Remove ServerClusterCommandExists * Remove ConcreteAttributePathExists * Remove ReadSingleClusterData * Remove GetAttributeMetadata * Even more cleanup * Remove invalid include * Update target test file: we removed all DM enable/disable * Add back endif * Cleanup targets for building * Cleanup unused target * one more unused function removal * Fix up one condition * Restyled by clang-format * Update src/app/AttributePathExpandIterator.h Co-authored-by: Boris Zbarsky * Update src/app/AttributePathExpandIterator.h Co-authored-by: Boris Zbarsky * Update src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm Co-authored-by: Boris Zbarsky * Add back missed code * Restyled by clang-format * Update src/app/tests/BUILD.gn Co-authored-by: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> --------- Co-authored-by: Andrei Litvin Co-authored-by: Restyled.io Co-authored-by: Boris Zbarsky Co-authored-by: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> --- .github/workflows/build.yaml | 12 +- .github/workflows/examples-linux-arm.yaml | 2 +- .github/workflows/lint.yml | 3 - .github/workflows/tests.yaml | 6 +- .github/workflows/unit_integration_test.yaml | 2 +- build/chip/esp32/esp32_codegen.cmake | 10 +- config/common/cmake/chip_gn_args.cmake | 5 - config/esp32/components/chip/CMakeLists.txt | 8 - config/mbed/CMakeLists.txt | 4 - config/nrfconnect/chip-module/CMakeLists.txt | 8 - config/nxp/chip-cmake-freertos/CMakeLists.txt | 7 - config/nxp/chip-module/CMakeLists.txt | 8 - config/telink/chip-module/CMakeLists.txt | 7 - config/zephyr/Kconfig | 8 - config/zephyr/chip-module/CMakeLists.txt | 7 - .../common/pigweed/rpc_services/Attributes.h | 17 +- scripts/build/build/targets.py | 20 +- scripts/build/builders/esp32.py | 5 - scripts/build/builders/host.py | 11 - scripts/build/builders/mbed.py | 5 - scripts/build/builders/nrf.py | 6 - scripts/build/builders/nxp.py | 10 - scripts/build/builders/qpg.py | 4 - scripts/build/builders/telink.py | 6 - .../build/testdata/all_targets_linux_x64.txt | 14 +- scripts/tests/local.py | 9 +- .../AttributePathExpandIterator-Checked.cpp | 99 --- src/app/AttributePathExpandIterator-Checked.h | 44 - .../AttributePathExpandIterator-DataModel.h | 128 --- src/app/AttributePathExpandIterator-Ember.cpp | 261 ------ src/app/AttributePathExpandIterator-Ember.h | 136 --- ...el.cpp => AttributePathExpandIterator.cpp} | 23 +- src/app/AttributePathExpandIterator.h | 123 ++- src/app/AttributeValueEncoder.h | 3 +- src/app/BUILD.gn | 76 +- src/app/CommandHandlerImpl.cpp | 19 - src/app/InteractionModelEngine.cpp | 146 +--- src/app/WriteHandler.cpp | 21 - src/app/WriteHandler.h | 2 - src/app/chip_data_model.cmake | 13 +- src/app/chip_data_model.gni | 5 - .../microwave-oven-control-server.cpp | 5 - .../pump-configuration-and-control-server.cpp | 1 - .../InteractionModelTemporaryOverrides.cpp | 61 -- src/app/common_flags.gni | 16 - src/app/dynamic_server/AccessControl.cpp | 16 +- src/app/dynamic_server/DynamicDispatcher.cpp | 135 +-- src/app/reporting/Engine.cpp | 10 +- src/app/reporting/Read-Checked.cpp | 184 ---- src/app/reporting/Read-Checked.h | 41 - src/app/reporting/Read-DataModel.h | 42 - src/app/reporting/Read-Ember.cpp | 62 -- src/app/reporting/Read-Ember.h | 43 - .../{Read-DataModel.cpp => Read.cpp} | 11 +- src/app/reporting/Read.h | 34 +- src/app/server/Server.cpp | 20 - src/app/tests/BUILD.gn | 2 +- src/app/tests/TestCommandInteraction.cpp | 2 +- .../tests/integration/chip_im_initiator.cpp | 67 -- .../tests/integration/chip_im_responder.cpp | 76 +- src/app/tests/test-interaction-model-api.cpp | 69 +- src/app/tests/test-interaction-model-api.h | 14 - .../util/ember-compatibility-functions.cpp | 814 ------------------ src/app/util/ember-compatibility-functions.h | 94 -- .../tests/data_model/DataModelFixtures.cpp | 207 +---- .../ServerEndpoint/MTRServerAccessControl.mm | 10 +- .../Matter.xcodeproj/project.pbxproj | 6 - 67 files changed, 197 insertions(+), 3148 deletions(-) delete mode 100644 src/app/AttributePathExpandIterator-Checked.cpp delete mode 100644 src/app/AttributePathExpandIterator-Checked.h delete mode 100644 src/app/AttributePathExpandIterator-DataModel.h delete mode 100644 src/app/AttributePathExpandIterator-Ember.cpp delete mode 100644 src/app/AttributePathExpandIterator-Ember.h rename src/app/{AttributePathExpandIterator-DataModel.cpp => AttributePathExpandIterator.cpp} (91%) delete mode 100644 src/app/reporting/Read-Checked.cpp delete mode 100644 src/app/reporting/Read-Checked.h delete mode 100644 src/app/reporting/Read-DataModel.h delete mode 100644 src/app/reporting/Read-Ember.cpp delete mode 100644 src/app/reporting/Read-Ember.h rename src/app/reporting/{Read-DataModel.cpp => Read.cpp} (93%) delete mode 100644 src/app/util/ember-compatibility-functions.cpp delete mode 100644 src/app/util/ember-compatibility-functions.h diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index af102bf96ea5b8..210106ccc08e0c 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -76,7 +76,7 @@ jobs: with: languages: "cpp" - name: Setup Build - run: scripts/build/gn_gen.sh --args="chip_config_memory_debug_checks=true chip_config_memory_debug_dmalloc=false chip_data_model_check_die_on_failure=true" + run: scripts/build/gn_gen.sh --args="chip_config_memory_debug_checks=true chip_config_memory_debug_dmalloc=false" - name: Run Build run: scripts/run_in_build_env.sh "ninja -C ./out" - name: Run Tests @@ -183,7 +183,7 @@ jobs: scripts/run_in_build_env.sh "ninja -C ./out/$BUILD_TYPE" - name: Setup Build, Run Build and Run Tests run: | - BUILD_TYPE=gcc_release scripts/build/gn_gen.sh --args="is_debug=false chip_data_model_check_die_on_failure=true" + BUILD_TYPE=gcc_release scripts/build/gn_gen.sh --args="is_debug=false" scripts/run_in_build_env.sh "ninja -C ./out/gcc_release" BUILD_TYPE=gcc_release scripts/tests/gn_tests.sh - name: Clean output @@ -205,14 +205,14 @@ jobs: esac rm -rf ./out/sanitizers - BUILD_TYPE=sanitizers scripts/build/gn_gen.sh --args="$GN_ARGS chip_data_model_check_die_on_failure=true" --export-compile-commands + BUILD_TYPE=sanitizers scripts/build/gn_gen.sh --args="$GN_ARGS" --export-compile-commands BUILD_TYPE=sanitizers scripts/tests/gn_tests.sh done - name: Generate tests with sanitizers (for tidy) if: github.event.pull_request.number != null run: | rm -rf ./out/sanitizers - BUILD_TYPE=sanitizers scripts/build/gn_gen.sh --args="is_clang=true is_asan=true chip_data_model_check_die_on_failure=true" --export-compile-commands + BUILD_TYPE=sanitizers scripts/build/gn_gen.sh --args="is_clang=true is_asan=true" --export-compile-commands - name: Ensure codegen is done for sanitize run: | ./scripts/run_in_build_env.sh "./scripts/run_codegen_targets.sh out/sanitizers" @@ -333,7 +333,7 @@ jobs: - name: Setup Build, Run Build and Run Tests run: | - scripts/build/gn_gen.sh --args="enable_rtti=true chip_config_memory_debug_checks=false chip_config_memory_debug_dmalloc=false chip_generate_link_map_file=false chip_data_model_check_die_on_failure=true" + scripts/build/gn_gen.sh --args="enable_rtti=true chip_config_memory_debug_checks=false chip_config_memory_debug_dmalloc=false chip_generate_link_map_file=false" scripts/run_in_build_env.sh "ninja -C ./out" scripts/tests/gn_tests.sh - name: Setup test python environment @@ -439,7 +439,7 @@ jobs: # We want to build various standalone example apps (similar to what examples-linux-standalone.yaml # does), so use target_os="all" to get those picked up as part of the "unified" build. But then # to save CI resources we want to exclude the "host clang" build, which uses the pigweed clang. - scripts/build/gn_gen.sh --args='target_os="all" is_asan=true enable_host_clang_build=false chip_data_model_check_die_on_failure=true' --export-compile-commands + scripts/build/gn_gen.sh --args='target_os="all" is_asan=true enable_host_clang_build=false' --export-compile-commands scripts/run_in_build_env.sh "ninja -C ./out/$BUILD_TYPE" scripts/tests/gn_tests.sh - name: Ensure codegen is done for default diff --git a/.github/workflows/examples-linux-arm.yaml b/.github/workflows/examples-linux-arm.yaml index 78a1c8dea80809..5aeeb4d5494c4d 100644 --- a/.github/workflows/examples-linux-arm.yaml +++ b/.github/workflows/examples-linux-arm.yaml @@ -65,7 +65,7 @@ jobs: --target linux-arm64-chip-tool-nodeps-ipv6only \ --target linux-arm64-lock-clang \ --target linux-arm64-minmdns-clang \ - --target linux-arm64-light-data-model-enabled-rpc-ipv6only-clang \ + --target linux-arm64-light-rpc-ipv6only-clang \ --target linux-arm64-thermostat-no-ble-clang \ --target linux-arm64-lit-icd-no-ble-clang \ --target linux-arm64-fabric-admin-clang-rpc \ diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 68bf4b0310bffb..2471529f4170fb 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -114,8 +114,6 @@ jobs: --known-failure app/util/config.h \ --known-failure app/util/DataModelHandler.cpp \ --known-failure app/util/DataModelHandler.h \ - --known-failure app/util/ember-compatibility-functions.cpp \ - --known-failure app/util/ember-compatibility-functions.h \ --known-failure app/util/ember-global-attribute-access-interface.h \ --known-failure app/util/ember-io-storage.h \ --known-failure app/util/endpoint-config-api.h \ @@ -299,7 +297,6 @@ jobs: ':(exclude)src/app/dynamic_server/DynamicDispatcher.cpp' \ ':(exclude)src/app/util/attribute-table.cpp' \ ':(exclude)src/app/util/attribute-table.h' \ - ':(exclude)src/app/util/ember-compatibility-functions.cpp' \ ':(exclude)src/app/util/mock/CodegenEmberMocks.cpp' \ ':(exclude)src/app/zap-templates/templates/app/attributes/Accessors-src.zapt' \ ':(exclude)src/darwin/Framework/CHIP/ServerEndpoint/MTRIMDispatch.mm' \ diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 63957b64d8f00d..77c31b8be7212e 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -487,7 +487,7 @@ jobs: scripts/run_in_build_env.sh './scripts/build_python.sh --install_virtual_env out/venv' ./scripts/run_in_build_env.sh \ "./scripts/build/build_examples.py \ - --target linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test-data-model-check-check-failure-die \ + --target linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test \ --target linux-x64-lock-ipv6only-no-ble-no-wifi-tsan-clang-test \ --target linux-x64-lit-icd-ipv6only-no-ble-no-wifi-tsan-clang-test \ --target linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test \ @@ -504,7 +504,7 @@ jobs: - name: Generate an argument environment file run: | echo -n "" >/tmp/test_env.yaml - echo "ALL_CLUSTERS_APP: out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test-data-model-check-check-failure-die/chip-all-clusters-app" >> /tmp/test_env.yaml + echo "ALL_CLUSTERS_APP: out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app" >> /tmp/test_env.yaml echo "CHIP_LOCK_APP: out/linux-x64-lock-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-lock-app" >> /tmp/test_env.yaml echo "ENERGY_MANAGEMENT_APP: out/linux-x64-energy-management-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-energy-management-app" >> /tmp/test_env.yaml echo "LIT_ICD_APP: out/linux-x64-lit-icd-ipv6only-no-ble-no-wifi-tsan-clang-test/lit-icd-app" >> /tmp/test_env.yaml @@ -523,7 +523,7 @@ jobs: mkdir -p out/trace_data scripts/run_in_python_env.sh out/venv './scripts/tests/run_python_test.py --load-from-env /tmp/test_env.yaml --script src/controller/python/test/test_scripts/mobile-device-test.py' scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/execute_python_tests.py --env-file /tmp/test_env.yaml --search-directory src/python_testing' - scripts/run_in_python_env.sh out/venv './scripts/tests/TestTimeSyncTrustedTimeSourceRunner.py --all-clusters out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test-data-model-check-check-failure-die/chip-all-clusters-app' + scripts/run_in_python_env.sh out/venv './scripts/tests/TestTimeSyncTrustedTimeSourceRunner.py --all-clusters out/linux-x64-all-clusters-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-all-clusters-app' scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/TestIdChecks.py' scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/TestSpecParsingDeviceType.py' scripts/run_in_python_env.sh out/venv 'python3 ./src/python_testing/TestConformanceSupport.py' diff --git a/.github/workflows/unit_integration_test.yaml b/.github/workflows/unit_integration_test.yaml index b51dfaa8fc2fde..1cc021375d7b1c 100644 --- a/.github/workflows/unit_integration_test.yaml +++ b/.github/workflows/unit_integration_test.yaml @@ -74,7 +74,7 @@ jobs: *) ;; esac - scripts/build/gn_gen.sh --args="$GN_ARGS chip_data_model_check_die_on_failure=true" + scripts/build/gn_gen.sh --args="$GN_ARGS" - name: Run Build run: scripts/run_in_build_env.sh "ninja -C out/$BUILD_TYPE" - name: Run Tests diff --git a/build/chip/esp32/esp32_codegen.cmake b/build/chip/esp32/esp32_codegen.cmake index 9148912d568652..9cbd839f10d0c3 100644 --- a/build/chip/esp32/esp32_codegen.cmake +++ b/build/chip/esp32/esp32_codegen.cmake @@ -71,15 +71,7 @@ macro(chip_app_component_zapgen ZAP_NAME) add_dependencies(${COMPONENT_LIB} app-zapgen) target_include_directories(${COMPONENT_LIB} PUBLIC "${APP_TEMPLATE_GEN_DIR}") - target_sources(${COMPONENT_LIB} PRIVATE ${APP_TEMPLATE_GEN_FILES}) - - # When data model interface is used, provide a default code-generation data model as - # part of zapgen. See `chip_data_model.cmake` for similar logic - set(CHIP_DATA_MODEL_INTERFACE "enabled" CACHE STRING "Data model interface option to use: enabled or disabled") - - if ("${CHIP_DATA_MODEL_INTERFACE}" STREQUAL "enabled") - target_sources(${COMPONENT_LIB} PRIVATE ${CODEGEN_DATA_MODEL_SOURCES}) - endif() + target_sources(${COMPONENT_LIB} PRIVATE ${APP_TEMPLATE_GEN_FILES} ${CODEGEN_DATA_MODEL_SOURCES}) endif() endmacro() diff --git a/config/common/cmake/chip_gn_args.cmake b/config/common/cmake/chip_gn_args.cmake index 8fde49c3438098..7d86d1fb433fdf 100644 --- a/config/common/cmake/chip_gn_args.cmake +++ b/config/common/cmake/chip_gn_args.cmake @@ -171,7 +171,6 @@ macro(matter_common_gn_args) LIB_PW_RPC DEVICE_INFO_EXAMPLE_PROVIDER PROJECT_CONFIG - DATA_MODEL_INTERFACE ) set(multiValueArgs PROJECT_CONFIG_INC_DIR @@ -204,10 +203,6 @@ macro(matter_common_gn_args) matter_add_gn_arg_bool ("chip_build_example_providers" ${ARG_DEVICE_INFO_EXAMPLE_PROVIDER}) endif() # ARG_DEVICE_INFO_EXAMPLE_PROVIDER - if (ARG_DATA_MODEL_INTERFACE) - matter_add_gn_arg_string("chip_use_data_model_interface" "${ARG_DATA_MODEL_INTERFACE}") - endif() - if (ARG_PROJECT_CONFIG) get_filename_component(PROJECT_CONFIG ${ARG_PROJECT_CONFIG} diff --git a/config/esp32/components/chip/CMakeLists.txt b/config/esp32/components/chip/CMakeLists.txt index f2036570b01a15..ddf4d72ff8691b 100644 --- a/config/esp32/components/chip/CMakeLists.txt +++ b/config/esp32/components/chip/CMakeLists.txt @@ -33,8 +33,6 @@ include(${CMAKE_CURRENT_LIST_DIR}/ota-image.cmake) set(CHIP_REQUIRE_COMPONENTS esp_eth freertos lwip bt mbedtls fatfs app_update console openthread nvs_flash spi_flash) -set(CHIP_DATA_MODEL_INTERFACE "enabled" CACHE STRING "Data model interface option to use: enabled or disabled") - if(NOT "${IDF_TARGET}" STREQUAL "esp32h2") list(APPEND CHIP_REQUIRE_COMPONENTS mdns) endif() @@ -66,12 +64,6 @@ macro(chip_gn_arg_bool arg boolean) endif() endmacro() -if ("${CHIP_DATA_MODEL_INTERFACE}" STREQUAL "enabled") - chip_gn_arg_append("chip_use_data_model_interface" "\"enabled\"") -else() - chip_gn_arg_append("chip_use_data_model_interface" "\"disabled\"") -endif() - # ESP-IDF lets user set software version string by two ways: # 1. Project's CMakeLists.txt file and 2. Config option # It depends on CONFIG_APP_PROJECT_VER_FROM_CONFIG option diff --git a/config/mbed/CMakeLists.txt b/config/mbed/CMakeLists.txt index e74127b7c0073a..88567b604e3254 100644 --- a/config/mbed/CMakeLists.txt +++ b/config/mbed/CMakeLists.txt @@ -112,9 +112,6 @@ if (CONFIG_MBED_BSD_SOCKET_TRACE) matter_add_flags(-DMBED_BSD_SOCKET_TRACE=1) endif() -# Option can be set with `-DCHIP_DATA_MODEL_INTERFACE=enabled` or similar on the command line -set(CHIP_DATA_MODEL_INTERFACE "enabled" CACHE STRING "Data model interface option to use: enabled or disabled") - # ============================================================================== # Generate configuration for CHIP GN build system # ============================================================================== @@ -124,7 +121,6 @@ matter_common_gn_args( LIB_TESTS CONFIG_CHIP_BUILD_TESTS LIB_PW_RPC CONFIG_CHIP_PW_RPC PROJECT_CONFIG ${CONFIG_CHIP_PROJECT_CONFIG} - DATA_MODEL_INTERFACE ${CHIP_DATA_MODEL_INTERFACE} ) if (CONFIG_CHIP_PW_RPC) matter_add_gn_arg_import("${GN_ROOT_TARGET}/lib/pw_rpc/pw_rpc.gni") diff --git a/config/nrfconnect/chip-module/CMakeLists.txt b/config/nrfconnect/chip-module/CMakeLists.txt index b3180fdc1b391f..448287f0ecd4cf 100644 --- a/config/nrfconnect/chip-module/CMakeLists.txt +++ b/config/nrfconnect/chip-module/CMakeLists.txt @@ -106,13 +106,6 @@ endif() get_property(CHIP_COMPILER_LAUNCHER GLOBAL PROPERTY RULE_LAUNCH_COMPILE) - -if (CONFIG_USE_CHIP_DATA_MODEL_INTERFACE) - set(DATA_MODEL_INTERFACE "enabled") -else() - set(DATA_MODEL_INTERFACE "disabled") -endif() - # ============================================================================== # Generate configuration for CHIP GN build system # ============================================================================== @@ -123,7 +116,6 @@ matter_common_gn_args( LIB_TESTS CONFIG_CHIP_BUILD_TESTS PROJECT_CONFIG ${CONFIG_CHIP_PROJECT_CONFIG} DEVICE_INFO_EXAMPLE_PROVIDER CONFIG_CHIP_EXAMPLE_DEVICE_INFO_PROVIDER - DATA_MODEL_INTERFACE ${DATA_MODEL_INTERFACE} ) matter_add_gn_arg_string("zephyr_ar" ${CMAKE_AR}) matter_add_gn_arg_string("zephyr_cc" ${CMAKE_C_COMPILER}) diff --git a/config/nxp/chip-cmake-freertos/CMakeLists.txt b/config/nxp/chip-cmake-freertos/CMakeLists.txt index 517d3539329b2b..a3c59dcb1feb1e 100644 --- a/config/nxp/chip-cmake-freertos/CMakeLists.txt +++ b/config/nxp/chip-cmake-freertos/CMakeLists.txt @@ -50,12 +50,6 @@ matter_add_gn_arg_bool("nxp_enable_secure_whole_factory_data" ${CONFIG_CHIP_ENAB matter_add_gn_arg_bool("nxp_enable_matter_cli" CONFIG_CHIP_LIB_SHELL) matter_add_gn_arg_bool("chip_enable_pairing_autostart" CONFIG_CHIP_ENABLE_PAIRING_AUTOSTART) -if (CONFIG_USE_CHIP_DATA_MODEL_INTERFACE) - set(DATA_MODEL_INTERFACE "enabled") -else() - set(DATA_MODEL_INTERFACE "disabled") -endif() - if(CONFIG_BOOTLOADER_MCUBOOT) matter_add_gn_arg_bool("no_mcuboot" false) endif(CONFIG_BOOTLOADER_MCUBOOT) @@ -73,7 +67,6 @@ else() PROJECT_CONFIG ${CONFIG_CHIP_PROJECT_CONFIG} PROJECT_CONFIG_INC_DIR ${CONFIG_CHIP_PROJECT_CONFIG_INCLUDE_DIRS} DEVICE_INFO_EXAMPLE_PROVIDER CONFIG_CHIP_EXAMPLE_DEVICE_INFO_PROVIDER - DATA_MODEL_INTERFACE ${DATA_MODEL_INTERFACE} ) endif() diff --git a/config/nxp/chip-module/CMakeLists.txt b/config/nxp/chip-module/CMakeLists.txt index 5024672e144e24..66894861d40f39 100644 --- a/config/nxp/chip-module/CMakeLists.txt +++ b/config/nxp/chip-module/CMakeLists.txt @@ -91,13 +91,6 @@ endif() get_property(CHIP_COMPILER_LAUNCHER GLOBAL PROPERTY RULE_LAUNCH_COMPILE) -if (CONFIG_USE_CHIP_DATA_MODEL_INTERFACE) - set(DATA_MODEL_INTERFACE "enabled") -else() - set(DATA_MODEL_INTERFACE "disabled") -endif() - - # ============================================================================== # Generate configuration for CHIP GN build system # ============================================================================== @@ -108,7 +101,6 @@ matter_common_gn_args( LIB_TESTS CONFIG_CHIP_BUILD_TESTS PROJECT_CONFIG ${CONFIG_CHIP_PROJECT_CONFIG} DEVICE_INFO_EXAMPLE_PROVIDER CONFIG_CHIP_EXAMPLE_DEVICE_INFO_PROVIDER - DATA_MODEL_INTERFACE ${DATA_MODEL_INTERFACE} ) matter_add_gn_arg_string("zephyr_ar" ${CMAKE_AR}) matter_add_gn_arg_string("zephyr_cc" ${CMAKE_C_COMPILER}) diff --git a/config/telink/chip-module/CMakeLists.txt b/config/telink/chip-module/CMakeLists.txt index bfc26ce5d96e56..7490cc497079cd 100644 --- a/config/telink/chip-module/CMakeLists.txt +++ b/config/telink/chip-module/CMakeLists.txt @@ -77,12 +77,6 @@ if (CONFIG_CHIP_OPENTHREAD_CONFIG) zephyr_set_openthread_config(${CHIP_OPENTHREAD_CONFIG}) endif() -if (CONFIG_USE_CHIP_DATA_MODEL_INTERFACE) - set(DATA_MODEL_INTERFACE "enabled") -else() - set(DATA_MODEL_INTERFACE "disabled") -endif() - # ============================================================================== # Generate configuration for CHIP GN build system # ============================================================================== @@ -93,7 +87,6 @@ matter_common_gn_args( LIB_TESTS CONFIG_CHIP_BUILD_TESTS PROJECT_CONFIG ${CONFIG_CHIP_PROJECT_CONFIG} DEVICE_INFO_EXAMPLE_PROVIDER CONFIG_CHIP_EXAMPLE_DEVICE_INFO_PROVIDER - DATA_MODEL_INTERFACE ${DATA_MODEL_INTERFACE} ) matter_add_gn_arg_string("zephyr_ar" ${CMAKE_AR}) matter_add_gn_arg_string("zephyr_cc" ${CMAKE_C_COMPILER}) diff --git a/config/zephyr/Kconfig b/config/zephyr/Kconfig index c98628e8070e7d..d8717a625d3dd3 100644 --- a/config/zephyr/Kconfig +++ b/config/zephyr/Kconfig @@ -581,12 +581,4 @@ config CHIP_BLE_ADVERTISING_DURATION If CHIP_BLE_EXT_ADVERTISING is set to false, the maximum duration time is 15 minutes, else the maximum duration time can be extended to 2880 minutes (48h). -config USE_CHIP_DATA_MODEL_INTERFACE - bool "Use a DataModel::Provider interface for data access" - default y - help - This enables a level of indiraction in the CHIP interaction model engine in - accessing underlying data and executing operations such as - wildcard-expansion, read, write and invoke. - endif diff --git a/config/zephyr/chip-module/CMakeLists.txt b/config/zephyr/chip-module/CMakeLists.txt index fb94465b772bf6..3461a974678e93 100644 --- a/config/zephyr/chip-module/CMakeLists.txt +++ b/config/zephyr/chip-module/CMakeLists.txt @@ -70,12 +70,6 @@ if(CONFIG_CHIP) zephyr_set_openthread_config(${CHIP_OPENTHREAD_CONFIG}) endif() - if (CONFIG_USE_CHIP_DATA_MODEL_INTERFACE) - set(DATA_MODEL_INTERFACE "enabled") - else() - set(DATA_MODEL_INTERFACE "disabled") - endif() - # ============================================================================== # Generate configuration for CHIP GN build system # ============================================================================== @@ -84,7 +78,6 @@ if(CONFIG_CHIP) LIB_SHELL CONFIG_CHIP_LIB_SHELL LIB_TESTS CONFIG_CHIP_BUILD_TESTS PROJECT_CONFIG ${CONFIG_CHIP_PROJECT_CONFIG} - DATA_MODEL_INTERFACE ${DATA_MODEL_INTERFACE} ) matter_add_gn_arg_string("zephyr_ar" ${CMAKE_AR}) diff --git a/examples/common/pigweed/rpc_services/Attributes.h b/examples/common/pigweed/rpc_services/Attributes.h index d34d7e5789c3cd..99e348e3a205ba 100644 --- a/examples/common/pigweed/rpc_services/Attributes.h +++ b/examples/common/pigweed/rpc_services/Attributes.h @@ -23,23 +23,19 @@ #include #include +#include #include #include +#include +#include +#include #include #include -#include #include #include #include #include -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -#include -#include -#include -#include -#endif - namespace chip { namespace rpc { @@ -217,7 +213,6 @@ class Attributes : public pw_rpc::nanopb::Attributes::Service PW_TRY(ChipErrorToPwStatus(writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outer))); PW_TRY(ChipErrorToPwStatus(attributeReports.Init(&writer, kReportContextTag))); -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE // TODO: this assumes a singleton data model provider app::DataModel::Provider * provider = app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); @@ -243,10 +238,6 @@ class Attributes : public pw_rpc::nanopb::Attributes::Service return ::pw::Status::Internal(); } -#else - PW_TRY(ChipErrorToPwStatus(app::ReadSingleClusterData(subjectDescriptor, false, path, attributeReports, nullptr))); -#endif - attributeReports.EndOfContainer(); PW_TRY(ChipErrorToPwStatus(writer.EndContainer(outer))); PW_TRY(ChipErrorToPwStatus(writer.Finalize())); diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index 52696de1cd25cf..ff7dd298351688 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -113,8 +113,8 @@ def BuildHostTarget(): TargetPart('chip-tool', app=HostApp.CHIP_TOOL), TargetPart('thermostat', app=HostApp.THERMOSTAT), # TODO: controllers depending on a datamodel is odd. For now fix compile dependencies on ember. - TargetPart('java-matter-controller', app=HostApp.JAVA_MATTER_CONTROLLER, data_model_interface="disabled"), - TargetPart('kotlin-matter-controller', app=HostApp.KOTLIN_MATTER_CONTROLLER, data_model_interface="disabled"), + TargetPart('java-matter-controller', app=HostApp.JAVA_MATTER_CONTROLLER), + TargetPart('kotlin-matter-controller', app=HostApp.KOTLIN_MATTER_CONTROLLER), TargetPart('minmdns', app=HostApp.MIN_MDNS), TargetPart('light', app=HostApp.LIGHT), TargetPart('light-data-model-no-unique-id', app=HostApp.LIGHT_DATA_MODEL_NO_UNIQUE_ID), @@ -196,10 +196,6 @@ def BuildHostTarget(): target.AppendModifier('enable-dnssd-tests', enable_dnssd_tests=True).OnlyIfRe('-tests') target.AppendModifier('disable-dnssd-tests', enable_dnssd_tests=False).OnlyIfRe('-tests') target.AppendModifier('chip-casting-simplified', chip_casting_simplified=True).OnlyIfRe('-tv-casting-app') - target.AppendModifier('data-model-check', data_model_interface="check").ExceptIfRe('-data-model-(enabled|disabled)') - target.AppendModifier('data-model-disabled', data_model_interface="disabled").ExceptIfRe('-data-model-(check|enabled)') - target.AppendModifier('data-model-enabled', data_model_interface="enabled").ExceptIfRe('-data-model-(check|disabled)') - target.AppendModifier('check-failure-die', chip_data_model_check_die_on_failure=True).OnlyIfRe('-data-model-check') target.AppendModifier('googletest', use_googletest=True).OnlyIfRe('-tests') return target @@ -236,8 +232,6 @@ def BuildEsp32Target(): target.AppendModifier('rpc', enable_rpcs=True) target.AppendModifier('ipv6only', enable_ipv4=False) target.AppendModifier('tracing', enable_insights_trace=True).OnlyIfRe("light") - target.AppendModifier('data-model-disabled', data_model_interface="disabled").ExceptIfRe('-data-model-enabled') - target.AppendModifier('data-model-enabled', data_model_interface="enabled").ExceptIfRe('-data-model-disabled') return target @@ -339,8 +333,6 @@ def BuildNrfTarget(): ]) target.AppendModifier('rpc', enable_rpcs=True) - target.AppendModifier('data-model-disabled', use_data_model_interface=False).ExceptIfRe('-data-model-enabled') - target.AppendModifier('data-model-enabled', use_data_model_interface=True).ExceptIfRe('-data-model-disabled') return target @@ -426,8 +418,6 @@ def BuildMbedTarget(): '-(release|debug)') target.AppendModifier('debug', profile=MbedProfile.DEBUG).ExceptIfRe( '-(release|develop)') - target.AppendModifier('data-model-disabled', data_model_interface="disabled").ExceptIfRe('-data-model-enabled') - target.AppendModifier('data-model-enabled', data_model_interface="enabled").ExceptIfRe('-data-model-disabled') return target @@ -556,8 +546,6 @@ def BuildNxpTarget(): target.AppendModifier(name="ethernet", enable_ethernet=True).OnlyIfRe('rw61x_eth-zephyr') target.AppendModifier(name="thread", enable_thread=True).ExceptIfRe('zephyr') target.AppendModifier(name="matter-shell", enable_shell=True).ExceptIfRe('k32w0|k32w1') - target.AppendModifier('data-model-disabled', data_model_interface="disabled").ExceptIfRe('-data-model-enabled') - target.AppendModifier('data-model-enabled', data_model_interface="enabled").ExceptIfRe('-data-model-disabled') target.AppendModifier(name="factory-build", enable_factory_data_build=True).OnlyIfRe('rt1060|rt1170|rw61x') target.AppendModifier(name="frdm", board_variant=NxpBoardVariant.FRDM).OnlyIfRe('rw61x') target.AppendModifier(name="cmake", build_system=NxpBuildSystem.CMAKE).OnlyIfRe('rw61x') @@ -649,8 +637,6 @@ def BuildQorvoTarget(): ]) target.AppendModifier('updateimage', update_image=True) - target.AppendModifier('data-model-disabled', data_model_interface="disabled").ExceptIfRe('-data-model-enabled') - target.AppendModifier('data-model-enabled', data_model_interface="enabled").ExceptIfRe('-data-model-disabled') return target @@ -814,8 +800,6 @@ def BuildTelinkTarget(): target.AppendModifier('4mb', enable_4mb_flash=True) target.AppendModifier('mars', mars_board_config=True) target.AppendModifier('usb', usb_board_config=True) - target.AppendModifier('data-model-disabled', use_data_model_interface=False).ExceptIfRe('-data-model-enabled') - target.AppendModifier('data-model-enabled', use_data_model_interface=True).ExceptIfRe('-data-model-disabled') return target diff --git a/scripts/build/builders/esp32.py b/scripts/build/builders/esp32.py index a225315fc613c6..02f7e25e55a693 100644 --- a/scripts/build/builders/esp32.py +++ b/scripts/build/builders/esp32.py @@ -155,7 +155,6 @@ def __init__(self, enable_rpcs: bool = False, enable_ipv4: bool = True, enable_insights_trace: bool = False, - data_model_interface: Optional[str] = None, ): super(Esp32Builder, self).__init__(root, runner) self.board = board @@ -163,7 +162,6 @@ def __init__(self, self.enable_rpcs = enable_rpcs self.enable_ipv4 = enable_ipv4 self.enable_insights_trace = enable_insights_trace - self.data_model_interface = data_model_interface if not app.IsCompatible(board): raise Exception( @@ -218,9 +216,6 @@ def generate(self): cmake_flags.append( f"-DCHIP_CODEGEN_PREGEN_DIR={shlex.quote(self.options.pregen_dir)}") - if self.data_model_interface: - cmake_flags.append(f'-DCHIP_DATA_MODEL_INTERFACE={self.data_model_interface}') - cmake_args = ['-C', self.ExamplePath, '-B', shlex.quote(self.output_dir)] + cmake_flags diff --git a/scripts/build/builders/host.py b/scripts/build/builders/host.py index dbb85f99e87d16..0ced1270fb583e 100644 --- a/scripts/build/builders/host.py +++ b/scripts/build/builders/host.py @@ -334,8 +334,6 @@ def __init__(self, root, runner, app: HostApp, board=HostBoard.NATIVE, enable_test_event_triggers=None, enable_dnssd_tests: Optional[bool] = None, chip_casting_simplified: Optional[bool] = None, - data_model_interface: Optional[str] = None, - chip_data_model_check_die_on_failure: Optional[bool] = None, disable_shell=False, use_googletest=False, ): @@ -375,9 +373,6 @@ def __init__(self, root, runner, app: HostApp, board=HostBoard.NATIVE, if use_ubsan: self.extra_gn_options.append('is_ubsan=true') - if data_model_interface is not None: - self.extra_gn_options.append(f'chip_use_data_model_interface="{data_model_interface}"') - if use_dmalloc: self.extra_gn_options.append('chip_config_memory_debug_checks=true') self.extra_gn_options.append('chip_config_memory_debug_dmalloc=true') @@ -437,13 +432,7 @@ def __init__(self, root, runner, app: HostApp, board=HostBoard.NATIVE, if app == HostApp.TESTS: self.extra_gn_options.append('chip_build_tests=true') - self.extra_gn_options.append('chip_data_model_check_die_on_failure=true') self.build_command = 'check' - elif chip_data_model_check_die_on_failure is not None: - if chip_data_model_check_die_on_failure: - self.extra_gn_options.append('chip_data_model_check_die_on_failure=true') - else: - self.extra_gn_options.append('chip_data_model_check_die_on_failure=false') if app == HostApp.EFR32_TEST_RUNNER: self.build_command = 'runner' diff --git a/scripts/build/builders/mbed.py b/scripts/build/builders/mbed.py index cc4eb83a665621..92ae4e3a42a3f1 100644 --- a/scripts/build/builders/mbed.py +++ b/scripts/build/builders/mbed.py @@ -103,7 +103,6 @@ def __init__(self, app: MbedApp = MbedApp.LOCK, board: MbedBoard = MbedBoard.CY8CPROTO_062_4343W, profile: MbedProfile = MbedProfile.RELEASE, - data_model_interface: Optional[str] = None, ): super(MbedBuilder, self).__init__(root, runner) self.app = app @@ -114,7 +113,6 @@ def __init__(self, self.root, 'third_party', 'mbed-os', 'repo') self.mbed_os_posix_socket_path = os.path.join( self.root, 'third_party', 'mbed-os-posix-socket', 'repo') - self.data_model_interface = data_model_interface @property def ExamplePath(self): @@ -135,9 +133,6 @@ def generate(self): flags.append(f"-DMBED_OS_PATH={shlex.quote(self.mbed_os_path)}") flags.append(f"-DMBED_OS_POSIX_SOCKET_PATH={shlex.quote(self.mbed_os_posix_socket_path)}") - if self.data_model_interface is not None: - flags.append(f"-DCHIP_DATA_MODEL_INTERFACE={self.data_model_interface}") - if self.options.pregen_dir: flags.append(f"-DCHIP_CODEGEN_PREGEN_DIR={shlex.quote(self.options.pregen_dir)}") diff --git a/scripts/build/builders/nrf.py b/scripts/build/builders/nrf.py index b94a695359752c..bd681abedb5cfd 100644 --- a/scripts/build/builders/nrf.py +++ b/scripts/build/builders/nrf.py @@ -141,13 +141,11 @@ def __init__(self, app: NrfApp = NrfApp.LIGHT, board: NrfBoard = NrfBoard.NRF52840DK, enable_rpcs: bool = False, - use_data_model_interface: Optional[bool] = None, ): super(NrfConnectBuilder, self).__init__(root, runner) self.app = app self.board = board self.enable_rpcs = enable_rpcs - self.use_data_model_interface = use_data_model_interface def generate(self): if not os.path.exists(self.output_dir): @@ -191,10 +189,6 @@ def generate(self): if self.options.pregen_dir: flags.append(f"-DCHIP_CODEGEN_PREGEN_DIR={shlex.quote(self.options.pregen_dir)}") - if self.use_data_model_interface is not None: - value = 'y' if self.use_data_model_interface else 'n' - flags.append(f"-DCONFIG_USE_CHIP_DATA_MODEL_INTERFACE={value}") - build_flags = " -- " + " ".join(flags) if len(flags) > 0 else "" cmd = 'source "$ZEPHYR_BASE/zephyr-env.sh";\nexport ZEPHYR_TOOLCHAIN_VARIANT=zephyr;' diff --git a/scripts/build/builders/nxp.py b/scripts/build/builders/nxp.py index 0f9ebed42ad18b..fa24ef2d2d13ce 100644 --- a/scripts/build/builders/nxp.py +++ b/scripts/build/builders/nxp.py @@ -190,7 +190,6 @@ def __init__(self, enable_ethernet: bool = False, enable_shell: bool = False, enable_ota: bool = False, - data_model_interface: Optional[str] = None, enable_factory_data_build: bool = False, disable_pairing_autostart: bool = False, iw416_transceiver: bool = False, @@ -220,7 +219,6 @@ def __init__(self, self.enable_ethernet = enable_ethernet self.enable_ota = enable_ota self.enable_shell = enable_shell - self.data_model_interface = data_model_interface self.enable_factory_data_build = enable_factory_data_build self.disable_pairing_autostart = disable_pairing_autostart self.board_variant = board_variant @@ -309,9 +307,6 @@ def GnBuildArgs(self): if self.board == NxpBoard.RT1170: args.append('chip_enable_openthread=true chip_inet_config_enable_ipv4=false') - if self.data_model_interface is not None: - args.append(f'chip_use_data_model_interface="{self.data_model_interface}"') - if self.board_variant: if self.board == NxpBoard.RT1060: flag_board_variant = "evkname=\\\"%s\\\"" % self.board_variant.BoardVariantName(self.board) @@ -349,11 +344,6 @@ def CmakeBuildFlags(self): flags.append("-DCONFIG_CHIP_DEVICE_SOFTWARE_VERSION=2") flags.append("-DCONFIG_CHIP_DEVICE_SOFTWARE_VERSION_STRING=\"2.0\"") - if self.data_model_interface: - # NOTE: this is not supporting "check" - enabled = "y" if self.data_model_interface.lower() == "enabled" else "n" - flags.append(f"-DCONFIG_USE_CHIP_DATA_MODEL_INTERFACE={enabled}") - if self.enable_ota: flags.append("-DCONFIG_CHIP_OTA_REQUESTOR=true") if self.os_env == NxpOsUsed.FREERTOS and self.board == NxpBoard.RW61X: diff --git a/scripts/build/builders/qpg.py b/scripts/build/builders/qpg.py index 93feaee78f6b99..2de1d105d12d42 100644 --- a/scripts/build/builders/qpg.py +++ b/scripts/build/builders/qpg.py @@ -110,7 +110,6 @@ def __init__(self, flavour: QpgFlavour = QpgFlavour.EXT_FLASH, enable_rpcs: bool = False, update_image: bool = False, - data_model_interface: Optional[str] = None, ): super(QpgBuilder, self).__init__( root=app.BuildRoot(root), @@ -120,7 +119,6 @@ def __init__(self, self.flavour = flavour self.enable_rpcs = enable_rpcs self.update_image = update_image - self.data_model_interface = data_model_interface def GnBuildArgs(self): args = ['qpg_target_ic=\"%s\" qpg_flavour=\"%s\"' % (self.board.GnArgName(), self.flavour.GnFlavourName())] @@ -128,8 +126,6 @@ def GnBuildArgs(self): args.append('import("//with_pw_rpc.gni")') if self.update_image: args.append('matter_ota_test_image=true') - if self.data_model_interface: - args.append(f'chip_use_data_model_interface="{self.data_model_interface}"') return args def build_outputs(self): diff --git a/scripts/build/builders/telink.py b/scripts/build/builders/telink.py index 2badbce4d131eb..1145b848a289b6 100644 --- a/scripts/build/builders/telink.py +++ b/scripts/build/builders/telink.py @@ -154,7 +154,6 @@ def __init__(self, enable_4mb_flash: bool = False, mars_board_config: bool = False, usb_board_config: bool = False, - use_data_model_interface: Optional[str] = None, ): super(TelinkBuilder, self).__init__(root, runner) self.app = app @@ -167,7 +166,6 @@ def __init__(self, self.enable_4mb_flash = enable_4mb_flash self.mars_board_config = mars_board_config self.usb_board_config = usb_board_config - self.use_data_model_interface = use_data_model_interface def get_cmd_prefixes(self): if not self._runner.dry_run: @@ -215,10 +213,6 @@ def generate(self): if self.options.pregen_dir: flags.append(f"-DCHIP_CODEGEN_PREGEN_DIR={shlex.quote(self.options.pregen_dir)}") - if self.use_data_model_interface is not None: - value = 'y' if self.use_data_model_interface else 'n' - flags.append(f"-DCONFIG_USE_CHIP_DATA_MODEL_INTERFACE={value}") - build_flags = " -- " + " ".join(flags) if len(flags) > 0 else "" cmd = self.get_cmd_prefixes() diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index 5e17f58a8af78c..e58549453af58b 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -6,21 +6,21 @@ cc32xx-{lock,air-purifier} ti-cc13x4_26x4-{lighting,lock,pump,pump-controller}[-mtd][-ftd] cyw30739-{cyw30739b2_p5_evk_01,cyw30739b2_p5_evk_02,cyw30739b2_p5_evk_03,cyw930739m2evb_01,cyw930739m2evb_02}-{light,light-switch,lock,thermostat} efr32-{brd2704b,brd4316a,brd4317a,brd4318a,brd4319a,brd4186a,brd4187a,brd2601b,brd4187c,brd4186c,brd2703a,brd4338a,brd2605a,brd4343a}-{window-covering,switch,unit-test,light,lock,thermostat,pump,air-quality-sensor-app}[-rpc][-with-ota-requestor][-icd][-low-power][-shell][-no-logging][-openthread-mtd][-heap-monitoring][-no-openthread-cli][-show-qr-code][-wifi][-rs9116][-wf200][-siwx917][-ipv4][-additional-data-advertising][-use-ot-lib][-use-ot-coap-lib][-no-version][-skip-rps-generation] -esp32-{m5stack,c3devkit,devkitc,qemu}-{all-clusters,all-clusters-minimal,energy-management,ota-provider,ota-requestor,shell,light,lock,bridge,temperature-measurement,ota-requestor,tests}[-rpc][-ipv6only][-tracing][-data-model-disabled][-data-model-enabled] +esp32-{m5stack,c3devkit,devkitc,qemu}-{all-clusters,all-clusters-minimal,energy-management,ota-provider,ota-requestor,shell,light,lock,bridge,temperature-measurement,ota-requestor,tests}[-rpc][-ipv6only][-tracing] genio-lighting-app linux-fake-tests[-mbedtls][-boringssl][-asan][-tsan][-ubsan][-libfuzzer][-ossfuzz][-pw-fuzztest][-coverage][-dmalloc][-clang] -linux-{x64,arm64}-{rpc-console,all-clusters,all-clusters-minimal,chip-tool,thermostat,java-matter-controller,kotlin-matter-controller,minmdns,light,light-data-model-no-unique-id,lock,shell,ota-provider,ota-requestor,simulated-app1,simulated-app2,python-bindings,tv-app,tv-casting-app,bridge,fabric-admin,fabric-bridge,fabric-sync,tests,chip-cert,address-resolve-tool,contact-sensor,dishwasher,microwave-oven,refrigerator,rvc,air-purifier,lit-icd,air-quality-sensor,network-manager,energy-management,water-leak-detector}[-nodeps][-nlfaultinject][-platform-mdns][-minmdns-verbose][-libnl][-same-event-loop][-no-interactive][-ipv6only][-no-ble][-no-wifi][-no-thread][-no-shell][-mbedtls][-boringssl][-asan][-tsan][-ubsan][-libfuzzer][-ossfuzz][-pw-fuzztest][-coverage][-dmalloc][-clang][-test][-rpc][-with-ui][-evse-test-event][-enable-dnssd-tests][-disable-dnssd-tests][-chip-casting-simplified][-data-model-check][-data-model-disabled][-data-model-enabled][-check-failure-die][-googletest] +linux-{x64,arm64}-{rpc-console,all-clusters,all-clusters-minimal,chip-tool,thermostat,java-matter-controller,kotlin-matter-controller,minmdns,light,light-data-model-no-unique-id,lock,shell,ota-provider,ota-requestor,simulated-app1,simulated-app2,python-bindings,tv-app,tv-casting-app,bridge,fabric-admin,fabric-bridge,fabric-sync,tests,chip-cert,address-resolve-tool,contact-sensor,dishwasher,microwave-oven,refrigerator,rvc,air-purifier,lit-icd,air-quality-sensor,network-manager,energy-management,water-leak-detector}[-nodeps][-nlfaultinject][-platform-mdns][-minmdns-verbose][-libnl][-same-event-loop][-no-interactive][-ipv6only][-no-ble][-no-wifi][-no-thread][-no-shell][-mbedtls][-boringssl][-asan][-tsan][-ubsan][-libfuzzer][-ossfuzz][-pw-fuzztest][-coverage][-dmalloc][-clang][-test][-rpc][-with-ui][-evse-test-event][-enable-dnssd-tests][-disable-dnssd-tests][-chip-casting-simplified][-googletest] linux-x64-efr32-test-runner[-clang] imx-{chip-tool,lighting-app,thermostat,all-clusters-app,all-clusters-minimal-app,ota-provider-app}[-release] infineon-psoc6-{lock,light,all-clusters,all-clusters-minimal}[-ota][-updateimage][-trustm] -nxp-{k32w0,k32w1,rt1060,rt1170,rw61x,rw61x_eth,mcxw71}-{zephyr,freertos}-{lighting,contact-sensor,lock-app,all-clusters,laundry-washer,thermostat}[-factory][-low-power][-lit][-fro32k][-smu2][-dac-conversion][-rotating-id][-sw-v2][-ota][-wifi][-ethernet][-thread][-matter-shell][-data-model-disabled][-data-model-enabled][-factory-build][-frdm][-cmake][-evkc][-iw416][-w8801][-iwx12][-log-all][-log-progress][-log-error][-log-none] -mbed-cy8cproto_062_4343w-{lock,light,all-clusters,all-clusters-minimal,pigweed,ota-requestor,shell}[-release][-develop][-debug][-data-model-disabled][-data-model-enabled] +nxp-{k32w0,k32w1,rt1060,rt1170,rw61x,rw61x_eth,mcxw71}-{zephyr,freertos}-{lighting,contact-sensor,lock-app,all-clusters,laundry-washer,thermostat}[-factory][-low-power][-lit][-fro32k][-smu2][-dac-conversion][-rotating-id][-sw-v2][-ota][-wifi][-ethernet][-thread][-matter-shell][-factory-build][-frdm][-cmake][-evkc][-iw416][-w8801][-iwx12][-log-all][-log-progress][-log-error][-log-none] +mbed-cy8cproto_062_4343w-{lock,light,all-clusters,all-clusters-minimal,pigweed,ota-requestor,shell}[-release][-develop][-debug] mw320-all-clusters-app -nrf-{nrf5340dk,nrf52840dk,nrf52840dongle}-{all-clusters,all-clusters-minimal,lock,light,light-switch,shell,pump,pump-controller,window-covering}[-rpc][-data-model-disabled][-data-model-enabled] +nrf-{nrf5340dk,nrf52840dk,nrf52840dongle}-{all-clusters,all-clusters-minimal,lock,light,light-switch,shell,pump,pump-controller,window-covering}[-rpc] nrf-native-posix-64-tests nuttx-x64-light -qpg-qpg6105-{lock,light,shell,persistent-storage,light-switch,thermostat}[-updateimage][-data-model-disabled][-data-model-enabled] +qpg-qpg6105-{lock,light,shell,persistent-storage,light-switch,thermostat}[-updateimage] stm32-stm32wb5mm-dk-light tizen-arm-{all-clusters,chip-tool,light,tests}[-no-ble][-no-thread][-no-wifi][-asan][-ubsan][-coverage][-with-ui] -telink-{tlsr9118bdk40d,tlsr9518adk80d,tlsr9528a,tlsr9528a_retention,tlsr9258a,tlsr9258a_retention}-{air-quality-sensor,all-clusters,all-clusters-minimal,bridge,contact-sensor,light,light-switch,lock,ota-requestor,pump,pump-controller,shell,smoke-co-alarm,temperature-measurement,thermostat,window-covering}[-ota][-dfu][-shell][-rpc][-factory-data][-4mb][-mars][-usb][-data-model-disabled][-data-model-enabled] +telink-{tlsr9118bdk40d,tlsr9518adk80d,tlsr9528a,tlsr9528a_retention,tlsr9258a,tlsr9258a_retention}-{air-quality-sensor,all-clusters,all-clusters-minimal,bridge,contact-sensor,light,light-switch,lock,ota-requestor,pump,pump-controller,shell,smoke-co-alarm,temperature-measurement,thermostat,window-covering}[-ota][-dfu][-shell][-rpc][-factory-data][-4mb][-mars][-usb] openiotsdk-{shell,lock}[-mbedtls][-psa] diff --git a/scripts/tests/local.py b/scripts/tests/local.py index f44bdc2e546f34..aaa4d88133a6dc 100755 --- a/scripts/tests/local.py +++ b/scripts/tests/local.py @@ -587,11 +587,8 @@ def build_fabric_sync(): @cli.command() -@click.option( - "--data-model-interface", type=click.Choice(["enabled", "disabled", "check"]) -) @click.option("--asan", is_flag=True, default=False, show_default=True) -def build_casting_apps(data_model_interface, asan): +def build_casting_apps(asan): """ Builds Applications used for tv casting tests """ @@ -603,10 +600,6 @@ def build_casting_apps(data_model_interface, asan): tv_args.append('chip_crypto="boringssl"') casting_args.append('chip_crypto="boringssl"') - if data_model_interface: - tv_args.append(f'chip_use_data_model_interface="{data_model_interface}"') - casting_args.append(f'chip_use_data_model_interface="{data_model_interface}"') - if asan: tv_args.append("is_asan=true is_clang=true") casting_args.append("is_asan=true is_clang=true") diff --git a/src/app/AttributePathExpandIterator-Checked.cpp b/src/app/AttributePathExpandIterator-Checked.cpp deleted file mode 100644 index 119eb29d5b22f4..00000000000000 --- a/src/app/AttributePathExpandIterator-Checked.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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 "lib/support/logging/TextOnlyLogging.h" -#include - -namespace chip { -namespace app { -AttributePathExpandIteratorChecked::AttributePathExpandIteratorChecked(DataModel::Provider * dataModel, - SingleLinkedListNode * attributePath) : - mDataModelIterator(dataModel, attributePath), - mEmberIterator(dataModel, attributePath) -{ - CheckOutputsIdentical("Constructor"); -} - -bool AttributePathExpandIteratorChecked::Next() -{ - bool dmResult = mDataModelIterator.Next(); - bool emResult = mEmberIterator.Next(); - - CheckOutputsIdentical("Next"); - - VerifyOrDie(dmResult == emResult); - - return emResult; -} - -bool AttributePathExpandIteratorChecked::Get(ConcreteAttributePath & aPath) -{ - CheckOutputsIdentical("Get"); - return mEmberIterator.Get(aPath); -} - -void AttributePathExpandIteratorChecked::ResetCurrentCluster() -{ - mDataModelIterator.ResetCurrentCluster(); - mEmberIterator.ResetCurrentCluster(); - - CheckOutputsIdentical("ResetCurrentCluster"); -} - -void AttributePathExpandIteratorChecked::ResetTo(SingleLinkedListNode * paths) - -{ - mDataModelIterator.ResetTo(paths); - mEmberIterator.ResetTo(paths); - CheckOutputsIdentical("ResetTo"); -} - -void AttributePathExpandIteratorChecked::CheckOutputsIdentical(const char * msg) -{ - ConcreteAttributePath dmPath; - ConcreteAttributePath emPath; - - bool dmResult = mDataModelIterator.Get(dmPath); - bool emResult = mEmberIterator.Get(emPath); - - if (dmResult == emResult) - { - // We check for: - // - either failed result (in which case path should not matter) - // - or exact match of paths on success - // - // NOTE: extra logic because mExpanded is NOT considered in operator== (ugly...) - if ((dmResult == false) || ((dmPath == emPath) && (dmPath.mExpanded == emPath.mExpanded))) - { - // outputs are identical. All is good - return; - } - } - - ChipLogProgress(Test, "Different paths in DM vs EMBER (%d and %d) in %s", dmResult, emResult, msg); - ChipLogProgress(Test, " DM PATH: 0x%X/" ChipLogFormatMEI "/" ChipLogFormatMEI " (%s)", dmPath.mEndpointId, - ChipLogValueMEI(dmPath.mClusterId), ChipLogValueMEI(dmPath.mAttributeId), - dmPath.mExpanded ? "EXPANDED" : "NOT expanded"); - ChipLogProgress(Test, " EMBER PATH: 0x%X/" ChipLogFormatMEI "/" ChipLogFormatMEI " (%s)", emPath.mEndpointId, - ChipLogValueMEI(emPath.mClusterId), ChipLogValueMEI(emPath.mAttributeId), - emPath.mExpanded ? "EXPANDED" : "NOT expanded"); - - chipDie(); -} - -} // namespace app -} // namespace chip diff --git a/src/app/AttributePathExpandIterator-Checked.h b/src/app/AttributePathExpandIterator-Checked.h deleted file mode 100644 index efbe99ef6faade..00000000000000 --- a/src/app/AttributePathExpandIterator-Checked.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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. - */ - -#pragma once - -#include -#include - -namespace chip { -namespace app { - -class AttributePathExpandIteratorChecked -{ -public: - AttributePathExpandIteratorChecked(DataModel::Provider * dataModel, SingleLinkedListNode * attributePath); - - bool Next(); - bool Get(ConcreteAttributePath & aPath); - void ResetCurrentCluster(); - void ResetTo(SingleLinkedListNode * paths); - -private: - AttributePathExpandIteratorDataModel mDataModelIterator; - AttributePathExpandIteratorEmber mEmberIterator; - - void CheckOutputsIdentical(const char * msg); -}; - -} // namespace app -} // namespace chip diff --git a/src/app/AttributePathExpandIterator-DataModel.h b/src/app/AttributePathExpandIterator-DataModel.h deleted file mode 100644 index c8baca768b4602..00000000000000 --- a/src/app/AttributePathExpandIterator-DataModel.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * 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. - */ -#pragma once - -#include -#include -#include -#include - -namespace chip { -namespace app { - -/** - * AttributePathExpandIteratorDataModel is used to iterate over a linked list of AttributePathParams-s. - * The AttributePathExpandIteratorDataModel is copiable, however, the given cluster info must be valid when calling Next(). - * - * AttributePathExpandIteratorDataModel will expand attribute paths with wildcards, and only emit existing paths for - * AttributePathParams with wildcards. For AttributePathParams with a concrete path (i.e. does not contain wildcards), - * AttributePathExpandIteratorDataModel will emit them as-is. - * - * The typical use of AttributePathExpandIteratorDataModel may look like: - * ConcreteAttributePath path; - * for (AttributePathExpandIteratorDataModel iterator(AttributePathParams); iterator.Get(path); iterator.Next()) {...} - * - * The iterator does not copy the given AttributePathParams, The given AttributePathParams must be valid when using the iterator. - * If the set of endpoints, clusters, or attributes that are supported changes, AttributePathExpandIteratorDataModel must be - * reinitialized. - * - * A initialized iterator will return the first valid path, no need to call Next() before calling Get() for the first time. - * - * Note: The Next() and Get() are two separate operations by design since a possible call of this iterator might be: - * - Get() - * - Chunk full, return - * - In a new chunk, Get() - * - * TODO: The AttributePathParams may support a group id, the iterator should be able to call group data provider to expand the group - * id. - */ -class AttributePathExpandIteratorDataModel -{ -public: - AttributePathExpandIteratorDataModel(DataModel::Provider * provider, SingleLinkedListNode * attributePath); - - /** - * Proceed the iterator to the next attribute path in the given cluster info. - * - * Returns false if AttributePathExpandIteratorDataModeDataModel has exhausted all paths in the given AttributePathParams list. - */ - bool Next(); - - /** - * Fills the aPath with the path the iterator currently points to. - * Returns false if the iterator is not pointing to a valid path (i.e. it has exhausted the cluster info). - */ - bool Get(ConcreteAttributePath & aPath) - { - aPath = mOutputPath; - return (mpAttributePath != nullptr); - } - - /** - * Reset the iterator to the beginning of current cluster if we are in the middle of expanding a wildcard attribute id for some - * cluster. - * - * When attributes are changed in the middle of expanding a wildcard attribute, we need to reset the iterator, to provide the - * client with a consistent state of the cluster. - */ - void ResetCurrentCluster(); - - /** Start iterating over the given `paths` */ - inline void ResetTo(SingleLinkedListNode * paths) - { - *this = AttributePathExpandIteratorDataModel(mDataModelProvider, paths); - } - -private: - DataModel::Provider * mDataModelProvider; - SingleLinkedListNode * mpAttributePath; - ConcreteAttributePath mOutputPath; - - /// Move to the next endpoint/cluster/attribute triplet that is valid given - /// the current mOutputPath and mpAttributePath - /// - /// returns true if such a next value was found. - bool AdvanceOutputPath(); - - /// Get the next attribute ID in mOutputPath(endpoint/cluster) if one is available. - /// Will start from the beginning if current mOutputPath.mAttributeId is kInvalidAttributeId - /// - /// Respects path expansion/values in mpAttributePath - /// - /// Handles Global attributes (which are returned at the end) - std::optional NextAttributeId(); - - /// Get the next cluster ID in mOutputPath(endpoint) if one is available. - /// Will start from the beginning if current mOutputPath.mClusterId is kInvalidClusterId - /// - /// Respects path expansion/values in mpAttributePath - std::optional NextClusterId(); - - /// Get the next endpoint ID in mOutputPath if one is available. - /// Will start from the beginning if current mOutputPath.mEndpointId is kInvalidEndpointId - /// - /// Respects path expansion/values in mpAttributePath - std::optional NextEndpointId(); - - /// Checks if the given attributeId is valid for the current mOutputPath(endpoint/cluster) - /// - /// Meaning that it is known to the data model OR it is a always-there global attribute. - bool IsValidAttributeId(AttributeId attributeId); -}; - -} // namespace app -} // namespace chip diff --git a/src/app/AttributePathExpandIterator-Ember.cpp b/src/app/AttributePathExpandIterator-Ember.cpp deleted file mode 100644 index 1149f0c7026918..00000000000000 --- a/src/app/AttributePathExpandIterator-Ember.cpp +++ /dev/null @@ -1,261 +0,0 @@ -/* - * - * Copyright (c) 2021 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 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace chip; - -// TODO: Need to make it so that declarations of things that don't depend on generated files are not intermixed in af.h with -// dependencies on generated files, so we don't have to re-declare things here. -// Note: Some of the generated files that depended by af.h are gen_config.h and gen_tokens.h -typedef uint8_t EmberAfClusterMask; - -extern uint16_t emberAfEndpointCount(); -extern uint16_t emberAfIndexFromEndpoint(EndpointId endpoint); -extern uint8_t emberAfClusterCount(EndpointId endpoint, bool server); -extern uint16_t emberAfGetServerAttributeCount(chip::EndpointId endpoint, chip::ClusterId cluster); -extern uint16_t emberAfGetServerAttributeIndexByAttributeId(chip::EndpointId endpoint, chip::ClusterId cluster, - chip::AttributeId attributeId); -extern chip::EndpointId emberAfEndpointFromIndex(uint16_t index); -extern Optional emberAfGetNthClusterId(chip::EndpointId endpoint, uint8_t n, bool server); -extern Optional emberAfGetServerAttributeIdByIndex(chip::EndpointId endpoint, chip::ClusterId cluster, - uint16_t attributeIndex); -extern uint8_t emberAfClusterIndex(EndpointId endpoint, ClusterId clusterId, EmberAfClusterMask mask); -extern bool emberAfEndpointIndexIsEnabled(uint16_t index); - -namespace chip { -namespace app { - -AttributePathExpandIteratorEmber::AttributePathExpandIteratorEmber(DataModel::Provider *, - SingleLinkedListNode * aAttributePath) : - mpAttributePath(aAttributePath) -{ - - // Reset iterator state - mEndpointIndex = UINT16_MAX; - mClusterIndex = UINT8_MAX; - mAttributeIndex = UINT16_MAX; - - static_assert(std::numeric_limits::max() >= ArraySize(GlobalAttributesNotInMetadata), - "Our index won't be able to hold the value we need to hold."); - static_assert(std::is_same::value, - "If this changes audit all uses where we set to UINT8_MAX"); - mGlobalAttributeIndex = UINT8_MAX; - - // Make the iterator ready to emit the first valid path in the list. - Next(); -} - -void AttributePathExpandIteratorEmber::PrepareEndpointIndexRange(const AttributePathParams & aAttributePath) -{ - if (aAttributePath.HasWildcardEndpointId()) - { - mEndpointIndex = 0; - mEndEndpointIndex = emberAfEndpointCount(); - } - else - { - mEndpointIndex = emberAfIndexFromEndpoint(aAttributePath.mEndpointId); - // If the given cluster id does not exist on the given endpoint, it will return uint16(0xFFFF), then endEndpointIndex - // will be 0, means we should iterate a null endpoint set (skip it). - mEndEndpointIndex = static_cast(mEndpointIndex + 1); - } -} - -void AttributePathExpandIteratorEmber::PrepareClusterIndexRange(const AttributePathParams & aAttributePath, EndpointId aEndpointId) -{ - if (aAttributePath.HasWildcardClusterId()) - { - mClusterIndex = 0; - mEndClusterIndex = emberAfClusterCount(aEndpointId, true /* server */); - } - else - { - mClusterIndex = emberAfClusterIndex(aEndpointId, aAttributePath.mClusterId, CLUSTER_MASK_SERVER); - // If the given cluster id does not exist on the given endpoint, it will return uint8(0xFF), then endClusterIndex - // will be 0, means we should iterate a null cluster set (skip it). - mEndClusterIndex = static_cast(mClusterIndex + 1); - } -} - -void AttributePathExpandIteratorEmber::PrepareAttributeIndexRange(const AttributePathParams & aAttributePath, - EndpointId aEndpointId, ClusterId aClusterId) -{ - if (aAttributePath.HasWildcardAttributeId()) - { - mAttributeIndex = 0; - mEndAttributeIndex = emberAfGetServerAttributeCount(aEndpointId, aClusterId); - mGlobalAttributeIndex = 0; - mGlobalAttributeEndIndex = ArraySize(GlobalAttributesNotInMetadata); - } - else - { - mAttributeIndex = emberAfGetServerAttributeIndexByAttributeId(aEndpointId, aClusterId, aAttributePath.mAttributeId); - // If the given attribute id does not exist on the given endpoint, it will return uint16(0xFFFF), then endAttributeIndex - // will be 0, means we should iterate a null attribute set (skip it). - mEndAttributeIndex = static_cast(mAttributeIndex + 1); - if (mAttributeIndex == UINT16_MAX) - { - // Check whether this is a non-metadata global attribute. - // - // Default to the max value, which will correspond (after we add 1 - // and overflow to 0 for the max index) to us not going through - // non-metadata global attributes for this attribute. - mGlobalAttributeIndex = UINT8_MAX; - - static_assert(ArraySize(GlobalAttributesNotInMetadata) <= UINT8_MAX, "Iterating over at most 256 array entries"); - - const uint8_t arraySize = static_cast(ArraySize(GlobalAttributesNotInMetadata)); - for (uint8_t idx = 0; idx < arraySize; ++idx) - { - if (GlobalAttributesNotInMetadata[idx] == aAttributePath.mAttributeId) - { - mGlobalAttributeIndex = idx; - break; - } - } - mGlobalAttributeEndIndex = static_cast(mGlobalAttributeIndex + 1); - } - else - { - mGlobalAttributeIndex = UINT8_MAX; - mGlobalAttributeEndIndex = 0; - } - } -} - -void AttributePathExpandIteratorEmber::ResetCurrentCluster() -{ - // If this is a null iterator, or the attribute id of current cluster info is not a wildcard attribute id, then this function - // will do nothing, since we won't be expanding the wildcard attribute ids under a cluster. - VerifyOrReturn(mpAttributePath != nullptr && mpAttributePath->mValue.HasWildcardAttributeId()); - - // Otherwise, we will reset the index for iterating the attributes, so we report the attributes for this cluster again. This - // will ensure that the client sees a coherent view of the cluster from the reports generated by a single (wildcard) attribute - // path in the request. - // - // Note that when Next() returns, we must be in one of the following states: - // - This is not a wildcard path - // - We just expanded some attribute id field - // - We have exhausted all paths - // Only the second case will happen here since the above check will fail for 1 and 3, so the following Next() call must result - // in a valid path, which is the first attribute id we will emit for the current cluster. - mAttributeIndex = UINT16_MAX; - mGlobalAttributeIndex = UINT8_MAX; - Next(); -} - -bool AttributePathExpandIteratorEmber::Next() -{ - for (; mpAttributePath != nullptr; (mpAttributePath = mpAttributePath->mpNext, mEndpointIndex = UINT16_MAX)) - { - mOutputPath.mExpanded = mpAttributePath->mValue.IsWildcardPath(); - - if (mEndpointIndex == UINT16_MAX) - { - // Special case: If this is a concrete path, we just return its value as-is. - if (!mpAttributePath->mValue.IsWildcardPath()) - { - mOutputPath.mEndpointId = mpAttributePath->mValue.mEndpointId; - mOutputPath.mClusterId = mpAttributePath->mValue.mClusterId; - mOutputPath.mAttributeId = mpAttributePath->mValue.mAttributeId; - - // Prepare for next iteration - mEndpointIndex = mEndEndpointIndex = 0; - return true; - } - - PrepareEndpointIndexRange(mpAttributePath->mValue); - mClusterIndex = UINT8_MAX; - } - - for (; mEndpointIndex < mEndEndpointIndex; - (mEndpointIndex++, mClusterIndex = UINT8_MAX, mAttributeIndex = UINT16_MAX, mGlobalAttributeIndex = UINT8_MAX)) - { - if (!emberAfEndpointIndexIsEnabled(mEndpointIndex)) - { - // Not an enabled endpoint; skip it. - continue; - } - - EndpointId endpointId = emberAfEndpointFromIndex(mEndpointIndex); - - if (mClusterIndex == UINT8_MAX) - { - PrepareClusterIndexRange(mpAttributePath->mValue, endpointId); - mAttributeIndex = UINT16_MAX; - mGlobalAttributeIndex = UINT8_MAX; - } - - for (; mClusterIndex < mEndClusterIndex; - (mClusterIndex++, mAttributeIndex = UINT16_MAX, mGlobalAttributeIndex = UINT8_MAX)) - { - // emberAfGetNthClusterId must return a valid cluster id here since we have verified the mClusterIndex does - // not exceed the mEndClusterIndex. - ClusterId clusterId = emberAfGetNthClusterId(endpointId, mClusterIndex, true /* server */).Value(); - if (mAttributeIndex == UINT16_MAX && mGlobalAttributeIndex == UINT8_MAX) - { - PrepareAttributeIndexRange(mpAttributePath->mValue, endpointId, clusterId); - } - - if (mAttributeIndex < mEndAttributeIndex) - { - // GetServerAttributeIdByIdex must return a valid attribute here since we have verified the mAttributeIndex does - // not exceed the mEndAttributeIndex. - mOutputPath.mAttributeId = emberAfGetServerAttributeIdByIndex(endpointId, clusterId, mAttributeIndex).Value(); - mOutputPath.mClusterId = clusterId; - mOutputPath.mEndpointId = endpointId; - mAttributeIndex++; - // We found a valid attribute path, now return and increase the attribute index for next iteration. - // Return true will skip the increment of mClusterIndex, mEndpointIndex and mpAttributePath. - return true; - } - if (mGlobalAttributeIndex < mGlobalAttributeEndIndex) - { - // Return a path pointing to the next global attribute. - mOutputPath.mAttributeId = GlobalAttributesNotInMetadata[mGlobalAttributeIndex]; - mOutputPath.mClusterId = clusterId; - mOutputPath.mEndpointId = endpointId; - mGlobalAttributeIndex++; - return true; - } - // We have exhausted all attributes of this cluster, continue iterating over attributes of next cluster. - } - // We have exhausted all clusters of this endpoint, continue iterating over clusters of next endpoint. - } - // We have exhausted all endpoints in this cluster info, continue iterating over next cluster info item. - } - - // Reset to default, invalid value. - mOutputPath = ConcreteReadAttributePath(); - return false; -} -} // namespace app -} // namespace chip diff --git a/src/app/AttributePathExpandIterator-Ember.h b/src/app/AttributePathExpandIterator-Ember.h deleted file mode 100644 index c7c112d689064b..00000000000000 --- a/src/app/AttributePathExpandIterator-Ember.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - * - * Copyright (c) 2021 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. - */ - -/** - * @file - * Defines an iterator for iterating all possible paths from a list of AttributePathParams-s according to spec section 8.9.2.2 - * (Valid Attribute Paths) - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace chip { -namespace app { - -/** - * AttributePathExpandIteratorEmber is used to iterate over a linked list of AttributePathParams-s. - * The AttributePathExpandIteratorEmber is copiable, however, the given cluster info must be valid when calling Next(). - * - * AttributePathExpandIteratorEmber will expand attribute paths with wildcards, and only emit existing paths for AttributePathParams - * with wildcards. For AttributePathParams with a concrete path (i.e. does not contain wildcards), AttributePathExpandIteratorEmber - * will emit them as-is. - * - * The typical use of AttributePathExpandIteratorEmber may look like: - * ConcreteAttributePath path; - * for (AttributePathExpandIteratorEmber iterator(AttributePathParams); iterator.Get(path); iterator.Next()) {...} - * - * The iterator does not copy the given AttributePathParams, The given AttributePathParams must be valid when using the iterator. - * If the set of endpoints, clusters, or attributes that are supported changes, AttributePathExpandIteratorEmber must be - * reinitialized. - * - * A initialized iterator will return the first valid path, no need to call Next() before calling Get() for the first time. - * - * Note: The Next() and Get() are two separate operations by design since a possible call of this iterator might be: - * - Get() - * - Chunk full, return - * - In a new chunk, Get() - * - * TODO: The AttributePathParams may support a group id, the iterator should be able to call group data provider to expand the group - * id. - */ -class AttributePathExpandIteratorEmber -{ -public: - AttributePathExpandIteratorEmber(DataModel::Provider *, // datamodel is NOT used by this class - SingleLinkedListNode * aAttributePath); - - /** - * Proceed the iterator to the next attribute path in the given cluster info. - * - * Returns false if AttributePathExpandIteratorEmber has exhausted all paths in the given AttributePathParams list. - */ - bool Next(); - - /** - * Fills the aPath with the path the iterator currently points to. - * Returns false if the iterator is not pointing to a valid path (i.e. it has exhausted the cluster info). - */ - bool Get(ConcreteAttributePath & aPath) - { - aPath = mOutputPath; - return (mpAttributePath != nullptr); // still handling some path - } - - /** - * Reset the iterator to the beginning of current cluster if we are in the middle of expanding a wildcard attribute id for some - * cluster. - * - * When attributes are changed in the middle of expanding a wildcard attribute, we need to reset the iterator, to provide the - * client with a consistent state of the cluster. - */ - void ResetCurrentCluster(); - - /** Start iterating over the given `paths` */ - inline void ResetTo(SingleLinkedListNode * paths) - { - *this = AttributePathExpandIteratorEmber(nullptr /* data model is not used */, paths); - } - -private: - SingleLinkedListNode * mpAttributePath; - - ConcreteAttributePath mOutputPath; - - uint16_t mEndpointIndex, mEndEndpointIndex; - uint16_t mAttributeIndex, mEndAttributeIndex; - - // Note: should use decltype(EmberAfEndpointType::clusterCount) here, but af-types is including app specific generated files. - uint8_t mClusterIndex, mEndClusterIndex; - // For dealing with global attributes that are not part of the attribute - // metadata. - uint8_t mGlobalAttributeIndex, mGlobalAttributeEndIndex; - - /** - * Prepare*IndexRange will update mBegin*Index and mEnd*Index variables. - * If AttributePathParams contains a wildcard field, it will set mBegin*Index to 0 and mEnd*Index to count. - * Or it will set mBegin*Index to the index of the Endpoint/Cluster/Attribute, and mEnd*Index to mBegin*Index + 1. - * - * If the Endpoint/Cluster/Attribute does not exist, mBegin*Index will be UINT*_MAX, and mEnd*Inde will be 0. - * - * The index can be used with emberAfEndpointFromIndex, emberAfGetNthClusterId and emberAfGetServerAttributeIdByIndex. - */ - void PrepareEndpointIndexRange(const AttributePathParams & aAttributePath); - void PrepareClusterIndexRange(const AttributePathParams & aAttributePath, EndpointId aEndpointId); - void PrepareAttributeIndexRange(const AttributePathParams & aAttributePath, EndpointId aEndpointId, ClusterId aClusterId); -}; -} // namespace app -} // namespace chip diff --git a/src/app/AttributePathExpandIterator-DataModel.cpp b/src/app/AttributePathExpandIterator.cpp similarity index 91% rename from src/app/AttributePathExpandIterator-DataModel.cpp rename to src/app/AttributePathExpandIterator.cpp index 1564db34568ee3..96aa2772912139 100644 --- a/src/app/AttributePathExpandIterator-DataModel.cpp +++ b/src/app/AttributePathExpandIterator.cpp @@ -14,17 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "lib/support/CodeUtils.h" -#include +#include + #include +#include using namespace chip::app::DataModel; namespace chip { namespace app { -AttributePathExpandIteratorDataModel::AttributePathExpandIteratorDataModel( - DataModel::Provider * provider, SingleLinkedListNode * attributePath) : +AttributePathExpandIterator::AttributePathExpandIterator(DataModel::Provider * provider, + SingleLinkedListNode * attributePath) : mDataModelProvider(provider), mpAttributePath(attributePath), mOutputPath(kInvalidEndpointId, kInvalidClusterId, kInvalidAttributeId) @@ -36,7 +37,7 @@ AttributePathExpandIteratorDataModel::AttributePathExpandIteratorDataModel( Next(); } -bool AttributePathExpandIteratorDataModel::IsValidAttributeId(AttributeId attributeId) +bool AttributePathExpandIterator::IsValidAttributeId(AttributeId attributeId) { switch (attributeId) { @@ -52,7 +53,7 @@ bool AttributePathExpandIteratorDataModel::IsValidAttributeId(AttributeId attrib return mDataModelProvider->GetAttributeInfo(attributePath).has_value(); } -std::optional AttributePathExpandIteratorDataModel::NextAttributeId() +std::optional AttributePathExpandIterator::NextAttributeId() { if (mOutputPath.mAttributeId == kInvalidAttributeId) { @@ -107,7 +108,7 @@ std::optional AttributePathExpandIteratorDataModel::NextAttributeId return GlobalAttributesNotInMetadata[0]; } -std::optional AttributePathExpandIteratorDataModel::NextClusterId() +std::optional AttributePathExpandIterator::NextClusterId() { if (mOutputPath.mClusterId == kInvalidClusterId) @@ -134,7 +135,7 @@ std::optional AttributePathExpandIteratorDataModel::NextClusterId() return entry.IsValid() ? std::make_optional(entry.path.mClusterId) : std::nullopt; } -std::optional AttributePathExpandIteratorDataModel::NextEndpointId() +std::optional AttributePathExpandIterator::NextEndpointId() { if (mOutputPath.mEndpointId == kInvalidEndpointId) { @@ -153,7 +154,7 @@ std::optional AttributePathExpandIteratorDataModel::NextEndpointId() return (id != kInvalidEndpointId) ? std::make_optional(id) : std::nullopt; } -void AttributePathExpandIteratorDataModel::ResetCurrentCluster() +void AttributePathExpandIterator::ResetCurrentCluster() { // If this is a null iterator, or the attribute id of current cluster info is not a wildcard attribute id, then this function // will do nothing, since we won't be expanding the wildcard attribute ids under a cluster. @@ -165,7 +166,7 @@ void AttributePathExpandIteratorDataModel::ResetCurrentCluster() Next(); } -bool AttributePathExpandIteratorDataModel::AdvanceOutputPath() +bool AttributePathExpandIterator::AdvanceOutputPath() { if (!mpAttributePath->mValue.IsWildcardPath()) { @@ -218,7 +219,7 @@ bool AttributePathExpandIteratorDataModel::AdvanceOutputPath() } } -bool AttributePathExpandIteratorDataModel::Next() +bool AttributePathExpandIterator::Next() { while (mpAttributePath != nullptr) { diff --git a/src/app/AttributePathExpandIterator.h b/src/app/AttributePathExpandIterator.h index fae69fe7995d4e..351520f7c49c99 100644 --- a/src/app/AttributePathExpandIterator.h +++ b/src/app/AttributePathExpandIterator.h @@ -17,30 +17,113 @@ */ #pragma once -#include - -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL && CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -#include -#else -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -#include -#else -#include -#endif // CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -#endif // CHIP_CONFIG_USE_EMBER_DATA_MODEL && CHIP_CONFIG_USE_DATA_MODEL_INTERFACE +#include +#include +#include +#include namespace chip { namespace app { -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL && CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -using AttributePathExpandIterator = ::chip::app::AttributePathExpandIteratorChecked; -#else -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -using AttributePathExpandIterator = ::chip::app::AttributePathExpandIteratorDataModel; -#else -using AttributePathExpandIterator = ::chip::app::AttributePathExpandIteratorEmber; -#endif // CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -#endif // CHIP_CONFIG_USE_EMBER_DATA_MODEL && CHIP_CONFIG_USE_DATA_MODEL_INTERFACE +/** + * AttributePathExpandIterator is used to iterate over a linked list of AttributePathParams-s. + * The AttributePathExpandIterator is copiable, however, the given cluster info must be valid when calling Next(). + * + * AttributePathExpandIterator will expand attribute paths with wildcards, and only emit existing paths for + * AttributePathParams with wildcards. For AttributePathParams with a concrete path (i.e. does not contain wildcards), + * AttributePathExpandIterator will emit them as-is. + * + * The typical use of AttributePathExpandIterator may look like: + * ConcreteAttributePath path; + * for (AttributePathExpandIterator iterator(AttributePathParams); iterator.Get(path); iterator.Next()) {...} + * + * The iterator does not copy the given AttributePathParams. The given AttributePathParams must remain valid when using the + * iterator. If the set of endpoints, clusters, or attributes that are supported changes, AttributePathExpandIterator must be + * reinitialized. + * + * A initialized iterator will return the first valid path, no need to call Next() before calling Get() for the first time. + * + * Note: Next() and Get() are two separate operations by design since a possible call of this iterator might be: + * - Get() + * - Chunk full, return + * - In a new chunk, Get() + * + * TODO: The AttributePathParams may support a group id, the iterator should be able to call group data provider to expand the group + * id. + */ +class AttributePathExpandIterator +{ +public: + AttributePathExpandIterator(DataModel::Provider * provider, SingleLinkedListNode * attributePath); + + /** + * Proceed the iterator to the next attribute path in the given cluster info. + * + * Returns false if AttributePathExpandIteratorDataModeDataModel has exhausted all paths in the given AttributePathParams list. + */ + bool Next(); + + /** + * Fills the aPath with the path the iterator currently points to. + * Returns false if the iterator is not pointing to a valid path (i.e. it has exhausted the cluster info). + */ + bool Get(ConcreteAttributePath & aPath) + { + aPath = mOutputPath; + return (mpAttributePath != nullptr); + } + + /** + * Reset the iterator to the beginning of current cluster if we are in the middle of expanding a wildcard attribute id for some + * cluster. + * + * When attributes are changed in the middle of expanding a wildcard attribute, we need to reset the iterator, to provide the + * client with a consistent state of the cluster. + */ + void ResetCurrentCluster(); + + /** Start iterating over the given `paths` */ + inline void ResetTo(SingleLinkedListNode * paths) + { + *this = AttributePathExpandIterator(mDataModelProvider, paths); + } + +private: + DataModel::Provider * mDataModelProvider; + SingleLinkedListNode * mpAttributePath; + ConcreteAttributePath mOutputPath; + + /// Move to the next endpoint/cluster/attribute triplet that is valid given + /// the current mOutputPath and mpAttributePath + /// + /// returns true if such a next value was found. + bool AdvanceOutputPath(); + + /// Get the next attribute ID in mOutputPath(endpoint/cluster) if one is available. + /// Will start from the beginning if current mOutputPath.mAttributeId is kInvalidAttributeId + /// + /// Respects path expansion/values in mpAttributePath + /// + /// Handles Global attributes (which are returned at the end) + std::optional NextAttributeId(); + + /// Get the next cluster ID in mOutputPath(endpoint) if one is available. + /// Will start from the beginning if current mOutputPath.mClusterId is kInvalidClusterId + /// + /// Respects path expansion/values in mpAttributePath + std::optional NextClusterId(); + + /// Get the next endpoint ID in mOutputPath if one is available. + /// Will start from the beginning if current mOutputPath.mEndpointId is kInvalidEndpointId + /// + /// Respects path expansion/values in mpAttributePath + std::optional NextEndpointId(); + + /// Checks if the given attributeId is valid for the current mOutputPath(endpoint/cluster) + /// + /// Meaning that it is known to the data model OR it is a always-there global attribute. + bool IsValidAttributeId(AttributeId attributeId); +}; } // namespace app } // namespace chip diff --git a/src/app/AttributeValueEncoder.h b/src/app/AttributeValueEncoder.h index 89436789f91a84..a0f8fbb71dab00 100644 --- a/src/app/AttributeValueEncoder.h +++ b/src/app/AttributeValueEncoder.h @@ -115,8 +115,7 @@ class AttributeValueEncoder * * When EncodeList returns an error, the consumers must abort the encoding, and return the exact error to the caller. * - * TODO: Can we hold a error state in the AttributeValueEncoder itself so functions in ember-compatibility-functions don't have - * to rely on the above assumption? + * TODO: Can we hold a error state in the AttributeValueEncoder itself? * * Consumers are allowed to make either one call to EncodeList or one call to Encode to handle a read. * diff --git a/src/app/BUILD.gn b/src/app/BUILD.gn index 8849d39f507a34..5fc0d0c8b97583 100644 --- a/src/app/BUILD.gn +++ b/src/app/BUILD.gn @@ -75,31 +75,9 @@ buildconfig_header("app_buildconfig") { "NON_SPEC_COMPLIANT_OTA_ACTION_DELAY_FLOOR=${non_spec_compliant_ota_action_delay_floor}", "CHIP_DEVICE_CONFIG_DYNAMIC_SERVER=${chip_build_controller_dynamic_server}", "CHIP_CONFIG_ENABLE_BUSY_HANDLING_FOR_OPERATIONAL_SESSION_SETUP=${chip_enable_busy_handling_for_operational_session_setup}", - "CHIP_CONFIG_DATA_MODEL_CHECK_DIE_ON_FAILURE=${chip_data_model_check_die_on_failure}", "CHIP_CONFIG_DATA_MODEL_EXTRA_LOGGING=${chip_data_model_extra_logging}", ] - if (chip_use_data_model_interface == "disabled") { - defines += [ - "CHIP_CONFIG_USE_DATA_MODEL_INTERFACE=0", - "CHIP_CONFIG_USE_EMBER_DATA_MODEL=1", - ] - } else if (chip_use_data_model_interface == "check") { - defines += [ - "CHIP_CONFIG_USE_DATA_MODEL_INTERFACE=1", - "CHIP_CONFIG_USE_EMBER_DATA_MODEL=1", - ] - } else { - # only one of disabled/check/enabled must be used - assert(chip_use_data_model_interface == "enabled", - "chip_use_data_model_interface must use a supported value") - - defines += [ - "CHIP_CONFIG_USE_DATA_MODEL_INTERFACE=1", - "CHIP_CONFIG_USE_EMBER_DATA_MODEL=0", - ] - } - visibility = [ ":app_config" ] } @@ -221,6 +199,8 @@ static_library("interaction-model") { # # This breaks having `.h` and `.cpp` based off the same compilation unit and # should ideally be cleaned up. + "reporting/Read.cpp", + "reporting/Read.h", "reporting/reporting.h", ] @@ -253,29 +233,6 @@ static_library("interaction-model") { public_configs = [ "${chip_root}/src:includes" ] - if (chip_use_data_model_interface == "disabled") { - sources += [ - "reporting/Read-Ember.cpp", - "reporting/Read-Ember.h", - ] - } else if (chip_use_data_model_interface == "check") { - sources += [ - "reporting/Read-Checked.cpp", - "reporting/Read-Checked.h", - "reporting/Read-DataModel.cpp", - "reporting/Read-DataModel.h", - "reporting/Read-Ember.cpp", - "reporting/Read-Ember.h", - ] - public_deps += [ "${chip_root}/src/app/data-model-provider" ] - } else { # enabled - sources += [ - "reporting/Read-DataModel.cpp", - "reporting/Read-DataModel.h", - ] - public_deps += [ "${chip_root}/src/app/data-model-provider" ] - } - if (chip_enable_read_client) { sources += [ "ReadClient.cpp" ] } @@ -440,6 +397,8 @@ static_library("app") { output_name = "libCHIPDataModel" sources = [ + "AttributePathExpandIterator.cpp", + "AttributePathExpandIterator.h", "AttributePathExpandIterator.h", "AttributePersistenceProvider.h", "ChunkedWriteCallback.cpp", @@ -479,6 +438,7 @@ static_library("app") { ":global-attributes", ":interaction-model", "${chip_root}/src/app/data-model", + "${chip_root}/src/app/data-model-provider", "${chip_root}/src/app/icd/server:icd-server-config", "${chip_root}/src/app/util:callbacks", "${chip_root}/src/lib/address_resolve", @@ -488,32 +448,6 @@ static_library("app") { "${chip_root}/src/system", ] - if (chip_use_data_model_interface == "disabled") { - sources += [ - "AttributePathExpandIterator-Ember.cpp", - "AttributePathExpandIterator-Ember.h", - "AttributePathExpandIterator.h", - ] - } else if (chip_use_data_model_interface == "check") { - sources += [ - "AttributePathExpandIterator-Checked.cpp", - "AttributePathExpandIterator-Checked.h", - "AttributePathExpandIterator-DataModel.cpp", - "AttributePathExpandIterator-DataModel.h", - "AttributePathExpandIterator-Ember.cpp", - "AttributePathExpandIterator-Ember.h", - "AttributePathExpandIterator.h", - ] - public_deps += [ "${chip_root}/src/app/data-model-provider" ] - } else { # enabled - sources += [ - "AttributePathExpandIterator-DataModel.cpp", - "AttributePathExpandIterator-DataModel.h", - "AttributePathExpandIterator.h", - ] - public_deps += [ "${chip_root}/src/app/data-model-provider" ] - } - if (chip_enable_read_client) { sources += [ "BufferedReadCallback.cpp", diff --git a/src/app/CommandHandlerImpl.cpp b/src/app/CommandHandlerImpl.cpp index 80373dc32ad755..b01343b4239b5e 100644 --- a/src/app/CommandHandlerImpl.cpp +++ b/src/app/CommandHandlerImpl.cpp @@ -475,25 +475,6 @@ Status CommandHandlerImpl::ProcessGroupCommandDataIB(CommandDataIB::Parser & aCo } VerifyOrReturnError(err == CHIP_NO_ERROR, Status::Failure); - // Per spec, we do the "is this a timed command?" check for every path, but - // since all paths that fail it just get silently discarded we can do it - // once up front and discard all the paths at once. Ordering with respect - // to ACL and command presence checks does not matter, because the behavior - // is the same for all of them: ignore the path. -#if !CHIP_CONFIG_USE_DATA_MODEL_INTERFACE - - // Without data model interface, we can query individual commands. - // Data model interface queries commands by a full path so we need endpointID as well. - // - // Since this is a performance update and group commands are never timed, - // missing this should not be that noticeable. - if (CommandNeedsTimedInvoke(clusterId, commandId)) - { - // Group commands are never timed. - return Status::Success; - } -#endif - // No check for `CommandIsFabricScoped` unlike in `ProcessCommandDataIB()` since group commands // always have an accessing fabric, by definition. diff --git a/src/app/InteractionModelEngine.cpp b/src/app/InteractionModelEngine.cpp index 49baa705d84ce1..0dd4df635b8e61 100644 --- a/src/app/InteractionModelEngine.cpp +++ b/src/app/InteractionModelEngine.cpp @@ -40,7 +40,6 @@ #include #include #include -#include #include #include #include @@ -51,11 +50,9 @@ #include #include -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE // TODO: defaulting to codegen should eventually be an application choice and not // hard-coded in the interaction model #include -#endif namespace chip { namespace app { @@ -87,8 +84,6 @@ bool MayHaveAccessibleEventPathForEndpointAndCluster(const ConcreteClusterPath & return (Access::GetAccessControl().Check(aSubjectDescriptor, requestPath, requiredPrivilege) == CHIP_NO_ERROR); } -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE - bool MayHaveAccessibleEventPathForEndpoint(DataModel::Provider * aProvider, EndpointId aEndpoint, const EventPathParams & aEventPath, const Access::SubjectDescriptor & aSubjectDescriptor) { @@ -132,72 +127,6 @@ bool MayHaveAccessibleEventPath(DataModel::Provider * aProvider, const EventPath return false; } -#else - -/** - * Helper to handle wildcard clusters in the event path. - */ -bool MayHaveAccessibleEventPathForEndpoint(EndpointId aEndpoint, const EventPathParams & aEventPath, - const Access::SubjectDescriptor & aSubjectDescriptor) -{ - if (aEventPath.HasWildcardClusterId()) - { - auto * endpointType = emberAfFindEndpointType(aEndpoint); - if (endpointType == nullptr) - { - // Not going to have any valid paths in here. - return false; - } - - for (decltype(endpointType->clusterCount) idx = 0; idx < endpointType->clusterCount; ++idx) - { - bool mayHaveAccessiblePath = MayHaveAccessibleEventPathForEndpointAndCluster( - ConcreteClusterPath(aEndpoint, endpointType->cluster[idx].clusterId), aEventPath, aSubjectDescriptor); - if (mayHaveAccessiblePath) - { - return true; - } - } - - return false; - } - - auto * cluster = emberAfFindServerCluster(aEndpoint, aEventPath.mClusterId); - if (cluster == nullptr) - { - // Nothing valid here. - return false; - } - return MayHaveAccessibleEventPathForEndpointAndCluster(ConcreteClusterPath(aEndpoint, cluster->clusterId), aEventPath, - aSubjectDescriptor); -} - -bool MayHaveAccessibleEventPath(const EventPathParams & aEventPath, const Access::SubjectDescriptor & aSubjectDescriptor) -{ - if (!aEventPath.HasWildcardEndpointId()) - { - // No need to check whether the endpoint is enabled, because - // emberAfFindEndpointType returns null for disabled endpoints. - return MayHaveAccessibleEventPathForEndpoint(aEventPath.mEndpointId, aEventPath, aSubjectDescriptor); - } - - for (uint16_t endpointIndex = 0; endpointIndex < emberAfEndpointCount(); ++endpointIndex) - { - if (!emberAfEndpointIndexIsEnabled(endpointIndex)) - { - continue; - } - if (MayHaveAccessibleEventPathForEndpoint(emberAfEndpointFromIndex(endpointIndex), aEventPath, aSubjectDescriptor)) - { - return true; - } - } - - // none of the paths matched - return false; -} -#endif - } // namespace class AutoReleaseSubscriptionInfoIterator @@ -245,15 +174,6 @@ CHIP_ERROR InteractionModelEngine::Init(Messaging::ExchangeManager * apExchangeM StatusIB::RegisterErrorFormatter(); -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL && CHIP_CONFIG_USE_DATA_MODEL_INTERFACE - ChipLogError(InteractionModel, "WARNING ┌────────────────────────────────────────────────────"); - ChipLogError(InteractionModel, "WARNING │ Interaction Model Engine running in 'Checked' mode."); - ChipLogError(InteractionModel, "WARNING │ This executes BOTH ember and data-model code paths."); - ChipLogError(InteractionModel, "WARNING │ which is inefficient and consumes more flash space."); - ChipLogError(InteractionModel, "WARNING │ This should be done for testing only."); - ChipLogError(InteractionModel, "WARNING └────────────────────────────────────────────────────"); -#endif - mState = State::kInitialized; return CHIP_NO_ERROR; } @@ -725,11 +645,7 @@ CHIP_ERROR InteractionModelEngine::ParseEventPaths(const Access::SubjectDescript // The definition of "valid path" is "path exists and ACL allows // access". We need to do some expansion of wildcards to handle that. -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE aHasValidEventPath = MayHaveAccessibleEventPath(mDataModelProvider, eventPath, aSubjectDescriptor); -#else - aHasValidEventPath = MayHaveAccessibleEventPath(eventPath, aSubjectDescriptor); -#endif } if (err == CHIP_ERROR_END_OF_TLV) @@ -1628,19 +1544,7 @@ CHIP_ERROR InteractionModelEngine::PushFrontAttributePathList(SingleLinkedListNo bool InteractionModelEngine::IsExistentAttributePath(const ConcreteAttributePath & path) { -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL - bool providerResult = GetDataModelProvider()->GetAttributeInfo(path).has_value(); - - bool emberResult = emberAfContainsAttribute(path.mEndpointId, path.mClusterId, path.mAttributeId); - - // Ensure that Provider interface and ember are IDENTICAL in attribute location (i.e. "check" mode) - VerifyOrDie(providerResult == emberResult); -#endif return GetDataModelProvider()->GetAttributeInfo(path).has_value(); -#else - return emberAfContainsAttribute(path.mEndpointId, path.mClusterId, path.mAttributeId); -#endif } void InteractionModelEngine::RemoveDuplicateConcreteAttributePath(SingleLinkedListNode *& aAttributePaths) @@ -1767,8 +1671,6 @@ CHIP_ERROR InteractionModelEngine::PushFront(SingleLinkedListNode *& aObjectL void InteractionModelEngine::DispatchCommand(CommandHandlerImpl & apCommandObj, const ConcreteCommandPath & aCommandPath, TLV::TLVReader & apPayload) { -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE - Access::SubjectDescriptor subjectDescriptor = apCommandObj.GetSubjectDescriptor(); DataModel::InvokeRequest request; @@ -1785,26 +1687,6 @@ void InteractionModelEngine::DispatchCommand(CommandHandlerImpl & apCommandObj, { apCommandObj.AddStatus(aCommandPath, status->GetStatusCode()); } -#else - CommandHandlerInterface * handler = - CommandHandlerInterfaceRegistry::Instance().GetCommandHandler(aCommandPath.mEndpointId, aCommandPath.mClusterId); - - if (handler) - { - CommandHandlerInterface::HandlerContext context(apCommandObj, aCommandPath, apPayload); - handler->InvokeCommand(context); - - // - // If the command was handled, don't proceed any further and return successfully. - // - if (context.mCommandHandled) - { - return; - } - } - - DispatchSingleClusterCommand(aCommandPath, apPayload, &apCommandObj); -#endif // CHIP_CONFIG_USE_DATA_MODEL_INTERFACE } Protocols::InteractionModel::Status InteractionModelEngine::ValidateCommandCanBeDispatched(const DataModel::InvokeRequest & request) @@ -1836,13 +1718,10 @@ Protocols::InteractionModel::Status InteractionModelEngine::CheckCommandAccess(c .endpoint = aRequest.path.mEndpointId, .requestType = Access::RequestType::kCommandInvokeRequest, .entityId = aRequest.path.mCommandId }; -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE std::optional commandInfo = mDataModelProvider->GetAcceptedCommandInfo(aRequest.path); Access::Privilege minimumRequiredPrivilege = commandInfo.has_value() ? commandInfo->invokePrivilege : Access::Privilege::kOperate; -#else - Access::Privilege minimumRequiredPrivilege = RequiredPrivilege::ForInvokeCommand(aRequest.path); -#endif + CHIP_ERROR err = Access::GetAccessControl().Check(*aRequest.subjectDescriptor, requestPath, minimumRequiredPrivilege); if (err != CHIP_NO_ERROR) { @@ -1858,17 +1737,12 @@ Protocols::InteractionModel::Status InteractionModelEngine::CheckCommandAccess(c Protocols::InteractionModel::Status InteractionModelEngine::CheckCommandFlags(const DataModel::InvokeRequest & aRequest) { -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE std::optional commandInfo = mDataModelProvider->GetAcceptedCommandInfo(aRequest.path); // This is checked by previous validations, so it should not happen VerifyOrDie(commandInfo.has_value()); const bool commandNeedsTimedInvoke = commandInfo->flags.Has(DataModel::CommandQualityFlags::kTimed); const bool commandIsFabricScoped = commandInfo->flags.Has(DataModel::CommandQualityFlags::kFabricScoped); -#else - const bool commandNeedsTimedInvoke = CommandNeedsTimedInvoke(aRequest.path.mClusterId, aRequest.path.mCommandId); - const bool commandIsFabricScoped = CommandIsFabricScoped(aRequest.path.mClusterId, aRequest.path.mCommandId); -#endif if (commandNeedsTimedInvoke && !aRequest.invokeFlags.Has(DataModel::InvokeFlags::kTimed)) { @@ -1893,13 +1767,9 @@ Protocols::InteractionModel::Status InteractionModelEngine::CheckCommandFlags(co Protocols::InteractionModel::Status InteractionModelEngine::CheckCommandExistence(const ConcreteCommandPath & aCommandPath) { -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE auto provider = GetDataModelProvider(); if (provider->GetAcceptedCommandInfo(aCommandPath).has_value()) { -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL - VerifyOrDie(ServerClusterCommandExists(aCommandPath) == Protocols::InteractionModel::Status::Success); -#endif return Protocols::InteractionModel::Status::Success; } @@ -1907,9 +1777,6 @@ Protocols::InteractionModel::Status InteractionModelEngine::CheckCommandExistenc // if (provider->GetClusterInfo(aCommandPath).has_value()) { -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL - VerifyOrDie(ServerClusterCommandExists(aCommandPath) == Protocols::InteractionModel::Status::UnsupportedCommand); -#endif return Protocols::InteractionModel::Status::UnsupportedCommand; // cluster exists, so command is invalid } @@ -1920,22 +1787,13 @@ Protocols::InteractionModel::Status InteractionModelEngine::CheckCommandExistenc { if (endpoint == aCommandPath.mEndpointId) { -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL - VerifyOrDie(ServerClusterCommandExists(aCommandPath) == Protocols::InteractionModel::Status::UnsupportedCluster); -#endif // endpoint exists, so cluster is invalid return Protocols::InteractionModel::Status::UnsupportedCluster; } } // endpoint not found -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL - VerifyOrDie(ServerClusterCommandExists(aCommandPath) == Protocols::InteractionModel::Status::UnsupportedEndpoint); -#endif return Protocols::InteractionModel::Status::UnsupportedEndpoint; -#else - return ServerClusterCommandExists(aCommandPath); -#endif } DataModel::Provider * InteractionModelEngine::SetDataModelProvider(DataModel::Provider * model) @@ -1974,14 +1832,12 @@ DataModel::Provider * InteractionModelEngine::SetDataModelProvider(DataModel::Pr DataModel::Provider * InteractionModelEngine::GetDataModelProvider() { -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE if (mDataModelProvider == nullptr) { // These should be called within the CHIP processing loop. assertChipStackLockedByCurrentThread(); SetDataModelProvider(CodegenDataModelProviderInstance()); } -#endif return mDataModelProvider; } diff --git a/src/app/WriteHandler.cpp b/src/app/WriteHandler.cpp index 7a1bbc5d57c668..1e129ad0af941c 100644 --- a/src/app/WriteHandler.cpp +++ b/src/app/WriteHandler.cpp @@ -28,7 +28,6 @@ #include #include #include -#include #include #include #include @@ -74,10 +73,8 @@ CHIP_ERROR WriteHandler::Init(DataModel::Provider * apProvider, WriteHandlerDele { VerifyOrReturnError(!mExchangeCtx, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(apWriteHandlerDelegate, CHIP_ERROR_INVALID_ARGUMENT); -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE VerifyOrReturnError(apProvider, CHIP_ERROR_INVALID_ARGUMENT); mDataModelProvider = apProvider; -#endif // CHIP_CONFIG_USE_DATA_MODEL_INTERFACE mDelegate = apWriteHandlerDelegate; MoveToState(State::Initialized); @@ -99,15 +96,12 @@ void WriteHandler::Close() DeliverFinalListWriteEnd(false /* wasSuccessful */); mExchangeCtx.Release(); mStateFlags.Clear(StateBits::kSuppressResponse); -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE mDataModelProvider = nullptr; -#endif // CHIP_CONFIG_USE_DATA_MODEL_INTERFACE MoveToState(State::Uninitialized); } std::optional WriteHandler::IsListAttributePath(const ConcreteAttributePath & path) { -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE if (mDataModelProvider == nullptr) { #if CHIP_CONFIG_DATA_MODEL_EXTRA_LOGGING @@ -123,15 +117,6 @@ std::optional WriteHandler::IsListAttributePath(const ConcreteAttributePat } return info->flags.Has(DataModel::AttributeQualityFlags::kListAttribute); -#else - constexpr uint8_t kListAttributeType = 0x48; - const auto attributeMetadata = GetAttributeMetadata(path); - if (attributeMetadata == nullptr) - { - return std::nullopt; - } - return (attributeMetadata->attributeType == kListAttributeType); -#endif } Status WriteHandler::HandleWriteRequestMessage(Messaging::ExchangeContext * apExchangeContext, @@ -613,9 +598,7 @@ Status WriteHandler::ProcessWriteRequest(System::PacketBufferHandle && aPayload, // our callees hand out Status as well. Status status = Status::InvalidAction; -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE mLastSuccessfullyWrittenPath = std::nullopt; -#endif // CHIP_CONFIG_USE_DATA_MODEL_INTERFACE reader.Init(std::move(aPayload)); @@ -773,7 +756,6 @@ CHIP_ERROR WriteHandler::WriteClusterData(const Access::SubjectDescriptor & aSub { // Writes do not have a checked-path. If data model interface is enabled (both checked and only version) // the write is done via the DataModel interface -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE VerifyOrReturnError(mDataModelProvider != nullptr, CHIP_ERROR_INCORRECT_STATE); DataModel::WriteAttributeRequest request; @@ -790,9 +772,6 @@ CHIP_ERROR WriteHandler::WriteClusterData(const Access::SubjectDescriptor & aSub mLastSuccessfullyWrittenPath = status.IsSuccess() ? std::make_optional(aPath) : std::nullopt; return AddStatusInternal(aPath, StatusIB(status.GetStatusCode())); -#else - return WriteSingleClusterData(aSubject, aPath, aData, this); -#endif // CHIP_CONFIG_USE_DATA_MODEL_INTERFACE } } // namespace app diff --git a/src/app/WriteHandler.h b/src/app/WriteHandler.h index 33c068b8cd02ea..fa1d324a5bd854 100644 --- a/src/app/WriteHandler.h +++ b/src/app/WriteHandler.h @@ -200,10 +200,8 @@ class WriteHandler : public Messaging::ExchangeDelegate Optional mProcessingAttributePath; Optional mACLCheckCache = NullOptional; -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE DataModel::Provider * mDataModelProvider = nullptr; std::optional mLastSuccessfullyWrittenPath; -#endif // This may be a "fake" pointer or a real delegate pointer, depending // on CHIP_CONFIG_STATIC_GLOBAL_INTERACTION_MODEL_ENGINE setting. diff --git a/src/app/chip_data_model.cmake b/src/app/chip_data_model.cmake index 11db6d4ec6c97b..75e2d8a349668a 100644 --- a/src/app/chip_data_model.cmake +++ b/src/app/chip_data_model.cmake @@ -70,17 +70,12 @@ endfunction() # function(chip_configure_data_model APP_TARGET) set(SCOPE PRIVATE) - set(ADD_EMBER_INTERFACE_FILES TRUE) - cmake_parse_arguments(ARG "SKIP_EMBER_INTERFACE" "SCOPE;ZAP_FILE;IDL" "EXTERNAL_CLUSTERS" ${ARGN}) + cmake_parse_arguments(ARG "" "SCOPE;ZAP_FILE;IDL" "EXTERNAL_CLUSTERS" ${ARGN}) if(ARG_SCOPE) set(SCOPE ${ARG_SCOPE}) endif() - if(ARG_SKIP_EMBER_INTERFACE) - set(ADD_EMBER_INTERFACE_FILES FALSE) - endif() - # CMAKE data model auto-includes the server side implementation target_sources(${APP_TARGET} ${SCOPE} ${CHIP_APP_BASE_DIR}/server/AclStorage.cpp @@ -173,10 +168,4 @@ function(chip_configure_data_model APP_TARGET) ${APP_GEN_FILES} ${APP_TEMPLATES_GEN_FILES} ) - - if(ADD_EMBER_INTERFACE_FILES) - target_sources(${APP_TARGET} ${SCOPE} - ${CHIP_APP_BASE_DIR}/util/ember-compatibility-functions.cpp - ) - endif() endfunction() diff --git a/src/app/chip_data_model.gni b/src/app/chip_data_model.gni index cc998948d835e7..9f4ed594ccb912 100644 --- a/src/app/chip_data_model.gni +++ b/src/app/chip_data_model.gni @@ -213,11 +213,6 @@ template("chip_data_model") { "${_app_root}/util/ember-io-storage.cpp", "${_app_root}/util/util.cpp", ] - - if (chip_use_data_model_interface != "enabled") { - # This applies to "check" or "disabled" (i.e. use ember-only or use ember for double-checking) - sources += [ "${_app_root}/util/ember-compatibility-functions.cpp" ] - } } if (defined(invoker.zap_file)) { diff --git a/src/app/clusters/microwave-oven-control-server/microwave-oven-control-server.cpp b/src/app/clusters/microwave-oven-control-server/microwave-oven-control-server.cpp index c012ddbb367eeb..75b7e7df182c21 100644 --- a/src/app/clusters/microwave-oven-control-server/microwave-oven-control-server.cpp +++ b/src/app/clusters/microwave-oven-control-server/microwave-oven-control-server.cpp @@ -24,7 +24,6 @@ #include #include #include -#include using namespace chip; using namespace chip::app; @@ -250,12 +249,8 @@ void Instance::HandleSetCookingParameters(HandlerContext & ctx, const Commands:: { ConcreteCommandPath commandPath(mEndpointId, OperationalState::Id, OperationalState::Commands::Start::Id); -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL - bool commandExists = ServerClusterCommandExists(commandPath) == Status::Success; -#else bool commandExists = InteractionModelEngine::GetInstance()->GetDataModelProvider()->GetAcceptedCommandInfo(commandPath).has_value(); -#endif VerifyOrExit( commandExists, status = Status::InvalidCommand; ChipLogError( Zcl, diff --git a/src/app/clusters/pump-configuration-and-control-server/pump-configuration-and-control-server.cpp b/src/app/clusters/pump-configuration-and-control-server/pump-configuration-and-control-server.cpp index 63bd6a29525724..749c80d7e8827b 100644 --- a/src/app/clusters/pump-configuration-and-control-server/pump-configuration-and-control-server.cpp +++ b/src/app/clusters/pump-configuration-and-control-server/pump-configuration-and-control-server.cpp @@ -25,7 +25,6 @@ #include #include #include -#include using namespace chip; using namespace chip::app; diff --git a/src/app/codegen-data-model-provider/tests/InteractionModelTemporaryOverrides.cpp b/src/app/codegen-data-model-provider/tests/InteractionModelTemporaryOverrides.cpp index e771827adf18f6..fd37e059e8249c 100644 --- a/src/app/codegen-data-model-provider/tests/InteractionModelTemporaryOverrides.cpp +++ b/src/app/codegen-data-model-provider/tests/InteractionModelTemporaryOverrides.cpp @@ -14,68 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include -#include #include -#include -#include -#include - -using chip::Protocols::InteractionModel::Status; - -// TODO: most of the functions here are part of EmberCompatibilityFunctions and is NOT decoupled -// from IM current, but it SHOULD be -// Open issue https://github.com/project-chip/connectedhomeip/issues/34137 for this work. -namespace chip { -namespace app { - -bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath) -{ - // TODO: this is just a noop which may be potentially invalid - return true; -} - -bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) -{ - // TODO: this is just a noop which may be potentially invalid - return true; -} - -const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aPath) -{ - return emberAfLocateAttributeMetadata(aPath.mEndpointId, aPath.mClusterId, aPath.mAttributeId); -} - -Status ServerClusterCommandExists(const ConcreteCommandPath & aCommandPath) -{ - // TODO: this is just a noop which may be potentially invalid - return Status::Success; -} - -Status CheckEventSupportStatus(const ConcreteEventPath & aPath) -{ - // TODO: this is just a noop which may be potentially invalid - return Status::Success; -} - -CHIP_ERROR WriteSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteDataAttributePath & aPath, - TLV::TLVReader & aReader, WriteHandler * apWriteHandler) -{ - // this is just to get things to compile. eventually this method should NOT be used - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * apEncoderState) -{ - // this is just to get things to compile. eventually this method should NOT be used - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -} // namespace app -} // namespace chip void MatterReportingAttributeChangeCallback(const chip::app::ConcreteAttributePath & aPath) { diff --git a/src/app/common_flags.gni b/src/app/common_flags.gni index 4dbbcb4fa3e145..30678dfe330f2f 100644 --- a/src/app/common_flags.gni +++ b/src/app/common_flags.gni @@ -25,22 +25,6 @@ declare_args() { # communicated to OperationalSessionSetup API consumers. chip_enable_busy_handling_for_operational_session_setup = true - # Data model interface usage: - # - disabled: does not use data model interface at all - # - check: runs BOTH datamodel and non-data-model (if possible) functionality and compares results - # - enabled: runs only the data model interface (does not use the legacy code) - if (matter_enable_recommended && current_os == "linux") { - chip_use_data_model_interface = "check" - } else { - chip_use_data_model_interface = "enabled" - } - - # Whether we call `chipDie` on DM `check` errors - # - # If/once the chip_use_data_model_interface flag is removed or does not support - # a `check` option, this should alwo be removed - chip_data_model_check_die_on_failure = false - # This controls if more logging is supposed to be enabled into the data models. # This is an optimization for small-flash size devices as extra logging requires # additional flash for messages & code for formatting. diff --git a/src/app/dynamic_server/AccessControl.cpp b/src/app/dynamic_server/AccessControl.cpp index d091b9ae1faea6..9f39040e00b056 100644 --- a/src/app/dynamic_server/AccessControl.cpp +++ b/src/app/dynamic_server/AccessControl.cpp @@ -25,11 +25,6 @@ #include #include -// TODO: this include is unclear as dynamic server should NOT link those. -// we should probably have some separate includes here for dynamic -// server -#include - using namespace chip; using namespace chip::Access; using namespace chip::app::Clusters; @@ -44,7 +39,16 @@ class DeviceTypeResolver : public Access::AccessControl::DeviceTypeResolver public: bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) override { - return app::IsDeviceTypeOnEndpoint(deviceType, endpoint); + chip::app::DataModel::Provider * model = chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); + + for (auto type = model->FirstDeviceType(endpoint); type.has_value(); type = model->NextDeviceType(endpoint, *type)) + { + if (type->deviceTypeId == deviceType) + { + return true; + } + } + return false; } }; diff --git a/src/app/dynamic_server/DynamicDispatcher.cpp b/src/app/dynamic_server/DynamicDispatcher.cpp index 0c9825d6792eb4..ba4525e2fc7add 100644 --- a/src/app/dynamic_server/DynamicDispatcher.cpp +++ b/src/app/dynamic_server/DynamicDispatcher.cpp @@ -15,8 +15,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include - #include #include #include @@ -43,9 +41,8 @@ /** * This file defines the APIs needed to handle interaction model dispatch. - * These are the APIs normally defined in - * src/app/util/ember-compatibility-functions.cpp and the generated - * IMClusterCommandHandler.cpp but we want a different implementation of these + * These are the APIs normally defined generated ember code, + * however we want a different implementation of these * to enable more dynamic behavior, since not all framework consumers will be * implementing the same server clusters. */ @@ -69,129 +66,6 @@ namespace app { using Access::SubjectDescriptor; using Protocols::InteractionModel::Status; -namespace { - -bool IsSupportedGlobalAttribute(AttributeId aAttribute) -{ - // We don't have any non-global attributes. - using namespace Globals::Attributes; - - for (auto & attr : GlobalAttributesNotInMetadata) - { - if (attr == aAttribute) - { - return true; - } - } - - switch (aAttribute) - { - case FeatureMap::Id: - FALLTHROUGH; - case ClusterRevision::Id: - return true; - } - - return false; -} - -Status DetermineAttributeStatus(const ConcreteAttributePath & aPath, bool aIsWrite) -{ - // TODO: Consider making this configurable for applications that are not - // trying to be an OTA provider, though in practice it just affects which - // error is returned. - if (aPath.mEndpointId != kSupportedEndpoint) - { - return Status::UnsupportedEndpoint; - } - - // TODO: Consider making this configurable for applications that are not - // trying to be an OTA provider, though in practice it just affects which - // error is returned. - if (aPath.mClusterId != OtaSoftwareUpdateProvider::Id) - { - return Status::UnsupportedCluster; - } - - if (!IsSupportedGlobalAttribute(aPath.mAttributeId)) - { - return Status::UnsupportedAttribute; - } - - // No permissions for this for read, and none of these are writable for - // write. The writable-or-not check happens before the ACL check. - return aIsWrite ? Status::UnsupportedWrite : Status::UnsupportedAccess; -} - -} // anonymous namespace - -CHIP_ERROR ReadSingleClusterData(const SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * aEncoderState) -{ - Status status = DetermineAttributeStatus(aPath, /* aIsWrite = */ false); - return aAttributeReports.EncodeAttributeStatus(aPath, StatusIB(status)); -} - -bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath) -{ - return DetermineAttributeStatus(aPath, /* aIsWrite = */ false) == Status::UnsupportedAccess; -} - -Status ServerClusterCommandExists(const ConcreteCommandPath & aPath) -{ - // TODO: Consider making this configurable for applications that are not - // trying to be an OTA provider. - using namespace OtaSoftwareUpdateProvider::Commands; - - if (aPath.mEndpointId != kSupportedEndpoint) - { - return Status::UnsupportedEndpoint; - } - - if (aPath.mClusterId != OtaSoftwareUpdateProvider::Id) - { - return Status::UnsupportedCluster; - } - - switch (aPath.mCommandId) - { - case QueryImage::Id: - FALLTHROUGH; - case ApplyUpdateRequest::Id: - FALLTHROUGH; - case NotifyUpdateApplied::Id: - return Status::Success; - } - - return Status::UnsupportedCommand; -} - -bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) -{ - // Will never be called anyway; we have no attributes. - return false; -} - -const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aConcreteClusterPath) -{ - // Note: This test does not make use of the real attribute metadata. - static EmberAfAttributeMetadata stub = { .defaultValue = EmberAfDefaultOrMinMaxAttributeValue(uint32_t(0)) }; - return &stub; -} - -bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) -{ - return false; -} - -CHIP_ERROR WriteSingleClusterData(const SubjectDescriptor & aSubjectDescriptor, const ConcreteDataAttributePath & aPath, - TLV::TLVReader & aReader, WriteHandler * aWriteHandler) -{ - Status status = DetermineAttributeStatus(aPath, /* aIsWrite = */ true); - return aWriteHandler->AddStatus(aPath, status); -} - void DispatchSingleClusterCommand(const ConcreteCommandPath & aPath, TLV::TLVReader & aReader, CommandHandler * aCommandObj) { // This command passed ServerClusterCommandExists so we know it's one of our @@ -240,11 +114,6 @@ void DispatchSingleClusterCommand(const ConcreteCommandPath & aPath, TLV::TLVRea } } -Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath) -{ - return Protocols::InteractionModel::Status::UnsupportedEvent; -} - } // namespace app } // namespace chip diff --git a/src/app/reporting/Engine.cpp b/src/app/reporting/Engine.cpp index 45ebdeb7f64c02..284aa6fa66db06 100644 --- a/src/app/reporting/Engine.cpp +++ b/src/app/reporting/Engine.cpp @@ -24,11 +24,9 @@ #include #include #include -#include #include #include #include -#include #include #include @@ -47,17 +45,12 @@ using Protocols::InteractionModel::Status; Status EventPathValid(DataModel::Provider * model, const ConcreteEventPath & eventPath) { -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE - if (!model->GetClusterInfo(eventPath).has_value()) { return model->EndpointExists(eventPath.mEndpointId) ? Status::UnsupportedCluster : Status::UnsupportedEndpoint; } return Status::Success; -#else - return CheckEventSupportStatus(eventPath); -#endif } } // namespace @@ -1046,8 +1039,7 @@ void Engine::MarkDirty(const AttributePathParams & path) } // namespace app } // namespace chip -// TODO: MatterReportingAttributeChangeCallback should just live in libCHIP, -// instead of being in ember-compatibility-functions. It does not depend on any +// TODO: MatterReportingAttributeChangeCallback should just live in libCHIP, It does not depend on any // app-specific generated bits. void __attribute__((weak)) MatterReportingAttributeChangeCallback(chip::EndpointId endpoint, chip::ClusterId clusterId, chip::AttributeId attributeId) diff --git a/src/app/reporting/Read-Checked.cpp b/src/app/reporting/Read-Checked.cpp deleted file mode 100644 index 6e10fae93cf58a..00000000000000 --- a/src/app/reporting/Read-Checked.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/* - * 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 - -#include -#include -#include -#include -#include -#include - -namespace chip { -namespace app { -namespace reporting { -namespace CheckedImpl { -namespace { - -using DataModel::ActionReturnStatus; - -/// Checkpoints and saves the state (including error state) for a -/// AttributeReportIBs::Builder -class ScopedAttributeReportIBsBuilderState -{ -public: - ScopedAttributeReportIBsBuilderState(AttributeReportIBs::Builder & builder) : mBuilder(builder), mError(mBuilder.GetError()) - { - mBuilder.Checkpoint(mCheckpoint); - } - - ~ScopedAttributeReportIBsBuilderState() - { - mBuilder.Rollback(mCheckpoint); - mBuilder.ResetError(mError); - } - -private: - AttributeReportIBs::Builder & mBuilder; - chip::TLV::TLVWriter mCheckpoint; - CHIP_ERROR mError; -}; - -} // namespace - -ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, const Access::SubjectDescriptor & subjectDescriptor, - bool isFabricFiltered, AttributeReportIBs::Builder & reportBuilder, - const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState) -{ - ChipLogDetail(DataManagement, " Cluster %" PRIx32 ", Attribute %" PRIx32 " is dirty", path.mClusterId, - path.mAttributeId); - DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, - DataModelCallbacks::OperationOrder::Pre, path); - - ActionReturnStatus statusEmber(CHIP_NO_ERROR); - uint32_t lengthWrittenEmber = 0; - - // a copy for DM logic only. Ember changes state directly - // IMPORTANT: the copy MUST be taken BEFORE ember processes/changes encoderState inline. - AttributeEncodeState stateDm(encoderState); - - { - ScopedAttributeReportIBsBuilderState builderState(reportBuilder); // temporary only - statusEmber = - EmberImpl::RetrieveClusterData(dataModel, subjectDescriptor, isFabricFiltered, reportBuilder, path, encoderState); - lengthWrittenEmber = reportBuilder.GetWriter()->GetLengthWritten(); - } - - ActionReturnStatus statusDm = DataModelImpl::RetrieveClusterData(dataModel, subjectDescriptor, isFabricFiltered, reportBuilder, - path, encoderState != nullptr ? &stateDm : nullptr); - - if (statusEmber != statusDm) - { - ActionReturnStatus::StringStorage buffer; - - // Note log + chipDie instead of VerifyOrDie so that breakpoints (and usage of rr) - // is easier to debug. - ChipLogError(Test, "Different return codes between ember and DM"); - ChipLogError(Test, " Ember status: %s", statusEmber.c_str(buffer)); - ChipLogError(Test, " DM status: %s", statusDm.c_str(buffer)); - - // For time-dependent data, we may have size differences here: one data fitting in buffer - // while another not, resulting in different errors (success vs out of space). - // - // Make unit tests strict; otherwise allow it with potentially odd mismatch errors - // (in which case logs will be odd, however we also expect Checked versions to only - // run for a short period until we switch over to either ember or DM completely). -#if CHIP_CONFIG_DATA_MODEL_CHECK_DIE_ON_FAILURE - chipDie(); -#endif - } - - // data should be identical for most cases EXCEPT that for time-deltas (e.g. seconds since boot or similar) - // it may actually differ. As a result, the amount of data written in bytes MUST be the same, however if the rest of the - // data is not the same, we just print it out as a warning for manual inspection - // - // We have no direct access to TLV buffer data (especially given backing store splits) - // so for now we check that data length was identical. - // - // NOTE: RetrieveClusterData is responsible for encoding StatusIB errors in case of failures - // so we validate length written requirements for BOTH success and failure. - // - // NOTE: data length is NOT reliable if the data content differs in encoding length. E.g. numbers changing - // from 0xFF to 0x100 or similar will use up more space. - // For unit tests we make the validation strict, however for runtime we just report an - // error for different sizes. - if (lengthWrittenEmber != reportBuilder.GetWriter()->GetLengthWritten()) - { - ChipLogError(Test, "Different written length: %" PRIu32 " (Ember) vs %" PRIu32 " (DataModel)", lengthWrittenEmber, - reportBuilder.GetWriter()->GetLengthWritten()); -#if CHIP_CONFIG_DATA_MODEL_CHECK_DIE_ON_FAILURE - chipDie(); -#endif - } - - // For chunked reads, the encoder state MUST be identical (since this is what controls - // where chunking resumes). - if (statusEmber.IsOutOfSpaceEncodingResponse()) - { - // Encoder state MUST match on partial reads (used by chunking) - // specifically ReadViaAccessInterface in ember-compatibility-functions only - // sets the encoder state in case an error occurs. - if (encoderState != nullptr) - { - if (encoderState->AllowPartialData() != stateDm.AllowPartialData()) - { - ChipLogError(Test, "Different partial data"); - // NOTE: die on unit tests only, since partial data size may differ across - // time-dependent data (very rarely because fast code, but still possible) -#if CHIP_CONFIG_DATA_MODEL_CHECK_DIE_ON_FAILURE - chipDie(); -#endif - } - if (encoderState->CurrentEncodingListIndex() != stateDm.CurrentEncodingListIndex()) - { - ChipLogError(Test, "Different partial data"); - // NOTE: die on unit tests only, since partial data size may differ across - // time-dependent data (very rarely because fast code, but still possible) -#if CHIP_CONFIG_DATA_MODEL_CHECK_DIE_ON_FAILURE - chipDie(); -#endif - } - } - } - - DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, - DataModelCallbacks::OperationOrder::Post, path); - - return statusDm; -} - -bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const ConcreteClusterPath & path, DataVersion dataVersion) -{ - bool emberResult = EmberImpl::IsClusterDataVersionEqualTo(dataModel, path, dataVersion); - bool dmResult = DataModelImpl::IsClusterDataVersionEqualTo(dataModel, path, dataVersion); - - if (emberResult != dmResult) - { - ChipLogError(Test, "Different data model check result between ember (%s) and data model provider(%s)", - emberResult ? "TRUE" : "FALSE", dmResult ? "TRUE" : "FALSE"); -#if CHIP_CONFIG_DATA_MODEL_CHECK_DIE_ON_FAILURE - chipDie(); -#endif - } - - return dmResult; -} - -} // namespace CheckedImpl -} // namespace reporting -} // namespace app -} // namespace chip diff --git a/src/app/reporting/Read-Checked.h b/src/app/reporting/Read-Checked.h deleted file mode 100644 index 63ca9bf88d9d6b..00000000000000 --- a/src/app/reporting/Read-Checked.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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. - */ -#pragma once - -#include "app/data-model-provider/ActionReturnStatus.h" -#include -#include -#include -#include -#include - -namespace chip { -namespace app { -namespace reporting { -namespace CheckedImpl { - -DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, - const Access::SubjectDescriptor & subjectDescriptor, bool isFabricFiltered, - AttributeReportIBs::Builder & reportBuilder, - const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState); - -bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const ConcreteClusterPath & path, DataVersion dataVersion); - -} // namespace CheckedImpl -} // namespace reporting -} // namespace app -} // namespace chip diff --git a/src/app/reporting/Read-DataModel.h b/src/app/reporting/Read-DataModel.h deleted file mode 100644 index ff4801b64cf832..00000000000000 --- a/src/app/reporting/Read-DataModel.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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. - */ -#pragma once - -#include "app/data-model-provider/ActionReturnStatus.h" -#include -#include -#include -#include -#include -#include - -namespace chip { -namespace app { -namespace reporting { -namespace DataModelImpl { - -DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, - const Access::SubjectDescriptor & subjectDescriptor, bool isFabricFiltered, - AttributeReportIBs::Builder & reportBuilder, - const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState); - -bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const ConcreteClusterPath & path, DataVersion dataVersion); - -} // namespace DataModelImpl -} // namespace reporting -} // namespace app -} // namespace chip diff --git a/src/app/reporting/Read-Ember.cpp b/src/app/reporting/Read-Ember.cpp deleted file mode 100644 index e07df08617f4b5..00000000000000 --- a/src/app/reporting/Read-Ember.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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 - -#include -#include -#include -#include - -namespace chip { -namespace app { -namespace reporting { -namespace EmberImpl { - -DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, - const Access::SubjectDescriptor & subjectDescriptor, bool isFabricFiltered, - AttributeReportIBs::Builder & reportBuilder, - const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState) -{ - // Odd ifdef is to only do this if the `Read-Check` does not do it already. -#if !CHIP_CONFIG_USE_DATA_MODEL_INTERFACE - ChipLogDetail(DataManagement, " Cluster %" PRIx32 ", Attribute %" PRIx32 " is dirty", path.mClusterId, - path.mAttributeId); - - DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, - DataModelCallbacks::OperationOrder::Pre, path); -#endif // !CHIP_CONFIG_USE_DATA_MODEL_INTERFACE - - ReturnErrorOnFailure(ReadSingleClusterData(subjectDescriptor, isFabricFiltered, path, reportBuilder, encoderState)); - - // Odd ifdef is to only do this if the `Read-Check` does not do it already. -#if !CHIP_CONFIG_USE_DATA_MODEL_INTERFACE - DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, - DataModelCallbacks::OperationOrder::Post, path); -#endif // !CHIP_CONFIG_USE_DATA_MODEL_INTERFACE - - return CHIP_NO_ERROR; -} - -bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const ConcreteClusterPath & path, DataVersion dataVersion) -{ - return IsClusterDataVersionEqual(path, dataVersion); -} - -} // namespace EmberImpl -} // namespace reporting -} // namespace app -} // namespace chip diff --git a/src/app/reporting/Read-Ember.h b/src/app/reporting/Read-Ember.h deleted file mode 100644 index 4aaf2f1fdbde6e..00000000000000 --- a/src/app/reporting/Read-Ember.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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. - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace chip { -namespace app { -namespace reporting { -namespace EmberImpl { - -DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, - const Access::SubjectDescriptor & subjectDescriptor, bool isFabricFiltered, - AttributeReportIBs::Builder & reportBuilder, - const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState); - -bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const ConcreteClusterPath & path, DataVersion dataVersion); - -} // namespace EmberImpl -} // namespace reporting -} // namespace app -} // namespace chip diff --git a/src/app/reporting/Read-DataModel.cpp b/src/app/reporting/Read.cpp similarity index 93% rename from src/app/reporting/Read-DataModel.cpp rename to src/app/reporting/Read.cpp index 584536bdeb9606..db55b14cd257b3 100644 --- a/src/app/reporting/Read-DataModel.cpp +++ b/src/app/reporting/Read.cpp @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include +#include #include #include @@ -26,20 +26,17 @@ namespace chip { namespace app { namespace reporting { -namespace DataModelImpl { +namespace Impl { DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, const Access::SubjectDescriptor & subjectDescriptor, bool isFabricFiltered, AttributeReportIBs::Builder & reportBuilder, const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState) { - // Odd ifdef is to only do this if the `Read-Check` does not do it already. -#if !CHIP_CONFIG_USE_EMBER_DATA_MODEL ChipLogDetail(DataManagement, " Cluster %" PRIx32 ", Attribute %" PRIx32 " is dirty", path.mClusterId, path.mAttributeId); DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, DataModelCallbacks::OperationOrder::Pre, path); -#endif // !CHIP_CONFIG_USE_EMBER_DATA_MODEL DataModel::ReadAttributeRequest readRequest; @@ -70,7 +67,6 @@ DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataMode if (status.IsSuccess()) { // Odd ifdef is to only do this if the `Read-Check` does not do it already. -#if !CHIP_CONFIG_USE_EMBER_DATA_MODEL // TODO: this callback being only executed on success is awkward. The Write callback is always done // for both read and write. // @@ -78,7 +74,6 @@ DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataMode // call this. DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, DataModelCallbacks::OperationOrder::Post, path); -#endif // !CHIP_CONFIG_USE_EMBER_DATA_MODEL return status; } @@ -115,7 +110,7 @@ bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const Concrete return (info->dataVersion == dataVersion); } -} // namespace DataModelImpl +} // namespace Impl } // namespace reporting } // namespace app } // namespace chip diff --git a/src/app/reporting/Read.h b/src/app/reporting/Read.h index c568c5356ab472..6731addfab736e 100644 --- a/src/app/reporting/Read.h +++ b/src/app/reporting/Read.h @@ -16,31 +16,25 @@ */ #pragma once -#include - -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL && CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -#include -#else -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -#include -#else -#include -#endif // CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -#endif // CHIP_CONFIG_USE_EMBER_DATA_MODEL && CHIP_CONFIG_USE_DATA_MODEL_INTERFACE +#include +#include +#include +#include +#include +#include namespace chip { namespace app { namespace reporting { +namespace Impl { + +DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, + const Access::SubjectDescriptor & subjectDescriptor, bool isFabricFiltered, + AttributeReportIBs::Builder & reportBuilder, + const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState); -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL && CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -namespace Impl = CheckedImpl; -#else -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -namespace Impl = DataModelImpl; -#else -namespace Impl = EmberImpl; -#endif // CHIP_CONFIG_USE_DATA_MODEL_INTERFACE -#endif // CHIP_CONFIG_USE_EMBER_DATA_MODEL && CHIP_CONFIG_USE_DATA_MODEL_INTERFACE +bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const ConcreteClusterPath & path, DataVersion dataVersion); +} // namespace Impl } // namespace reporting } // namespace app diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index 9a32401bc7a47d..cfb8d21de3a130 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -26,7 +26,6 @@ #include #include #include -#include #if CONFIG_NETWORK_LAYER_BLE #include @@ -83,7 +82,6 @@ using chip::Transport::TcpListenParameters; namespace { -#if CHIP_CONFIG_USE_DATA_MODEL_INTERFACE class DeviceTypeResolver : public chip::Access::AccessControl::DeviceTypeResolver { public: @@ -95,30 +93,12 @@ class DeviceTypeResolver : public chip::Access::AccessControl::DeviceTypeResolve { if (type->deviceTypeId == deviceType) { -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL - VerifyOrDie(chip::app::IsDeviceTypeOnEndpoint(deviceType, endpoint)); -#endif // CHIP_CONFIG_USE_EMBER_DATA_MODEL return true; } } -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL - VerifyOrDie(!chip::app::IsDeviceTypeOnEndpoint(deviceType, endpoint)); -#endif // CHIP_CONFIG_USE_EMBER_DATA_MODEL return false; } } sDeviceTypeResolver; -#else // CHIP_CONFIG_USE_DATA_MODEL_INTERFACE - -// Ember implementation of the device type resolver -class DeviceTypeResolver : public chip::Access::AccessControl::DeviceTypeResolver -{ -public: - bool IsDeviceTypeOnEndpoint(chip::DeviceTypeId deviceType, chip::EndpointId endpoint) override - { - return chip::app::IsDeviceTypeOnEndpoint(deviceType, endpoint); - } -} sDeviceTypeResolver; -#endif } // namespace diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index 9ebed234e5b45e..03dadc061740a6 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -171,7 +171,7 @@ source_set("app-test-stubs") { "test-ember-api.cpp", "test-ember-api.h", - # The overrides in these files are overrides from ember-compatibility-functions + # The overrides in these files are overrides from ember generated code # and the data model interface is NOT aware of such functionality # # TODO: ideally tests should have been written via mock ember, however mock ember did diff --git a/src/app/tests/TestCommandInteraction.cpp b/src/app/tests/TestCommandInteraction.cpp index a44d76d1fc6258..4535a51dff4b1e 100644 --- a/src/app/tests/TestCommandInteraction.cpp +++ b/src/app/tests/TestCommandInteraction.cpp @@ -193,7 +193,7 @@ struct BadFields } }; -Protocols::InteractionModel::Status ServerClusterCommandExists(const ConcreteCommandPath & aRequestCommandPath) +static Protocols::InteractionModel::Status ServerClusterCommandExists(const ConcreteCommandPath & aRequestCommandPath) { // Mock cluster catalog, only support commands on one cluster on one endpoint. if (aRequestCommandPath.mEndpointId != kTestEndpointId) diff --git a/src/app/tests/integration/chip_im_initiator.cpp b/src/app/tests/integration/chip_im_initiator.cpp index 48a66cb7fc2bba..70a18b8796953e 100644 --- a/src/app/tests/integration/chip_im_initiator.cpp +++ b/src/app/tests/integration/chip_im_initiator.cpp @@ -617,11 +617,6 @@ void SubscribeRequestTimerHandler(chip::System::Layer * systemLayer, void * appS namespace chip { namespace app { -Protocols::InteractionModel::Status ServerClusterCommandExists(const ConcreteCommandPath & aCommandPath) -{ - // Always return success in test. - return Protocols::InteractionModel::Status::Success; -} void DispatchSingleClusterCommand(const ConcreteCommandPath & aCommandPath, chip::TLV::TLVReader & aReader, CommandHandler * apCommandObj) @@ -629,68 +624,6 @@ void DispatchSingleClusterCommand(const ConcreteCommandPath & aCommandPath, chip // Nothing todo. } -CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * apEncoderState) -{ - AttributeReportIB::Builder & attributeReport = aAttributeReports.CreateAttributeReport(); - ReturnErrorOnFailure(aAttributeReports.GetError()); - AttributeStatusIB::Builder & attributeStatus = attributeReport.CreateAttributeStatus(); - ReturnErrorOnFailure(attributeReport.GetError()); - AttributePathIB::Builder & attributePath = attributeStatus.CreatePath(); - ReturnErrorOnFailure(attributeStatus.GetError()); - attributePath.Endpoint(aPath.mEndpointId).Cluster(aPath.mClusterId).Attribute(aPath.mAttributeId).EndOfAttributePathIB(); - ReturnErrorOnFailure(attributePath.GetError()); - StatusIB::Builder & errorStatus = attributeStatus.CreateErrorStatus(); - errorStatus.EncodeStatusIB(StatusIB(Protocols::InteractionModel::Status::UnsupportedAttribute)); - ReturnErrorOnFailure(errorStatus.GetError()); - attributeStatus.EndOfAttributeStatusIB(); - ReturnErrorOnFailure(attributeStatus.GetError()); - return attributeReport.EndOfAttributeReportIB(); -} - -const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aConcreteClusterPath) -{ - // Note: This test does not make use of the real attribute metadata. - static EmberAfAttributeMetadata stub = { .defaultValue = EmberAfDefaultOrMinMaxAttributeValue(uint32_t(0)) }; - return &stub; -} - -bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath) -{ - return true; -} - -Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath) -{ - return Protocols::InteractionModel::Status::Success; -} - -CHIP_ERROR WriteSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteDataAttributePath & aPath, - TLV::TLVReader & aReader, WriteHandler *) -{ - if (aPath.mClusterId != kTestClusterId || aPath.mEndpointId != kTestEndpointId) - { - return CHIP_ERROR_INVALID_ARGUMENT; - } - - if (aReader.GetLength() != 0) - { - chip::TLV::Debug::Dump(aReader, TLVPrettyPrinter); - } - return CHIP_NO_ERROR; -} - -bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) -{ - return true; -} - -bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) -{ - return false; -} - } // namespace app } // namespace chip diff --git a/src/app/tests/integration/chip_im_responder.cpp b/src/app/tests/integration/chip_im_responder.cpp index b65710d06894b1..12996affd398ca 100644 --- a/src/app/tests/integration/chip_im_responder.cpp +++ b/src/app/tests/integration/chip_im_responder.cpp @@ -25,6 +25,7 @@ */ #include "MockEvents.h" +#include "common.h" #include #include #include @@ -76,43 +77,13 @@ class TestTLVDataEncoder : public DataModel::EncodableToTLV // // We cannot just say "every attribut exist, every device on every endpoint exists, // every data version compare is the same etc.". -// -// The following override implementation need changing: -// - ServerClusterCommandExists - should have a proper data mmodel -// - ConcreteAttributePathExists - cannot say "Yes" on all paths when query for EP/Cluster would fail -// - CheckEventSupportStatus - cannot say yes for invalid endpoints/clusters -// - IsClusterDataVersionEqual returning true on everything is odd -// - IsDeviceTypeOnEndpoint returning true on every value seems odd - -Protocols::InteractionModel::Status ServerClusterCommandExists(const ConcreteCommandPath & aCommandPath) -{ - // The Mock cluster catalog -- only have one command on one cluster on one endpoint. - using Protocols::InteractionModel::Status; - - if (aCommandPath.mEndpointId != kTestEndpointId) - { - return Status::UnsupportedEndpoint; - } - - if (aCommandPath.mClusterId != kTestClusterId) - { - return Status::UnsupportedCluster; - } - - if (aCommandPath.mCommandId != kTestCommandId) - { - return Status::UnsupportedCommand; - } - - return Status::Success; -} void DispatchSingleClusterCommand(const ConcreteCommandPath & aRequestCommandPath, chip::TLV::TLVReader & aReader, CommandHandler * apCommandObj) { static bool statusCodeFlipper = false; - if (ServerClusterCommandExists(aRequestCommandPath) != Protocols::InteractionModel::Status::Success) + if (aRequestCommandPath != ConcreteCommandPath(kTestEndpointId, kTestClusterId, kTestCommandId)) { return; } @@ -144,49 +115,6 @@ void DispatchSingleClusterCommand(const ConcreteCommandPath & aRequestCommandPat statusCodeFlipper = !statusCodeFlipper; } -CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * apEncoderState) -{ - return AttributeValueEncoder(aAttributeReports, aSubjectDescriptor, aPath, 0).Encode(kTestFieldValue1); -} - -bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath) -{ - return true; -} - -Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath) -{ - return Protocols::InteractionModel::Status::Success; -} - -const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aConcreteClusterPath) -{ - // Note: This test does not make use of the real attribute metadata. - static EmberAfAttributeMetadata stub = { .defaultValue = EmberAfDefaultOrMinMaxAttributeValue(uint32_t(0)) }; - return &stub; -} - -CHIP_ERROR WriteSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteDataAttributePath & aPath, - TLV::TLVReader & aReader, WriteHandler * apWriteHandler) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - ConcreteDataAttributePath attributePath(2, 3, 4); - err = apWriteHandler->AddStatus(attributePath, Protocols::InteractionModel::Status::Success); - return err; -} - -bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) -{ - return true; -} - -bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) -{ - return false; -} - } // namespace app } // namespace chip diff --git a/src/app/tests/test-interaction-model-api.cpp b/src/app/tests/test-interaction-model-api.cpp index 33097d320bc880..d263e251d2da7d 100644 --- a/src/app/tests/test-interaction-model-api.cpp +++ b/src/app/tests/test-interaction-model-api.cpp @@ -60,78 +60,15 @@ class TestOnlyAttributeValueDecoderAccessor AttributeValueDecoder & mDecoder; }; -// Used by the code in TestWriteInteraction.cpp (and generally tests that interact with the WriteHandler may need this). -const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aConcreteClusterPath) -{ - // Note: This test does not make use of the real attribute metadata. - static EmberAfAttributeMetadata stub = { .defaultValue = EmberAfDefaultOrMinMaxAttributeValue(uint32_t(0)) }; - return &stub; -} - -// Used by the code in TestWriteInteraction.cpp (and generally tests that interact with the WriteHandler may need this). -CHIP_ERROR WriteSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteDataAttributePath & aPath, - TLV::TLVReader & aReader, WriteHandler * aWriteHandler) -{ - if (aPath.mDataVersion.HasValue() && aPath.mDataVersion.Value() == Test::kRejectedDataVersion) - { - return aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::DataVersionMismatch); - } - - TLV::TLVWriter writer; - writer.Init(chip::Test::attributeDataTLV); - writer.CopyElement(TLV::AnonymousTag(), aReader); - chip::Test::attributeDataTLVLen = writer.GetLengthWritten(); - return aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Success); -} - -// Used by the code in TestAclAttribute.cpp (and generally tests that interact with the InteractionModelEngine may need this). -bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath) -{ - return aPath.mClusterId != Test::kTestDeniedClusterId1; -} - -// Used by the code in TestAclAttribute.cpp (and generally tests that interact with the InteractionModelEngine may need this). -Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath) -{ - if (aPath.mClusterId == Test::kTestDeniedClusterId1) - { - return Protocols::InteractionModel::Status::UnsupportedCluster; - } - - return Protocols::InteractionModel::Status::Success; -} - -// strong defintion in TestCommandInteraction.cpp -__attribute__((weak)) Protocols::InteractionModel::Status -ServerClusterCommandExists(const ConcreteCommandPath & aRequestCommandPath) -{ - // Mock cluster catalog, only support commands on one cluster on one endpoint. - using Protocols::InteractionModel::Status; - - return Status::Success; -} - // strong defintion in TestCommandInteraction.cpp __attribute__((weak)) void DispatchSingleClusterCommand(const ConcreteCommandPath & aRequestCommandPath, chip::TLV::TLVReader & aReader, CommandHandler * apCommandObj) {} // Used by the code in TestReadInteraction.cpp (and generally tests that interact with the Reporting Engine may need this). -bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) -{ - return (Test::kTestDataVersion1 == aRequiredVersion); -} - -// Used by the code in TestReadInteraction.cpp. -bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) -{ - return false; -} - -// Used by the code in TestReadInteraction.cpp (and generally tests that interact with the Reporting Engine may need this). -CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * apEncoderState) +static CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, + const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, + AttributeEncodeState * apEncoderState) { if (aPath.mClusterId >= Test::kMockEndpointMin) { diff --git a/src/app/tests/test-interaction-model-api.h b/src/app/tests/test-interaction-model-api.h index df410c656b9b03..0e0fd2c0e5b661 100644 --- a/src/app/tests/test-interaction-model-api.h +++ b/src/app/tests/test-interaction-model-api.h @@ -81,25 +81,11 @@ extern size_t attributeDataTLVLen; } // namespace Test namespace app { -CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * apEncoderState); - bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion); -CHIP_ERROR WriteSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteDataAttributePath & aPath, - TLV::TLVReader & aReader, WriteHandler * aWriteHandler); -const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aConcreteClusterPath); - -Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath); - -Protocols::InteractionModel::Status ServerClusterCommandExists(const ConcreteCommandPath & aRequestCommandPath); - void DispatchSingleClusterCommand(const ConcreteCommandPath & aRequestCommandPath, chip::TLV::TLVReader & aReader, CommandHandler * apCommandObj); -bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint); - /// A customized class for read/write/invoke that matches functionality /// with the ember-compatibility-functions functionality here. /// diff --git a/src/app/util/ember-compatibility-functions.cpp b/src/app/util/ember-compatibility-functions.cpp deleted file mode 100644 index e50b55975f9de8..00000000000000 --- a/src/app/util/ember-compatibility-functions.cpp +++ /dev/null @@ -1,814 +0,0 @@ -/* - * - * Copyright (c) 2021-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. - */ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -#include - -using chip::Protocols::InteractionModel::Status; - -using namespace chip; -using namespace chip::app; -using namespace chip::Access; -using namespace chip::app::Compatibility; -using namespace chip::app::Compatibility::Internal; - -namespace chip { -namespace app { -namespace { - -template -CHIP_ERROR attributeBufferToNumericTlvData(TLV::TLVWriter & writer, bool isNullable) -{ - typename NumericAttributeTraits::StorageType value; - memcpy(&value, gEmberAttributeIOBufferSpan.data(), sizeof(value)); - TLV::Tag tag = TLV::ContextTag(AttributeDataIB::Tag::kData); - if (isNullable && NumericAttributeTraits::IsNullValue(value)) - { - return writer.PutNull(tag); - } - - if (!NumericAttributeTraits::CanRepresentValue(isNullable, value)) - { - return CHIP_ERROR_INCORRECT_STATE; - } - - return NumericAttributeTraits::Encode(writer, tag, value); -} - -} // anonymous namespace - -Protocols::InteractionModel::Status ServerClusterCommandExists(const ConcreteCommandPath & aCommandPath) -{ - using Protocols::InteractionModel::Status; - - const EmberAfEndpointType * type = emberAfFindEndpointType(aCommandPath.mEndpointId); - if (type == nullptr) - { - return Status::UnsupportedEndpoint; - } - - const EmberAfCluster * cluster = emberAfFindClusterInType(type, aCommandPath.mClusterId, CLUSTER_MASK_SERVER); - if (cluster == nullptr) - { - return Status::UnsupportedCluster; - } - - auto * commandHandler = - CommandHandlerInterfaceRegistry::Instance().GetCommandHandler(aCommandPath.mEndpointId, aCommandPath.mClusterId); - if (commandHandler) - { - struct Context - { - bool commandExists; - CommandId targetCommand; - } context{ false, aCommandPath.mCommandId }; - - CHIP_ERROR err = commandHandler->EnumerateAcceptedCommands( - aCommandPath, - [](CommandId command, void * closure) -> Loop { - auto * ctx = static_cast(closure); - if (ctx->targetCommand == command) - { - ctx->commandExists = true; - return Loop::Break; - } - return Loop::Continue; - }, - &context); - - // We now have three cases: - // 1) handler returned CHIP_ERROR_NOT_IMPLEMENTED. In that case we - // should fall back to looking at cluster->acceptedCommandList - // 2) handler returned success. In that case, the handler is the source - // of truth about the set of accepted commands, and - // context.commandExists indicates whether a aCommandPath.mCommandId - // was in the set, and we should return either Success or - // UnsupportedCommand accordingly. - // 3) Some other status was returned. In this case we should probably - // err on the side of not allowing the command, since we have no idea - // whether to allow it or not. - if (err != CHIP_ERROR_NOT_IMPLEMENTED) - { - if (err == CHIP_NO_ERROR) - { - return context.commandExists ? Status::Success : Status::UnsupportedCommand; - } - - return Status::Failure; - } - } - - for (const CommandId * cmd = cluster->acceptedCommandList; cmd != nullptr && *cmd != kInvalidCommandId; cmd++) - { - if (*cmd == aCommandPath.mCommandId) - { - return Status::Success; - } - } - - return Status::UnsupportedCommand; -} - -namespace { - -CHIP_ERROR ReadClusterDataVersion(const ConcreteClusterPath & aConcreteClusterPath, DataVersion & aDataVersion) -{ - DataVersion * version = emberAfDataVersionStorage(aConcreteClusterPath); - if (version == nullptr) - { - ChipLogError(DataManagement, "Endpoint %x, Cluster " ChipLogFormatMEI " not found in ReadClusterDataVersion!", - aConcreteClusterPath.mEndpointId, ChipLogValueMEI(aConcreteClusterPath.mClusterId)); - return CHIP_ERROR_NOT_FOUND; - } - aDataVersion = *version; - return CHIP_NO_ERROR; -} - -// Helper function for trying to read an attribute value via an -// AttributeAccessInterface. On failure, the read has failed. On success, the -// aTriedEncode outparam is set to whether the AttributeAccessInterface tried to encode a value. -CHIP_ERROR ReadViaAccessInterface(const SubjectDescriptor & subjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * aEncoderState, AttributeAccessInterface * aAccessInterface, - bool * aTriedEncode) -{ - AttributeEncodeState state(aEncoderState); - DataVersion version = 0; - ReturnErrorOnFailure(ReadClusterDataVersion(aPath, version)); - AttributeValueEncoder valueEncoder(aAttributeReports, subjectDescriptor, aPath, version, aIsFabricFiltered, state); - CHIP_ERROR err = aAccessInterface->Read(aPath, valueEncoder); - - if (err == CHIP_IM_GLOBAL_STATUS(UnsupportedRead) && aPath.mExpanded) - { - // - // Set this to true to ensure our caller will return immediately without proceeding further. - // - *aTriedEncode = true; - return CHIP_NO_ERROR; - } - - if (err != CHIP_NO_ERROR) - { - // If the err is not CHIP_NO_ERROR, means the encoding was aborted, then the valueEncoder may save its state. - // The state is used by list chunking feature for now. - if (aEncoderState != nullptr) - { - *aEncoderState = valueEncoder.GetState(); - } - return err; - } - - *aTriedEncode = valueEncoder.TriedEncode(); - return CHIP_NO_ERROR; -} - -// Determine the appropriate status response for an unsupported attribute for -// the given path. Must be called when the attribute is known to be unsupported -// (i.e. we found no attribute metadata for it). -Protocols::InteractionModel::Status UnsupportedAttributeStatus(const ConcreteAttributePath & aPath) -{ - using Protocols::InteractionModel::Status; - - const EmberAfEndpointType * type = emberAfFindEndpointType(aPath.mEndpointId); - if (type == nullptr) - { - return Status::UnsupportedEndpoint; - } - - const EmberAfCluster * cluster = emberAfFindClusterInType(type, aPath.mClusterId, CLUSTER_MASK_SERVER); - if (cluster == nullptr) - { - return Status::UnsupportedCluster; - } - - // Since we know the attribute is unsupported and the endpoint/cluster are - // OK, this is the only option left. - return Status::UnsupportedAttribute; -} - -// Will set at most one of the out-params (aAttributeCluster or -// aAttributeMetadata) to non-null. Both null means attribute not supported, -// aAttributeCluster non-null means this is a supported global attribute that -// does not have metadata. -void FindAttributeMetadata(const ConcreteAttributePath & aPath, const EmberAfCluster ** aAttributeCluster, - const EmberAfAttributeMetadata ** aAttributeMetadata) -{ - *aAttributeCluster = nullptr; - *aAttributeMetadata = nullptr; - - for (auto & attr : GlobalAttributesNotInMetadata) - { - if (attr == aPath.mAttributeId) - { - *aAttributeCluster = emberAfFindServerCluster(aPath.mEndpointId, aPath.mClusterId); - return; - } - } - - *aAttributeMetadata = emberAfLocateAttributeMetadata(aPath.mEndpointId, aPath.mClusterId, aPath.mAttributeId); -} - -} // anonymous namespace - -bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath) -{ - for (auto & attr : GlobalAttributesNotInMetadata) - { - if (attr == aPath.mAttributeId) - { - return (emberAfFindServerCluster(aPath.mEndpointId, aPath.mClusterId) != nullptr); - } - } - return (emberAfLocateAttributeMetadata(aPath.mEndpointId, aPath.mClusterId, aPath.mAttributeId) != nullptr); -} - -CHIP_ERROR ReadSingleClusterData(const SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * apEncoderState) -{ - ChipLogDetail(DataManagement, - "Reading attribute: Cluster=" ChipLogFormatMEI " Endpoint=%x AttributeId=" ChipLogFormatMEI " (expanded=%d)", - ChipLogValueMEI(aPath.mClusterId), aPath.mEndpointId, ChipLogValueMEI(aPath.mAttributeId), aPath.mExpanded); - - // Check attribute existence. This includes attributes with registered metadata, but also specially handled - // mandatory global attributes (which just check for cluster on endpoint). - - const EmberAfCluster * attributeCluster = nullptr; - const EmberAfAttributeMetadata * attributeMetadata = nullptr; - FindAttributeMetadata(aPath, &attributeCluster, &attributeMetadata); - - if (attributeCluster == nullptr && attributeMetadata == nullptr) - { - return CHIP_ERROR_IM_GLOBAL_STATUS_VALUE(UnsupportedAttributeStatus(aPath)); - } - - // Check access control. A failed check will disallow the operation, and may or may not generate an attribute report - // depending on whether the path was expanded. - - { - Access::RequestPath requestPath{ .cluster = aPath.mClusterId, - .endpoint = aPath.mEndpointId, - .requestType = Access::RequestType::kAttributeReadRequest, - .entityId = aPath.mAttributeId }; - Access::Privilege requestPrivilege = RequiredPrivilege::ForReadAttribute(aPath); - CHIP_ERROR err = Access::GetAccessControl().Check(aSubjectDescriptor, requestPath, requestPrivilege); - if (err != CHIP_NO_ERROR) - { - VerifyOrReturnError((err == CHIP_ERROR_ACCESS_DENIED) || (err == CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL), err); - if (aPath.mExpanded) - { - return CHIP_NO_ERROR; - } - return err == CHIP_ERROR_ACCESS_DENIED ? CHIP_IM_GLOBAL_STATUS(UnsupportedAccess) - : CHIP_IM_GLOBAL_STATUS(AccessRestricted); - } - } - - { - // Special handling for mandatory global attributes: these are always for attribute list, using a special - // reader (which can be lightweight constructed even from nullptr). - GlobalAttributeReader reader(attributeCluster); - AttributeAccessInterface * attributeOverride = (attributeCluster != nullptr) - ? &reader - : AttributeAccessInterfaceRegistry::Instance().Get(aPath.mEndpointId, aPath.mClusterId); - if (attributeOverride) - { - bool triedEncode = false; - ReturnErrorOnFailure(ReadViaAccessInterface(aSubjectDescriptor, aIsFabricFiltered, aPath, aAttributeReports, - apEncoderState, attributeOverride, &triedEncode)); - VerifyOrReturnError(!triedEncode, CHIP_NO_ERROR); - } - } - - // Read attribute using Ember, if it doesn't have an override. - - EmberAfAttributeSearchRecord record; - record.endpoint = aPath.mEndpointId; - record.clusterId = aPath.mClusterId; - record.attributeId = aPath.mAttributeId; - Status status = emAfReadOrWriteAttribute(&record, &attributeMetadata, gEmberAttributeIOBufferSpan.data(), - static_cast(gEmberAttributeIOBufferSpan.size()), - /* write = */ false); - - if (status != Status::Success) - { - return CHIP_ERROR_IM_GLOBAL_STATUS_VALUE(status); - } - - // data available, return the corresponding record - AttributeReportIB::Builder & attributeReport = aAttributeReports.CreateAttributeReport(); - ReturnErrorOnFailure(aAttributeReports.GetError()); - - AttributeDataIB::Builder & attributeDataIBBuilder = attributeReport.CreateAttributeData(); - ReturnErrorOnFailure(attributeDataIBBuilder.GetError()); - - DataVersion version = 0; - ReturnErrorOnFailure(ReadClusterDataVersion(aPath, version)); - attributeDataIBBuilder.DataVersion(version); - ReturnErrorOnFailure(attributeDataIBBuilder.GetError()); - - AttributePathIB::Builder & attributePathIBBuilder = attributeDataIBBuilder.CreatePath(); - ReturnErrorOnFailure(attributeDataIBBuilder.GetError()); - - CHIP_ERROR err = attributePathIBBuilder.Endpoint(aPath.mEndpointId) - .Cluster(aPath.mClusterId) - .Attribute(aPath.mAttributeId) - .EndOfAttributePathIB(); - ReturnErrorOnFailure(err); - - TLV::TLVWriter * writer = attributeDataIBBuilder.GetWriter(); - VerifyOrReturnError(writer != nullptr, CHIP_NO_ERROR); - - const EmberAfAttributeType attributeType = attributeMetadata->attributeType; - const bool isNullable = attributeMetadata->IsNullable(); - const TLV::Tag tag = TLV::ContextTag(AttributeDataIB::Tag::kData); - - switch (AttributeBaseType(attributeType)) - { - case ZCL_NO_DATA_ATTRIBUTE_TYPE: // No data - ReturnErrorOnFailure(writer->PutNull(tag)); - break; - case ZCL_BOOLEAN_ATTRIBUTE_TYPE: // Boolean - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - case ZCL_INT8U_ATTRIBUTE_TYPE: // Unsigned 8-bit integer - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - case ZCL_INT16U_ATTRIBUTE_TYPE: // Unsigned 16-bit integer - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - case ZCL_INT24U_ATTRIBUTE_TYPE: // Unsigned 24-bit integer - { - using IntType = OddSizedInteger<3, false>; - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - } - case ZCL_INT32U_ATTRIBUTE_TYPE: // Unsigned 32-bit integer - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - case ZCL_INT40U_ATTRIBUTE_TYPE: // Unsigned 40-bit integer - { - using IntType = OddSizedInteger<5, false>; - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - } - case ZCL_INT48U_ATTRIBUTE_TYPE: // Unsigned 48-bit integer - { - using IntType = OddSizedInteger<6, false>; - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - } - case ZCL_INT56U_ATTRIBUTE_TYPE: // Unsigned 56-bit integer - { - using IntType = OddSizedInteger<7, false>; - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - } - case ZCL_INT64U_ATTRIBUTE_TYPE: // Unsigned 64-bit integer - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - case ZCL_INT8S_ATTRIBUTE_TYPE: // Signed 8-bit integer - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - case ZCL_INT16S_ATTRIBUTE_TYPE: // Signed 16-bit integer - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - case ZCL_INT24S_ATTRIBUTE_TYPE: // Signed 24-bit integer - { - using IntType = OddSizedInteger<3, true>; - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - } - case ZCL_INT32S_ATTRIBUTE_TYPE: // Signed 32-bit integer - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - case ZCL_INT40S_ATTRIBUTE_TYPE: // Signed 40-bit integer - { - using IntType = OddSizedInteger<5, true>; - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - } - case ZCL_INT48S_ATTRIBUTE_TYPE: // Signed 48-bit integer - { - using IntType = OddSizedInteger<6, true>; - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - } - case ZCL_INT56S_ATTRIBUTE_TYPE: // Signed 56-bit integer - { - using IntType = OddSizedInteger<7, true>; - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - } - case ZCL_INT64S_ATTRIBUTE_TYPE: // Signed 64-bit integer - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - case ZCL_SINGLE_ATTRIBUTE_TYPE: // 32-bit float - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - case ZCL_DOUBLE_ATTRIBUTE_TYPE: // 64-bit float - ReturnErrorOnFailure(attributeBufferToNumericTlvData(*writer, isNullable)); - break; - case ZCL_CHAR_STRING_ATTRIBUTE_TYPE: // Char string - { - char * actualData = reinterpret_cast(gEmberAttributeIOBufferSpan.data() + 1); - uint8_t dataLength = gEmberAttributeIOBufferSpan[0]; - if (dataLength == 0xFF) - { - VerifyOrReturnError(isNullable, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorOnFailure(writer->PutNull(tag)); - } - else - { - ReturnErrorOnFailure(writer->PutString(tag, actualData, dataLength)); - } - break; - } - case ZCL_LONG_CHAR_STRING_ATTRIBUTE_TYPE: { - char * actualData = - reinterpret_cast(gEmberAttributeIOBufferSpan.data() + 2); // The pascal string contains 2 bytes length - uint16_t dataLength; - memcpy(&dataLength, gEmberAttributeIOBufferSpan.data(), sizeof(dataLength)); - if (dataLength == 0xFFFF) - { - VerifyOrReturnError(isNullable, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorOnFailure(writer->PutNull(tag)); - } - else - { - ReturnErrorOnFailure(writer->PutString(tag, actualData, dataLength)); - } - break; - } - case ZCL_OCTET_STRING_ATTRIBUTE_TYPE: // Octet string - { - uint8_t * actualData = gEmberAttributeIOBufferSpan.data() + 1; - uint8_t dataLength = gEmberAttributeIOBufferSpan[0]; - if (dataLength == 0xFF) - { - VerifyOrReturnError(isNullable, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorOnFailure(writer->PutNull(tag)); - } - else - { - ReturnErrorOnFailure(writer->Put(tag, chip::ByteSpan(actualData, dataLength))); - } - break; - } - case ZCL_LONG_OCTET_STRING_ATTRIBUTE_TYPE: { - uint8_t * actualData = gEmberAttributeIOBufferSpan.data() + 2; // The pascal string contains 2 bytes length - uint16_t dataLength; - memcpy(&dataLength, gEmberAttributeIOBufferSpan.data(), sizeof(dataLength)); - if (dataLength == 0xFFFF) - { - VerifyOrReturnError(isNullable, CHIP_ERROR_INCORRECT_STATE); - ReturnErrorOnFailure(writer->PutNull(tag)); - } - else - { - ReturnErrorOnFailure(writer->Put(tag, chip::ByteSpan(actualData, dataLength))); - } - break; - } - default: - ChipLogError(DataManagement, "Attribute type 0x%x not handled", static_cast(attributeType)); - return CHIP_IM_GLOBAL_STATUS(Failure); - } - - // If we got this far, placing the data to be read in the output TLVWriter succeeded. - // Try to terminate our attribute report to signal success. - ReturnErrorOnFailure(attributeDataIBBuilder.EndOfAttributeDataIB()); - return attributeReport.EndOfAttributeReportIB(); -} - -namespace { - -template -CHIP_ERROR numericTlvDataToAttributeBuffer(TLV::TLVReader & aReader, bool isNullable, uint16_t & dataLen) -{ - typename NumericAttributeTraits::StorageType value; - VerifyOrDie(sizeof(value) <= gEmberAttributeIOBufferSpan.size()); - - if (isNullable && aReader.GetType() == TLV::kTLVType_Null) - { - NumericAttributeTraits::SetNull(value); - } - else - { - typename NumericAttributeTraits::WorkingType val; - ReturnErrorOnFailure(aReader.Get(val)); - VerifyOrReturnError(NumericAttributeTraits::CanRepresentValue(isNullable, val), CHIP_ERROR_INVALID_ARGUMENT); - NumericAttributeTraits::WorkingToStorage(val, value); - } - dataLen = sizeof(value); - memcpy(gEmberAttributeIOBufferSpan.data(), &value, sizeof(value)); - return CHIP_NO_ERROR; -} - -template -CHIP_ERROR stringTlvDataToAttributeBuffer(TLV::TLVReader & aReader, bool isOctetString, bool isNullable, uint16_t & dataLen) -{ - const uint8_t * data = nullptr; - T len; - if (isNullable && aReader.GetType() == TLV::kTLVType_Null) - { - // Null is represented by an 0xFF or 0xFFFF length, respectively. - len = std::numeric_limits::max(); - memcpy(gEmberAttributeIOBufferSpan.data(), &len, sizeof(len)); - dataLen = sizeof(len); - } - else - { - VerifyOrReturnError((isOctetString && aReader.GetType() == TLV::TLVType::kTLVType_ByteString) || - (!isOctetString && aReader.GetType() == TLV::TLVType::kTLVType_UTF8String), - CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(CanCastTo(aReader.GetLength()), CHIP_ERROR_MESSAGE_TOO_LONG); - ReturnErrorOnFailure(aReader.GetDataPtr(data)); - len = static_cast(aReader.GetLength()); - VerifyOrReturnError(len != std::numeric_limits::max(), CHIP_ERROR_MESSAGE_TOO_LONG); - VerifyOrReturnError(len + sizeof(len) /* length at the beginning of data */ <= gEmberAttributeIOBufferSpan.size(), - CHIP_ERROR_MESSAGE_TOO_LONG); - memcpy(gEmberAttributeIOBufferSpan.data(), &len, sizeof(len)); - memcpy(gEmberAttributeIOBufferSpan.data() + sizeof(len), data, len); - dataLen = static_cast(len + sizeof(len)); - } - return CHIP_NO_ERROR; -} - -CHIP_ERROR prepareWriteData(const EmberAfAttributeMetadata * attributeMetadata, TLV::TLVReader & aReader, uint16_t & dataLen) -{ - EmberAfAttributeType expectedType = AttributeBaseType(attributeMetadata->attributeType); - bool isNullable = attributeMetadata->IsNullable(); - switch (expectedType) - { - case ZCL_BOOLEAN_ATTRIBUTE_TYPE: // Boolean - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - case ZCL_INT8U_ATTRIBUTE_TYPE: // Unsigned 8-bit integer - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - case ZCL_INT16U_ATTRIBUTE_TYPE: // Unsigned 16-bit integer - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - case ZCL_INT24U_ATTRIBUTE_TYPE: // Unsigned 24-bit integer - { - using IntType = OddSizedInteger<3, false>; - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - } - case ZCL_INT32U_ATTRIBUTE_TYPE: // Unsigned 32-bit integer - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - case ZCL_INT40U_ATTRIBUTE_TYPE: // Unsigned 40-bit integer - { - using IntType = OddSizedInteger<5, false>; - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - } - case ZCL_INT48U_ATTRIBUTE_TYPE: // Unsigned 48-bit integer - { - using IntType = OddSizedInteger<6, false>; - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - } - case ZCL_INT56U_ATTRIBUTE_TYPE: // Unsigned 56-bit integer - { - using IntType = OddSizedInteger<7, false>; - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - } - case ZCL_INT64U_ATTRIBUTE_TYPE: // Unsigned 64-bit integer - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - case ZCL_INT8S_ATTRIBUTE_TYPE: // Signed 8-bit integer - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - case ZCL_INT16S_ATTRIBUTE_TYPE: // Signed 16-bit integer - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - case ZCL_INT24S_ATTRIBUTE_TYPE: // Signed 24-bit integer - { - using IntType = OddSizedInteger<3, true>; - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - } - case ZCL_INT32S_ATTRIBUTE_TYPE: // Signed 32-bit integer - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - case ZCL_INT40S_ATTRIBUTE_TYPE: // Signed 40-bit integer - { - using IntType = OddSizedInteger<5, true>; - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - } - case ZCL_INT48S_ATTRIBUTE_TYPE: // Signed 48-bit integer - { - using IntType = OddSizedInteger<6, true>; - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - } - case ZCL_INT56S_ATTRIBUTE_TYPE: // Signed 56-bit integer - { - using IntType = OddSizedInteger<7, true>; - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - } - case ZCL_INT64S_ATTRIBUTE_TYPE: // Signed 64-bit integer - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - case ZCL_SINGLE_ATTRIBUTE_TYPE: // 32-bit float - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - case ZCL_DOUBLE_ATTRIBUTE_TYPE: // 64-bit float - return numericTlvDataToAttributeBuffer(aReader, isNullable, dataLen); - case ZCL_OCTET_STRING_ATTRIBUTE_TYPE: // Octet string - case ZCL_CHAR_STRING_ATTRIBUTE_TYPE: // Char string - return stringTlvDataToAttributeBuffer(aReader, expectedType == ZCL_OCTET_STRING_ATTRIBUTE_TYPE, isNullable, - dataLen); - case ZCL_LONG_OCTET_STRING_ATTRIBUTE_TYPE: // Long octet string - case ZCL_LONG_CHAR_STRING_ATTRIBUTE_TYPE: // Long char string - return stringTlvDataToAttributeBuffer(aReader, expectedType == ZCL_LONG_OCTET_STRING_ATTRIBUTE_TYPE, isNullable, - dataLen); - default: - ChipLogError(DataManagement, "Attribute type %x not handled", static_cast(expectedType)); - return CHIP_ERROR_INVALID_DATA_LIST; - } -} -} // namespace - -const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aPath) -{ - return emberAfLocateAttributeMetadata(aPath.mEndpointId, aPath.mClusterId, aPath.mAttributeId); -} - -CHIP_ERROR WriteSingleClusterData(const SubjectDescriptor & aSubjectDescriptor, const ConcreteDataAttributePath & aPath, - TLV::TLVReader & aReader, WriteHandler * apWriteHandler) -{ - // Check attribute existence. This includes attributes with registered metadata, but also specially handled - // mandatory global attributes (which just check for cluster on endpoint). - const EmberAfCluster * attributeCluster = nullptr; - const EmberAfAttributeMetadata * attributeMetadata = nullptr; - FindAttributeMetadata(aPath, &attributeCluster, &attributeMetadata); - - if (attributeCluster == nullptr && attributeMetadata == nullptr) - { - return apWriteHandler->AddStatus(aPath, UnsupportedAttributeStatus(aPath)); - } - - // All the global attributes we don't have metadata for are readonly. - if (attributeMetadata == nullptr || attributeMetadata->IsReadOnly()) - { - return apWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::UnsupportedWrite); - } - - { - Access::RequestPath requestPath{ .cluster = aPath.mClusterId, - .endpoint = aPath.mEndpointId, - .requestType = Access::RequestType::kAttributeWriteRequest, - .entityId = aPath.mAttributeId }; - Access::Privilege requestPrivilege = RequiredPrivilege::ForWriteAttribute(aPath); - CHIP_ERROR err = CHIP_NO_ERROR; - if (!apWriteHandler->ACLCheckCacheHit({ aPath, requestPrivilege })) - { - err = Access::GetAccessControl().Check(aSubjectDescriptor, requestPath, requestPrivilege); - } - if (err != CHIP_NO_ERROR) - { - VerifyOrReturnError((err == CHIP_ERROR_ACCESS_DENIED) || (err == CHIP_ERROR_ACCESS_RESTRICTED_BY_ARL), err); - // TODO: when wildcard/group writes are supported, handle them to discard rather than fail with status - return apWriteHandler->AddStatus(aPath, - err == CHIP_ERROR_ACCESS_DENIED - ? Protocols::InteractionModel::Status::UnsupportedAccess - : Protocols::InteractionModel::Status::AccessRestricted); - } - apWriteHandler->CacheACLCheckResult({ aPath, requestPrivilege }); - } - - if (attributeMetadata->MustUseTimedWrite() && !apWriteHandler->IsTimedWrite()) - { - return apWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::NeedsTimedInteraction); - } - - if (aPath.mDataVersion.HasValue() && !IsClusterDataVersionEqual(aPath, aPath.mDataVersion.Value())) - { - ChipLogError(DataManagement, "Write Version mismatch for Endpoint %x, Cluster " ChipLogFormatMEI, aPath.mEndpointId, - ChipLogValueMEI(aPath.mClusterId)); - return apWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::DataVersionMismatch); - } - - if (auto * attrOverride = AttributeAccessInterfaceRegistry::Instance().Get(aPath.mEndpointId, aPath.mClusterId)) - { - AttributeValueDecoder valueDecoder(aReader, aSubjectDescriptor); - ReturnErrorOnFailure(attrOverride->Write(aPath, valueDecoder)); - - if (valueDecoder.TriedDecode()) - { - MatterReportingAttributeChangeCallback(aPath); - return apWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Success); - } - } - - CHIP_ERROR preparationError = CHIP_NO_ERROR; - uint16_t dataLen = 0; - if ((preparationError = prepareWriteData(attributeMetadata, aReader, dataLen)) != CHIP_NO_ERROR) - { - ChipLogDetail(Zcl, "Failed to prepare data to write: %" CHIP_ERROR_FORMAT, preparationError.Format()); - return apWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::InvalidValue); - } - - if (dataLen > attributeMetadata->size) - { - ChipLogDetail(Zcl, "Data to write exceedes the attribute size claimed."); - return apWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::InvalidValue); - } - - auto status = emAfWriteAttributeExternal( - aPath, EmberAfWriteDataInput(gEmberAttributeIOBufferSpan.data(), attributeMetadata->attributeType)); - return apWriteHandler->AddStatus(aPath, status); -} - -bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) -{ - DataVersion * version = emberAfDataVersionStorage(aConcreteClusterPath); - if (version == nullptr) - { - ChipLogError(DataManagement, "Endpoint %x, Cluster " ChipLogFormatMEI " not found in IsClusterDataVersionEqual!", - aConcreteClusterPath.mEndpointId, ChipLogValueMEI(aConcreteClusterPath.mClusterId)); - return false; - } - - return (*(version)) == aRequiredVersion; -} - -bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) -{ - CHIP_ERROR err; - auto deviceTypeList = emberAfDeviceTypeListFromEndpoint(endpoint, err); - if (err != CHIP_NO_ERROR) - { - return false; - } - - for (auto & device : deviceTypeList) - { - if (device.deviceId == deviceType) - { - return true; - } - } - - return false; -} - -Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath) -{ - using Protocols::InteractionModel::Status; - - const EmberAfEndpointType * type = emberAfFindEndpointType(aPath.mEndpointId); - if (type == nullptr) - { - return Status::UnsupportedEndpoint; - } - - const EmberAfCluster * cluster = emberAfFindClusterInType(type, aPath.mClusterId, CLUSTER_MASK_SERVER); - if (cluster == nullptr) - { - return Status::UnsupportedCluster; - } - - // No way to tell. Just claim supported. - return Status::Success; -} - -} // namespace app -} // namespace chip diff --git a/src/app/util/ember-compatibility-functions.h b/src/app/util/ember-compatibility-functions.h deleted file mode 100644 index ca7f16950bad39..00000000000000 --- a/src/app/util/ember-compatibility-functions.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2024 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. - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace chip { -namespace app { - -/** - * Check whether the given cluster exists on the given endpoint and supports - * the given command. If it does, Success will be returned. If it does not, - * one of UnsupportedEndpoint, UnsupportedCluster, or UnsupportedCommand - * will be returned, depending on how the command fails to exist. - */ -Protocols::InteractionModel::Status ServerClusterCommandExists(const ConcreteCommandPath & aCommandPath); - -/** - * Check whether concrete attribute path is an "existent attribute path" in spec terms. - * @param[in] aPath The concrete path of the data being read. - * @retval boolean true if the concrete attribute path indicates an attribute that exists on the node. - */ -bool ConcreteAttributePathExists(const ConcreteAttributePath & aPath); - -/** - * Fetch attribute value and version info and write to the AttributeReport provided. - * The ReadSingleClusterData will do everything required for encoding an attribute, i.e. it will try to put one or more - * AttributeReportIB to the AttributeReportIBs::Builder. - * When the endpoint / cluster / attribute data specified by aPath does not exist, corresponding interaction - * model error code will be put into aAttributeReports, and CHIP_NO_ERROR will be returned. If the data exists on the server, the - * data (with tag kData) and the data version (with tag kDataVersion) will be put into aAttributeReports. TLVWriter error will be - * returned if any error occurred while encoding these values. This function is implemented by CHIP as a part of cluster data - * storage & management. - * - * @param[in] aSubjectDescriptor The subject descriptor for the read. - * @param[in] aPath The concrete path of the data being read. - * @param[in] aAttributeReports The TLV Builder for Cluter attribute builder. - * - * @retval CHIP_NO_ERROR on success - */ -CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * apEncoderState); - -/** - * Returns the metadata of the attribute for the given path. - * - * @retval The metadata of the attribute, will return null if the given attribute does not exists. - */ -const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aPath); - -/** - * TODO: Document. - */ -CHIP_ERROR WriteSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteDataAttributePath & aPath, - TLV::TLVReader & aReader, WriteHandler * apWriteHandler); - -/** - * Check if the given cluster has the given DataVersion. - */ -bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion); - -/** - * Returns true if device type is on endpoint, false otherwise. - */ -bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint); - -/** - * Returns the event support status for the given event, as an interaction model status. - */ -Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath); - -} // namespace app -} // namespace chip diff --git a/src/controller/tests/data_model/DataModelFixtures.cpp b/src/controller/tests/data_model/DataModelFixtures.cpp index f007275c9b3bc2..6f42c38a7789e4 100644 --- a/src/controller/tests/data_model/DataModelFixtures.cpp +++ b/src/controller/tests/data_model/DataModelFixtures.cpp @@ -85,9 +85,9 @@ CommandHandler::Handle gAsyncCommandHandle; } // namespace DataModelTests -CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, - const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, - AttributeEncodeState * apEncoderState) +static CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, + const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, + AttributeEncodeState * apEncoderState) { if (aPath.mEndpointId >= chip::Test::kMockEndpointMin) { @@ -224,175 +224,6 @@ CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescr return CHIP_NO_ERROR; } -bool IsClusterDataVersionEqual(const app::ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) -{ - if (aRequiredVersion == kDataVersion) - { - return true; - } - if (Test::GetVersion() == aRequiredVersion) - { - return true; - } - - return false; -} - -bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) -{ - return false; -} - -Protocols::InteractionModel::Status CheckEventSupportStatus(const ConcreteEventPath & aPath) -{ - return Protocols::InteractionModel::Status::Success; -} - -const EmberAfAttributeMetadata * GetAttributeMetadata(const ConcreteAttributePath & aConcreteClusterPath) -{ - // Note: This test does not make use of the real attribute metadata. - static EmberAfAttributeMetadata stub = { .defaultValue = EmberAfDefaultOrMinMaxAttributeValue(uint32_t(0)) }; - return &stub; -} - -CHIP_ERROR WriteSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, const ConcreteDataAttributePath & aPath, - TLV::TLVReader & aReader, WriteHandler * aWriteHandler) -{ - static ListIndex listStructOctetStringElementCount = 0; - - if (aPath.mDataVersion.HasValue() && aPath.mDataVersion.Value() == kRejectedDataVersion) - { - return aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::DataVersionMismatch); - } - - if (aPath.mClusterId == Clusters::UnitTesting::Id && - aPath.mAttributeId == Attributes::ListStructOctetString::TypeInfo::GetAttributeId()) - { - if (gWriteResponseDirective == WriteResponseDirective::kSendAttributeSuccess) - { - if (!aPath.IsListOperation() || aPath.mListOp == ConcreteDataAttributePath::ListOperation::ReplaceAll) - { - - Attributes::ListStructOctetString::TypeInfo::DecodableType value; - - ReturnErrorOnFailure(DataModel::Decode(aReader, value)); - - auto iter = value.begin(); - listStructOctetStringElementCount = 0; - while (iter.Next()) - { - auto & item = iter.GetValue(); - - VerifyOrReturnError(item.member1 == listStructOctetStringElementCount, CHIP_ERROR_INVALID_ARGUMENT); - listStructOctetStringElementCount++; - } - - aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Success); - } - else if (aPath.mListOp == ConcreteDataAttributePath::ListOperation::AppendItem) - { - Structs::TestListStructOctet::DecodableType item; - ReturnErrorOnFailure(DataModel::Decode(aReader, item)); - VerifyOrReturnError(item.member1 == listStructOctetStringElementCount, CHIP_ERROR_INVALID_ARGUMENT); - listStructOctetStringElementCount++; - - aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Success); - } - else - { - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; - } - } - else - { - aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Failure); - } - - return CHIP_NO_ERROR; - } - if (aPath.mClusterId == Clusters::UnitTesting::Id && aPath.mAttributeId == Attributes::ListFabricScoped::Id) - { - // Mock an invalid SubjectDescriptor. - // NOTE: completely ignores the passed-in subjectDescriptor - AttributeValueDecoder decoder(aReader, Access::SubjectDescriptor()); - if (!aPath.IsListOperation() || aPath.mListOp == ConcreteDataAttributePath::ListOperation::ReplaceAll) - { - Attributes::ListFabricScoped::TypeInfo::DecodableType value; - - ReturnErrorOnFailure(decoder.Decode(value)); - - auto iter = value.begin(); - while (iter.Next()) - { - auto & item = iter.GetValue(); - (void) item; - } - - aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Success); - } - else if (aPath.mListOp == ConcreteDataAttributePath::ListOperation::AppendItem) - { - Structs::TestFabricScoped::DecodableType item; - ReturnErrorOnFailure(decoder.Decode(item)); - - aWriteHandler->AddStatus(aPath, Protocols::InteractionModel::Status::Success); - } - else - { - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; - } - return CHIP_NO_ERROR; - } - - // Boolean attribute of unit testing cluster triggers "multiple errors" case. - if (aPath.mClusterId == Clusters::UnitTesting::Id && aPath.mAttributeId == Attributes::Boolean::TypeInfo::GetAttributeId()) - { - Protocols::InteractionModel::ClusterStatusCode status{ Protocols::InteractionModel::Status::InvalidValue }; - - if (gWriteResponseDirective == WriteResponseDirective::kSendMultipleSuccess) - { - status = Protocols::InteractionModel::Status::Success; - } - else if (gWriteResponseDirective == WriteResponseDirective::kSendMultipleErrors) - { - status = Protocols::InteractionModel::Status::Failure; - } - else - { - VerifyOrDie(false); - } - - for (size_t i = 0; i < 4; ++i) - { - aWriteHandler->AddStatus(aPath, status); - } - - return CHIP_NO_ERROR; - } - - if (aPath.mClusterId == Clusters::UnitTesting::Id && aPath.mAttributeId == Attributes::Int8u::TypeInfo::GetAttributeId()) - { - Protocols::InteractionModel::ClusterStatusCode status{ Protocols::InteractionModel::Status::InvalidValue }; - if (gWriteResponseDirective == WriteResponseDirective::kSendClusterSpecificSuccess) - { - status = Protocols::InteractionModel::ClusterStatusCode::ClusterSpecificSuccess(kExampleClusterSpecificSuccess); - } - else if (gWriteResponseDirective == WriteResponseDirective::kSendClusterSpecificFailure) - { - status = Protocols::InteractionModel::ClusterStatusCode::ClusterSpecificFailure(kExampleClusterSpecificFailure); - } - else - { - VerifyOrDie(false); - } - - aWriteHandler->AddStatus(aPath, status); - return CHIP_NO_ERROR; - } - - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; -} - void DispatchSingleClusterCommand(const ConcreteCommandPath & aCommandPath, chip::TLV::TLVReader & aReader, CommandHandler * apCommandObj) { @@ -481,24 +312,6 @@ void DispatchSingleClusterCommand(const ConcreteCommandPath & aCommandPath, chip } } -Protocols::InteractionModel::Status ServerClusterCommandExists(const ConcreteCommandPath & aCommandPath) -{ - // Mock cluster catalog, only support commands on one cluster on one endpoint. - using Protocols::InteractionModel::Status; - - if (aCommandPath.mEndpointId != DataModelTests::kTestEndpointId) - { - return Status::UnsupportedEndpoint; - } - - if (aCommandPath.mClusterId != Clusters::UnitTesting::Id) - { - return Status::UnsupportedCluster; - } - - return Status::Success; -} - CustomDataModel & CustomDataModel::Instance() { static CustomDataModel model; @@ -509,20 +322,6 @@ ActionReturnStatus CustomDataModel::ReadAttribute(const ReadAttributeRequest & r { AttributeEncodeState mutableState(&encoder.GetState()); // provide a state copy to start. -#if CHIP_CONFIG_USE_EMBER_DATA_MODEL && CHIP_CONFIG_USE_DATA_MODEL_INTERFACE - if ((request.path.mEndpointId < chip::Test::kMockEndpointMin) && - (gReadResponseDirective == ReadResponseDirective::kSendDataResponse) && - (request.path.mClusterId == app::Clusters::UnitTesting::Id) && - (request.path.mAttributeId == app::Clusters::UnitTesting::Attributes::Int16u::Id)) - { - // gInt16uTotalReadCount is a global that keeps changing. Further more, encoding - // size differs when moving from 0xFF to 0x100, so encoding sizes in TLV differ. - // - // This is a HACKISH workaround as it relies that we ember-read before datamodel-read - gInt16uTotalReadCount--; - } -#endif // CHIP_CONFIG_USE_EMBER_DATA_MODEL && CHIP_CONFIG_USE_DATA_MODEL_INTERFACE - Access::SubjectDescriptor subjectDescriptor; if (request.subjectDescriptor != nullptr) { diff --git a/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm b/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm index e98bdc0b9e61a4..35f602e0de2aeb 100644 --- a/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm +++ b/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm @@ -35,7 +35,6 @@ #include #include -#include #include using namespace chip; @@ -47,7 +46,14 @@ public: bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) override { - return app::IsDeviceTypeOnEndpoint(deviceType, endpoint); + app::DataModel::Provider * model = app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); + + for (auto type = model->FirstDeviceType(endpoint); type.has_value(); type = model->NextDeviceType(endpoint, *type)) { + if (type->deviceTypeId == deviceType) { + return true; + } + } + return false; } }; diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index 7893475aa6050c..195dd8e2757316 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -161,8 +161,6 @@ 5143851E2A65885500EDC8E6 /* MTRSwiftPairingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5143851D2A65885500EDC8E6 /* MTRSwiftPairingTests.swift */; }; 514654492A72F9DF00904E61 /* MTRDemuxingStorage.mm in Sources */ = {isa = PBXBuildFile; fileRef = 514654482A72F9DF00904E61 /* MTRDemuxingStorage.mm */; }; 5146544B2A72F9F500904E61 /* MTRDemuxingStorage.h in Headers */ = {isa = PBXBuildFile; fileRef = 5146544A2A72F9F500904E61 /* MTRDemuxingStorage.h */; }; - 514C79ED2B62ADCD00DD6D7B /* ember-compatibility-functions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 514C79EC2B62ADCD00DD6D7B /* ember-compatibility-functions.cpp */; }; - 514C79EE2B62ADCD00DD6D7B /* ember-compatibility-functions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 514C79EC2B62ADCD00DD6D7B /* ember-compatibility-functions.cpp */; }; 514C79F02B62ADDA00DD6D7B /* descriptor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 514C79EF2B62ADDA00DD6D7B /* descriptor.cpp */; }; 514C79F12B62ADDA00DD6D7B /* descriptor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 514C79EF2B62ADDA00DD6D7B /* descriptor.cpp */; }; 514C79F32B62ED5500DD6D7B /* attribute-storage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 514C79F22B62ED5500DD6D7B /* attribute-storage.cpp */; }; @@ -641,7 +639,6 @@ 5143851D2A65885500EDC8E6 /* MTRSwiftPairingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MTRSwiftPairingTests.swift; sourceTree = ""; }; 514654482A72F9DF00904E61 /* MTRDemuxingStorage.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDemuxingStorage.mm; sourceTree = ""; }; 5146544A2A72F9F500904E61 /* MTRDemuxingStorage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MTRDemuxingStorage.h; sourceTree = ""; }; - 514C79EC2B62ADCD00DD6D7B /* ember-compatibility-functions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = "ember-compatibility-functions.cpp"; path = "util/ember-compatibility-functions.cpp"; sourceTree = ""; }; 514C79EF2B62ADDA00DD6D7B /* descriptor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = descriptor.cpp; path = clusters/descriptor/descriptor.cpp; sourceTree = ""; }; 514C79F22B62ED5500DD6D7B /* attribute-storage.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = "attribute-storage.cpp"; path = "util/attribute-storage.cpp"; sourceTree = ""; }; 514C79F52B62F0B900DD6D7B /* util.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = util.cpp; path = util/util.cpp; sourceTree = ""; }; @@ -1162,7 +1159,6 @@ 5143041F2914CED9004DC7FE /* generic-callback-stubs.cpp */, 514C79F22B62ED5500DD6D7B /* attribute-storage.cpp */, 514C79EF2B62ADDA00DD6D7B /* descriptor.cpp */, - 514C79EC2B62ADCD00DD6D7B /* ember-compatibility-functions.cpp */, E04AC67C2BEEA17F00BA409B /* ember-global-attribute-access-interface.cpp */, E04AC67B2BEEA17F00BA409B /* ember-io-storage.cpp */, 516415FE2B6B132200D5CE11 /* DataModelHandler.cpp */, @@ -2102,7 +2098,6 @@ 039546A62991E151006D42A8 /* InteractionModel.cpp in Sources */, B4FCD5722B603A6300832859 /* DownloadLogCommand.mm in Sources */, 75A202E62BA8DBAC00A771DD /* reporting.cpp in Sources */, - 514C79EE2B62ADCD00DD6D7B /* ember-compatibility-functions.cpp in Sources */, 039145E82993179300257B3E /* GetCommissionerNodeIdCommand.mm in Sources */, 0395469F2991DFC5006D42A8 /* json_reader.cpp in Sources */, 514C79F42B62ED5500DD6D7B /* attribute-storage.cpp in Sources */, @@ -2178,7 +2173,6 @@ 516415FF2B6B132200D5CE11 /* DataModelHandler.cpp in Sources */, 75139A6F2B7FE5E900E3A919 /* MTRDeviceControllerLocalTestStorage.mm in Sources */, 51E95DFC2A78443C00A434F0 /* MTRSessionResumptionStorageBridge.mm in Sources */, - 514C79ED2B62ADCD00DD6D7B /* ember-compatibility-functions.cpp in Sources */, 7534F12828BFF20300390851 /* MTRDeviceAttestationDelegate.mm in Sources */, B4C8E6B72B3453AD00FCD54D /* MTRDiagnosticLogsDownloader.mm in Sources */, 2C5EEEF7268A85C400CAE3D3 /* MTRDeviceConnectionBridge.mm in Sources */, From 08024d2ddb5f330384411d55bc44e2ee9bbcad8d Mon Sep 17 00:00:00 2001 From: Justin Wood Date: Thu, 31 Oct 2024 20:31:32 -0700 Subject: [PATCH 044/121] Add new API so it's possible to not leak a key (#36299) * Initial checkin * Fixing review feedback * Adding braces * Restyled by clang-format * Fixing build * Restyled by clang-format * Fixing annotations * Update src/darwin/Framework/CHIP/MTRKeypair.h Co-authored-by: Boris Zbarsky * separate statements involving _mPublicKey to make compiler happy * use `CFAutorelease` on CoreFoundation typed public key copies * fix indent * implement `copyPublicKey` for `MTRTestKeys`; add TODO note about optional method calls * remove comment it's a test; this is the best we can do with an optional protocol method * consistent formatting for `copyPublicKey` calls * reformat `copyPublicKey` in `MTRTestKeys` remove comment - not this method's job to worry about other implementation's potential side-effects * Update src/darwin/Framework/CHIP/MTRKeypair.h Co-authored-by: Boris Zbarsky --------- Co-authored-by: Restyled.io Co-authored-by: Boris Zbarsky Co-authored-by: Kiel Oleson --- .../commands/common/CHIPToolKeypair.h | 2 +- .../commands/common/CHIPToolKeypair.mm | 10 +++- src/darwin/Framework/CHIP/MTRCertificates.mm | 19 +++++- .../CHIP/MTRDeviceControllerFactory.mm | 19 +++++- src/darwin/Framework/CHIP/MTRKeypair.h | 15 +++-- .../Framework/CHIPTests/MTRCertificateTests.m | 60 ++++++++++++++----- .../CHIPTests/MTRCertificateValidityTests.m | 5 +- .../CHIPTests/MTRControllerAdvertisingTests.m | 5 +- .../Framework/CHIPTests/MTRControllerTests.m | 59 ++++++++++++++---- .../Framework/CHIPTests/MTRFabricInfoTests.m | 5 +- .../CHIPTests/MTRPerControllerStorageTests.m | 6 +- .../CHIPTests/TestHelpers/MTRTestKeys.m | 6 ++ 12 files changed, 170 insertions(+), 41 deletions(-) diff --git a/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.h b/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.h index f0ee3f8db6092b..58be7f2ac4b041 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.h +++ b/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.h @@ -22,7 +22,7 @@ @interface CHIPToolKeypair : NSObject - (BOOL)initialize; - (NSData *)signMessageECDSA_RAW:(NSData *)message; -- (SecKeyRef)publicKey; +- (SecKeyRef)copyPublicKey; - (CHIP_ERROR)Serialize:(chip::Crypto::P256SerializedKeypair &)output; - (CHIP_ERROR)Deserialize:(chip::Crypto::P256SerializedKeypair &)input; - (CHIP_ERROR)createOrLoadKeys:(id)storage; diff --git a/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.mm b/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.mm index ce0ef5819b6ac1..a09975d68da41f 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.mm +++ b/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.mm @@ -65,7 +65,7 @@ - (NSData *)signMessageECDSA_RAW:(NSData *)message return out_signature; } -- (SecKeyRef)publicKey +- (SecKeyRef)copyPublicKey { if (_mPublicKey == nil) { chip::Crypto::P256PublicKey publicKey = _mKeyPair.Pubkey(); @@ -79,7 +79,13 @@ - (SecKeyRef)publicKey }; _mPublicKey = SecKeyCreateWithData((__bridge CFDataRef) publicKeyNSData, (__bridge CFDictionaryRef) attributes, nullptr); } - return _mPublicKey; + + if (_mPublicKey) { + CFRetain(_mPublicKey); + return _mPublicKey; + } + + return NULL; } - (CHIP_ERROR)Deserialize:(chip::Crypto::P256SerializedKeypair &)input diff --git a/src/darwin/Framework/CHIP/MTRCertificates.mm b/src/darwin/Framework/CHIP/MTRCertificates.mm index b153cf4442b373..7dcec96cba695b 100644 --- a/src/darwin/Framework/CHIP/MTRCertificates.mm +++ b/src/darwin/Framework/CHIP/MTRCertificates.mm @@ -152,7 +152,24 @@ + (MTRCertificateDERBytes _Nullable)createOperationalCertificate:(id + (BOOL)keypair:(id)keypair matchesCertificate:(NSData *)certificate { P256PublicKey keypairPubKey; - CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(keypair.publicKey, &keypairPubKey); + SecKeyRef publicKey = NULL; + + if ([keypair respondsToSelector:@selector(copyPublicKey)]) { + publicKey = [keypair copyPublicKey]; + } else { + publicKey = [keypair publicKey]; + if (publicKey) { + CFRetain(publicKey); + } + } + + CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(publicKey, &keypairPubKey); + + if (publicKey != NULL) { + CFRelease(publicKey); + publicKey = NULL; + } + if (err != CHIP_NO_ERROR) { MTR_LOG_ERROR("Can't extract public key from keypair: %s", ErrorStr(err)); return NO; diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm index 9de51431bfe4f8..e287ef0446593f 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm @@ -819,7 +819,24 @@ - (BOOL)findMatchingFabric:(FabricTable &)fabricTable } else { // No root certificate means the nocSigner is using the root keys, because // consumers must provide a root certificate whenever an ICA is used. - CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(params.nocSigner.publicKey, &pubKey); + SecKeyRef publicKey = NULL; + + if ([params.nocSigner respondsToSelector:@selector(copyPublicKey)]) { + publicKey = [params.nocSigner copyPublicKey]; + } else { + publicKey = [params.nocSigner publicKey]; + if (publicKey) { + CFRetain(publicKey); + } + } + + CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(publicKey, &pubKey); + + if (publicKey != NULL) { + CFRelease(publicKey); + publicKey = NULL; + } + if (err != CHIP_NO_ERROR) { MTR_LOG_ERROR("Can't extract public key from MTRKeypair: %s", ErrorStr(err)); return NO; diff --git a/src/darwin/Framework/CHIP/MTRKeypair.h b/src/darwin/Framework/CHIP/MTRKeypair.h index a4e4521b2864a6..d7381fe096f900 100644 --- a/src/darwin/Framework/CHIP/MTRKeypair.h +++ b/src/darwin/Framework/CHIP/MTRKeypair.h @@ -16,6 +16,7 @@ */ #import +#import #import NS_ASSUME_NONNULL_BEGIN @@ -31,13 +32,19 @@ NS_ASSUME_NONNULL_BEGIN * framework APIs. */ @protocol MTRKeypair -@required + +@optional /** - * @brief Return public key for the keypair. + * @brief Returns a copy of the public key for the keypair. */ -- (SecKeyRef)publicKey; +- (SecKeyRef)copyPublicKey MTR_NEWLY_AVAILABLE; + +/** + * @brief Returns public key for the keypair without adding a reference. DEPRECATED - please use copyPublicKey, otherwise this will leak. + */ + +- (SecKeyRef)publicKey MTR_DEPRECATED("Please implement copyPublicKey, this will leak otherwise", ios(16.1, 18.3), macos(13.0, 15.3), watchos(9.1, 11.3), tvos(16.1, 18.3)); -@optional /** * @brief A function to sign a message using ECDSA * diff --git a/src/darwin/Framework/CHIPTests/MTRCertificateTests.m b/src/darwin/Framework/CHIPTests/MTRCertificateTests.m index fb6cfb9ecb7e67..d5be54e43816e9 100644 --- a/src/darwin/Framework/CHIPTests/MTRCertificateTests.m +++ b/src/darwin/Framework/CHIPTests/MTRCertificateTests.m @@ -127,9 +127,13 @@ - (void)testGenerateIntermediateCert __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); + __auto_type * intermediateCert = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:rootCert - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -155,13 +159,16 @@ - (void)testGenerateIntermediateCertWithValidityPeriod __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = intermediateKeys.copyPublicKey; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * startDate = [MTRCertificateTests startDateWithTimeIntervalSinceNow:300]; __auto_type * validityPeriod = [[NSDateInterval alloc] initWithStartDate:startDate duration:400]; __auto_type * intermediateCert = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:rootCert - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil validityPeriod:validityPeriod @@ -192,13 +199,16 @@ - (void)testGenerateIntermediateCertWithInfiniteValidity __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = intermediateKeys.copyPublicKey; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * startDate = [MTRCertificateTests startDateWithTimeIntervalSinceNow:300]; __auto_type * validityPeriod = [[NSDateInterval alloc] initWithStartDate:startDate endDate:[NSDate distantFuture]]; __auto_type * intermediateCert = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:rootCert - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil validityPeriod:validityPeriod @@ -229,6 +239,9 @@ - (void)testGenerateOperationalCertNoIntermediate __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * cats = [[NSMutableSet alloc] initWithCapacity:3]; // High bits are identifier, low bits are version. @@ -238,7 +251,7 @@ - (void)testGenerateOperationalCertNoIntermediate __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:cats @@ -265,6 +278,9 @@ - (void)testGenerateOperationalCertNoIntermediateWithValidityPeriod __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * cats = [[NSMutableSet alloc] initWithCapacity:3]; // High bits are identifier, low bits are version. @@ -277,7 +293,7 @@ - (void)testGenerateOperationalCertNoIntermediateWithValidityPeriod __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:cats @@ -309,6 +325,9 @@ - (void)testGenerateOperationalCertNoIntermediateWithInfiniteValidity __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * cats = [[NSMutableSet alloc] initWithCapacity:3]; // High bits are identifier, low bits are version. @@ -321,7 +340,7 @@ - (void)testGenerateOperationalCertNoIntermediateWithInfiniteValidity __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:cats @@ -353,10 +372,13 @@ - (void)testGenerateOperationalCertWithIntermediate __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediateCert = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:rootCert - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -364,10 +386,13 @@ - (void)testGenerateOperationalCertWithIntermediate __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:intermediateKeys signingCertificate:intermediateCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:nil @@ -394,6 +419,9 @@ - (void)testGenerateOperationalCertErrorCases __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * longCats = [[NSMutableSet alloc] initWithCapacity:4]; [longCats addObject:@0x00010001]; @@ -415,7 +443,7 @@ - (void)testGenerateOperationalCertErrorCases // Check basic case works __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:nil @@ -425,7 +453,7 @@ - (void)testGenerateOperationalCertErrorCases // CATs too long operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:longCats @@ -435,7 +463,7 @@ - (void)testGenerateOperationalCertErrorCases // Multiple CATs with the same identifier but different versions operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:catsWithSameIdentifier @@ -445,7 +473,7 @@ - (void)testGenerateOperationalCertErrorCases // CAT with invalid version operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:catsWithInvalidVersion @@ -455,7 +483,7 @@ - (void)testGenerateOperationalCertErrorCases // Signing key mismatch operationalCert = [MTRCertificates createOperationalCertificate:operationalKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:nil @@ -465,7 +493,7 @@ - (void)testGenerateOperationalCertErrorCases // Invalid fabric id operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@0 nodeID:@1 caseAuthenticatedTags:nil @@ -475,7 +503,7 @@ - (void)testGenerateOperationalCertErrorCases // Undefined node id operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@0 caseAuthenticatedTags:nil @@ -485,7 +513,7 @@ - (void)testGenerateOperationalCertErrorCases // Non-operational node id operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@1 nodeID:@(0xFFFFFFFFFFFFFFFFLLU) caseAuthenticatedTags:nil diff --git a/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m b/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m index ecc593e8432045..719be071063fbe 100644 --- a/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m +++ b/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m @@ -259,10 +259,13 @@ - (void)initStack:(MTRTestCertificateIssuer *)certificateIssuer __auto_type * controllerOperationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(controllerOperationalKeys); + __auto_type * controllerPublicKey = controllerOperationalKeys.copyPublicKey; + XCTAssert(controllerPublicKey != NULL); + CFAutorelease(controllerPublicKey); __auto_type * controllerOperationalCert = [certificateIssuer issueOperationalCertificateForNode:@(kControllerId) - operationalPublicKey:controllerOperationalKeys.publicKey]; + operationalPublicKey:controllerPublicKey]; XCTAssertNotNil(controllerOperationalCert); __auto_type * params = [[MTRDeviceControllerStartupParams alloc] initWithIPK:certificateIssuer.rootKey.ipk diff --git a/src/darwin/Framework/CHIPTests/MTRControllerAdvertisingTests.m b/src/darwin/Framework/CHIPTests/MTRControllerAdvertisingTests.m index 4092a38b56f84e..bee6ee90df3524 100644 --- a/src/darwin/Framework/CHIPTests/MTRControllerAdvertisingTests.m +++ b/src/darwin/Framework/CHIPTests/MTRControllerAdvertisingTests.m @@ -164,10 +164,13 @@ - (nullable MTRDeviceController *)startControllerWithRootKeys:(MTRTestKeys *)roo __auto_type * root = [MTRCertificates createRootCertificate:rootKeys issuerID:@(1) fabricID:nil error:error]; XCTAssertNil(*error); XCTAssertNotNil(root); + __auto_type * publicKey = operationalKeys.copyPublicKey; + XCTAssert(publicKey != NULL); + CFAutorelease(publicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:root - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:publicKey fabricID:fabricID nodeID:nodeID caseAuthenticatedTags:nil diff --git a/src/darwin/Framework/CHIPTests/MTRControllerTests.m b/src/darwin/Framework/CHIPTests/MTRControllerTests.m index 436a0df230e3d9..afd755f8e5e757 100644 --- a/src/darwin/Framework/CHIPTests/MTRControllerTests.m +++ b/src/darwin/Framework/CHIPTests/MTRControllerTests.m @@ -620,10 +620,13 @@ - (void)testControllerSignerKeyWithIntermediate __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -860,10 +863,12 @@ - (void)testControllerRotateToICA __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = intermediateKeys.copyPublicKey; + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -922,10 +927,13 @@ - (void)testControllerRotateFromICA __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -986,10 +994,13 @@ - (void)testControllerRotateICA __auto_type * intermediateKeys1 = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys1); + __auto_type * intermediate1PublicKey = [intermediateKeys1 copyPublicKey]; + XCTAssert(intermediate1PublicKey != NULL); + CFAutorelease(intermediate1PublicKey); __auto_type * intermediate1 = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys1.publicKey + intermediatePublicKey:intermediate1PublicKey issuerID:nil fabricID:nil error:nil]; @@ -997,10 +1008,13 @@ - (void)testControllerRotateICA __auto_type * intermediateKeys2 = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys2); + __auto_type * intermediate2PublicKey = [intermediateKeys2 copyPublicKey]; + XCTAssert(intermediate2PublicKey != NULL); + CFAutorelease(intermediate2PublicKey); __auto_type * intermediate2 = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys2.publicKey + intermediatePublicKey:intermediate2PublicKey issuerID:nil fabricID:nil error:nil]; @@ -1061,10 +1075,13 @@ - (void)testControllerICAWithoutRoot __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -1104,10 +1121,13 @@ - (void)testControllerProvideFullCertChain __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; @@ -1115,10 +1135,13 @@ - (void)testControllerProvideFullCertChain __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:intermediateKeys signingCertificate:intermediate - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@123 nodeID:@456 caseAuthenticatedTags:nil @@ -1179,10 +1202,13 @@ - (void)testControllerProvideCertChainNoICA __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:root - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@123 nodeID:@456 caseAuthenticatedTags:nil @@ -1229,10 +1255,13 @@ - (void)testControllerCertChainFabricMismatchRoot __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:root - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@123 nodeID:@456 caseAuthenticatedTags:nil @@ -1273,10 +1302,13 @@ - (void)testControllerCertChainFabricMismatchIntermediate __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:@111 error:nil]; @@ -1284,10 +1316,13 @@ - (void)testControllerCertChainFabricMismatchIntermediate __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:intermediateKeys signingCertificate:intermediate - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:@123 nodeID:@456 caseAuthenticatedTags:nil diff --git a/src/darwin/Framework/CHIPTests/MTRFabricInfoTests.m b/src/darwin/Framework/CHIPTests/MTRFabricInfoTests.m index a98067098688b5..acdc0ea45ff572 100644 --- a/src/darwin/Framework/CHIPTests/MTRFabricInfoTests.m +++ b/src/darwin/Framework/CHIPTests/MTRFabricInfoTests.m @@ -157,10 +157,13 @@ - (void)testFabricInfoTwoFabrics __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); + __auto_type * intermediatePublicKey = intermediateKeys.copyPublicKey; + XCTAssert(intermediatePublicKey != NULL); + CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediateKeys.publicKey + intermediatePublicKey:intermediatePublicKey issuerID:nil fabricID:nil error:nil]; diff --git a/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m b/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m index 1ead4692a2b335..3aeadf03730a78 100644 --- a/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m +++ b/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m @@ -403,9 +403,13 @@ - (nullable MTRDeviceController *)startControllerWithRootKeys:(MTRTestKeys *)roo XCTAssertNil(*error); XCTAssertNotNil(root); + __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; + XCTAssert(operationalPublicKey != NULL); + CFAutorelease(operationalPublicKey); + __auto_type * operational = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:root - operationalPublicKey:operationalKeys.publicKey + operationalPublicKey:operationalPublicKey fabricID:fabricID nodeID:nodeID caseAuthenticatedTags:caseAuthenticatedTags diff --git a/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestKeys.m b/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestKeys.m index e6a74f25bdeccf..090593a41babfb 100644 --- a/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestKeys.m +++ b/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestKeys.m @@ -31,6 +31,12 @@ - (NSData *)publicKeyData return (__bridge_transfer NSData *) SecKeyCopyExternalRepresentation([self publicKey], nil); } +- (SecKeyRef)copyPublicKey +{ + CFRetain(_publicKey); + return _publicKey; +} + - (instancetype)init { if (!(self = [super init])) { From a3140e2a796c58874eb8e5c39660fdfaf5c4494f Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 31 Oct 2024 23:50:27 -0400 Subject: [PATCH 045/121] Remove _storedCompressedFabricID on MTRDeviceController. (#36330) Both subclasses override the getter, so we should just mark it as abstract and stop pretending to have state we don't actually have. --- src/darwin/Framework/CHIP/MTRDeviceController.mm | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index 1085595a3ebd19..b5530e24117c17 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -53,7 +53,6 @@ #include #include -#include #include #import @@ -94,8 +93,6 @@ - (instancetype)initWithDelegate:(id)delegate queue @implementation MTRDeviceController { os_unfair_lock _underlyingDeviceMapLock; - std::atomic> _storedCompressedFabricID; - // For now, we just ensure that access to _suspended is atomic, but don't // guarantee atomicity of the the entire suspend/resume operation. The // expectation is that suspend/resume on a given controller happen on some @@ -504,8 +501,8 @@ - (void)asyncDispatchToMatterQueue:(dispatch_block_t)block errorHandler:(nullabl - (nullable NSNumber *)compressedFabricID { - auto storedValue = _storedCompressedFabricID.load(); - return storedValue.has_value() ? @(storedValue.value()) : nil; + MTR_ABSTRACT_METHOD(); + return nil; } #ifdef DEBUG From 87205958cd5761c42baa31d1339ca1ea46c9238c Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 1 Nov 2024 01:21:39 -0400 Subject: [PATCH 046/121] Move the controllerDataStore property to MTRDeviceController_Concrete. (#36331) Non-concrete controllers are not initialized with a datastore. --- .../CHIP/MTRDeviceControllerStartupParams.mm | 3 ++- ...TRDeviceControllerStartupParams_Internal.h | 5 +++- .../CHIP/MTRDeviceController_Concrete.h | 6 +++++ .../CHIP/MTRDeviceController_Internal.h | 6 ----- .../Framework/CHIP/MTRDevice_Concrete.mm | 26 ++++++++++--------- 5 files changed, 26 insertions(+), 20 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams.mm b/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams.mm index 6a64b6ee84ac8d..e3d3ad1de4f990 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams.mm @@ -18,6 +18,7 @@ #import "MTRCertificates.h" #import "MTRConversion.h" #import "MTRDeviceControllerStartupParams_Internal.h" +#import "MTRDeviceController_Concrete.h" #import "MTRDeviceController_Internal.h" #import "MTRLogging_Internal.h" #import "MTRP256KeypairBridge.h" @@ -596,7 +597,7 @@ - (instancetype)initForExistingFabric:(FabricTable *)fabricTable return self; } -- (instancetype)initForNewController:(MTRDeviceController *)controller +- (instancetype)initForNewController:(MTRDeviceController_Concrete *)controller fabricTable:(chip::FabricTable *)fabricTable keystore:(chip::Crypto::OperationalKeystore *)keystore advertiseOperational:(BOOL)advertiseOperational diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams_Internal.h index 0b4065f491873b..35ed52a3a6de78 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerStartupParams_Internal.h @@ -26,6 +26,9 @@ #include #include +// MTRDeviceController_Concrete.h imports this header, so we can't import it. +@class MTRDeviceController_Concrete; + namespace chip { class FabricTable; @@ -157,7 +160,7 @@ NS_ASSUME_NONNULL_BEGIN /** * Initialize for controller bringup with per-controller storage. */ -- (instancetype)initForNewController:(MTRDeviceController *)controller +- (instancetype)initForNewController:(MTRDeviceController_Concrete *)controller fabricTable:(chip::FabricTable *)fabricTable keystore:(chip::Crypto::OperationalKeystore *)keystore advertiseOperational:(BOOL)advertiseOperational diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h index 0f2b113af248aa..606d430847368e 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Concrete.h @@ -28,6 +28,7 @@ #import "MTRAsyncWorkQueue.h" #import "MTRDeviceConnectionBridge.h" +#import "MTRDeviceControllerDataStore.h" #import "MTRDeviceControllerStartupParams_Internal.h" #include @@ -233,6 +234,11 @@ NS_ASSUME_NONNULL_BEGIN */ @property (nonatomic, readonly) MTRAsyncWorkQueue * concurrentSubscriptionPool; +/** + * The per-controller data store this controller was initialized with, if any. + */ +@property (nonatomic, readonly, nullable) MTRDeviceControllerDataStore * controllerDataStore; + @end NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h index 6a8539d980c1f3..8fc93b6235015c 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h +++ b/src/darwin/Framework/CHIP/MTRDeviceController_Internal.h @@ -30,7 +30,6 @@ #import "MTRBaseDevice.h" #import "MTRDeviceClusterData.h" #import "MTRDeviceController.h" -#import "MTRDeviceControllerDataStore.h" #import "MTRDeviceControllerDelegate.h" #import "MTRDeviceStorageBehaviorConfiguration.h" @@ -65,11 +64,6 @@ NS_ASSUME_NONNULL_BEGIN */ @property (nonatomic, readonly, nullable) NSNumber * compressedFabricID; -/** - * The per-controller data store this controller was initialized with, if any. - */ -@property (nonatomic, readonly, nullable) MTRDeviceControllerDataStore * controllerDataStore; - /** * OTA delegate and its queue, if this controller supports OTA. Either both * will be non-nil or both will be nil. diff --git a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm index a613240fd76fa3..437b1a0676b97b 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm @@ -71,6 +71,9 @@ @interface MTRDevice_Concrete () @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); @@ -901,7 +904,7 @@ - (void)_triggerResubscribeWithReason:(NSString *)reason nodeLikelyReachable:(BO } else if (_internalDeviceState == MTRInternalDeviceStateSubscribing && nodeLikelyReachable) { // If we have reason to suspect that the node is now reachable and we haven’t established a // CASE session yet, let’s consider it to be stalled and invalidate the pairing session. - [[self _concreteController] asyncGetCommissionerOnMatterQueue:^(Controller::DeviceCommissioner * commissioner) { + [self._concreteController asyncGetCommissionerOnMatterQueue:^(Controller::DeviceCommissioner * commissioner) { auto caseSessionMgr = commissioner->CASESessionMgr(); VerifyOrDie(caseSessionMgr != nullptr); caseSessionMgr->ReleaseSession(commissioner->GetPeerScopedId(self->_nodeID.unsignedLongLongValue)); @@ -1245,7 +1248,7 @@ - (void)_scheduleSubscriptionPoolWork:(dispatch_block_t)workBlock inNanoseconds: workBlock(); }]; - [[[self _concreteController] concurrentSubscriptionPool] enqueueWorkItem:workItem description:description]; + [self._concreteController.concurrentSubscriptionPool enqueueWorkItem:workItem description:description]; MTR_LOG("%@ - enqueued in the subscription pool", self); }; @@ -1547,7 +1550,7 @@ - (void)_persistClusterData // storage implementation, which will try to read them later. Make sure // we snapshot the state here instead of handing out live copies. NSDictionary * clusterData = [self _clusterDataToPersistSnapshot]; - [_deviceController.controllerDataStore storeClusterData:clusterData forNodeID:_nodeID]; + [self._concreteController.controllerDataStore storeClusterData:clusterData forNodeID:_nodeID]; for (MTRClusterPath * clusterPath in _clusterDataToPersist) { [_persistedClusterData setObject:_clusterDataToPersist[clusterPath] forKey:clusterPath]; [_persistedClusters addObject:clusterPath]; @@ -2140,7 +2143,7 @@ - (void)_reconcilePersistedClustersWithStorage NSMutableSet * clusterPathsToRemove = [NSMutableSet set]; for (MTRClusterPath * clusterPath in _persistedClusters) { - MTRDeviceClusterData * data = [_deviceController.controllerDataStore getStoredClusterDataForNodeID:_nodeID endpointID:clusterPath.endpoint clusterID:clusterPath.cluster]; + MTRDeviceClusterData * data = [self._concreteController.controllerDataStore getStoredClusterDataForNodeID:_nodeID endpointID:clusterPath.endpoint clusterID:clusterPath.cluster]; if (!data) { [clusterPathsToRemove addObject:clusterPath]; } @@ -2175,13 +2178,13 @@ - (nullable MTRDeviceClusterData *)_clusterDataForPath:(MTRClusterPath *)cluster return nil; } - NSAssert(_deviceController.controllerDataStore != nil, + NSAssert(self._concreteController.controllerDataStore != nil, @"How can _persistedClusters have an entry if we have no persistence?"); NSAssert(_persistedClusterData != nil, @"How can _persistedClusterData not exist if we have persisted clusters?"); // Page in the stored value for the data. - MTRDeviceClusterData * data = [_deviceController.controllerDataStore getStoredClusterDataForNodeID:_nodeID endpointID:clusterPath.endpoint clusterID:clusterPath.cluster]; + MTRDeviceClusterData * data = [self._concreteController.controllerDataStore getStoredClusterDataForNodeID:_nodeID endpointID:clusterPath.endpoint clusterID:clusterPath.cluster]; MTR_LOG("%@ cluster path %@ cache miss - load from storage success %@", self, clusterPath, MTR_YES_NO(data)); if (data != nil) { [_persistedClusterData setObject:data forKey:clusterPath]; @@ -2456,7 +2459,7 @@ - (void)_setupSubscriptionWithReason:(NSString *)reason MATTER_LOG_METRIC_BEGIN(kMetricMTRDeviceInitialSubscriptionSetup); // Call directlyGetSessionForNode because the subscription setup already goes through the subscription pool queue - [[self _concreteController] + [self._concreteController directlyGetSessionForNode:_nodeID.unsignedLongLongValue completion:^(chip::Messaging::ExchangeManager * _Nullable exchangeManager, const chip::Optional & session, NSError * _Nullable error, @@ -3429,7 +3432,7 @@ - (void)_removeClusters:(NSSet *)clusterPathsToRemove [_persistedClusterData removeObjectForKey:path]; [_clusterDataToPersist removeObjectForKey:path]; if (doRemoveFromDataStore) { - [self.deviceController.controllerDataStore clearStoredClusterDataForNodeID:self.nodeID endpointID:path.endpoint clusterID:path.cluster]; + [self._concreteController.controllerDataStore clearStoredClusterDataForNodeID:self.nodeID endpointID:path.endpoint clusterID:path.cluster]; } } } @@ -3443,7 +3446,7 @@ - (void)_removeAttributes:(NSSet *)attributes fromCluster:(MTRCluste } // Just clear out the NSCache entry for this cluster, so we'll load it from storage as needed. [_persistedClusterData removeObjectForKey:clusterPath]; - [self.deviceController.controllerDataStore removeAttributes:attributes fromCluster:clusterPath forNodeID:self.nodeID]; + [self._concreteController.controllerDataStore removeAttributes:attributes fromCluster:clusterPath forNodeID:self.nodeID]; } - (void)_pruneEndpointsIn:(MTRDeviceDataValueDictionary)previousPartsListValue @@ -3464,7 +3467,7 @@ - (void)_pruneEndpointsIn:(MTRDeviceDataValueDictionary)previousPartsListValue } } [self _removeClusters:clusterPathsToRemove doRemoveFromDataStore:NO]; - [self.deviceController.controllerDataStore clearStoredClusterDataForNodeID:self.nodeID endpointID:endpoint]; + [self._concreteController.controllerDataStore clearStoredClusterDataForNodeID:self.nodeID endpointID:endpoint]; [_deviceController asyncDispatchToMatterQueue:^{ std::lock_guard lock(self->_lock); @@ -3792,7 +3795,7 @@ - (void)_storePersistedDeviceData { os_unfair_lock_assert_owner(&self->_lock); - auto datastore = _deviceController.controllerDataStore; + auto datastore = self._concreteController.controllerDataStore; if (datastore == nil) { // No way to store. return; @@ -4207,7 +4210,6 @@ - (void)controllerResumed [self _ensureSubscriptionForExistingDelegates:@"Controller resumed"]; } -// nullable because technically _deviceController is nullable. - (nullable MTRDeviceController_Concrete *)_concreteController { // We know our _deviceController is actually an MTRDeviceController_Concrete, since that's what From b0cc28a760b5283fea53a14885ffca418fa9a360 Mon Sep 17 00:00:00 2001 From: Anton Usmansky Date: Fri, 1 Nov 2024 10:10:42 +0300 Subject: [PATCH 047/121] [android] Feat: retry GATT_ERROR 133 on device.connectGatt fail (#34697) * feat: retry GATT_ERROR 133 on device.connectGatt fail * chore: add constant for error code 133 --- .../java/chip/platform/AndroidBleManager.java | 51 +++++++++++++++---- 1 file changed, 42 insertions(+), 9 deletions(-) diff --git a/src/platform/android/java/chip/platform/AndroidBleManager.java b/src/platform/android/java/chip/platform/AndroidBleManager.java index 52b0052d409ef8..1ca02562236ff0 100644 --- a/src/platform/android/java/chip/platform/AndroidBleManager.java +++ b/src/platform/android/java/chip/platform/AndroidBleManager.java @@ -89,6 +89,7 @@ private static class BleMtuDenylist { private static final int MSG_BLE_SCAN = 0; private static final int MSG_BLE_CONNECT = 1; private static final int MSG_BLE_CONNECT_SUCCESS = 2; + private static final int MSG_BLE_CONNECT_RETRY = 3; private static final int MSG_BLE_FAIL = 99; private static final int BLE_TIMEOUT_MS = 10000; @@ -501,7 +502,10 @@ public void handleMessage(Message msg) { break; case MSG_BLE_CONNECT: stopBleScan(); - connectBLE(msg.obj); + connectBLE(new ConnectionGattCallback((BluetoothDevice) msg.obj)); + break; + case MSG_BLE_CONNECT_RETRY: + connectBLE((ConnectionGattCallback) msg.obj); break; case MSG_BLE_CONNECT_SUCCESS: bleConnectSuccess(msg.obj); @@ -567,20 +571,16 @@ private void stopBleScan() { } } - private void connectBLE(Object bluetoothDeviceObj) { - if (bluetoothDeviceObj == null) { - return; - } - + private void connectBLE(ConnectionGattCallback callback) { // Fail Timer reset. mConnectionHandler.removeMessages(MSG_BLE_FAIL); mConnectionHandler.sendEmptyMessageDelayed(MSG_BLE_FAIL, BLE_TIMEOUT_MS); @SuppressWarnings("unchecked") - BluetoothDevice device = (BluetoothDevice) bluetoothDeviceObj; + BluetoothDevice device = callback.getTargetDevice(); Log.i(TAG, "Connecting"); - BluetoothGatt gatt = device.connectGatt(mContext, false, new ConnectionGattCallback()); + device.connectGatt(mContext, false, callback, BluetoothDevice.TRANSPORT_LE); } class ConnectionGattCallback extends AndroidBluetoothGattCallback { @@ -588,7 +588,22 @@ class ConnectionGattCallback extends AndroidBluetoothGattCallback { private static final int STATE_DISCOVER_SERVICE = 2; private static final int STATE_REQUEST_MTU = 3; + /// Unfortunately GATT 133 is very generic, however among other things + /// it may also show up on device out of range or BLE being closed due to + /// background task termination, hence it is a candidate to retry connectivity. + private static final int kGattRetryableErrorStatus = 133; + private int mState = STATE_INIT; + private BluetoothDevice mDevice; + private int connectRetriesLeft = 3; + + public ConnectionGattCallback(BluetoothDevice device) { + mDevice = device; + } + + public BluetoothDevice getTargetDevice() { + return mDevice; + } @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { @@ -599,9 +614,27 @@ public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState mState = STATE_DISCOVER_SERVICE; gatt.discoverServices(); return; - } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + } + + if (newState == BluetoothProfile.STATE_DISCONNECTED + && status == kGattRetryableErrorStatus + && connectRetriesLeft-- > 0) { + Log.i(TAG, "Retries left: " + connectRetriesLeft + ". Retrying connect..."); + + gatt.close(); + + Message msg = mConnectionHandler.obtainMessage(); + msg.what = MSG_BLE_CONNECT_RETRY; + msg.obj = (Object) this; + mConnectionHandler.sendMessage(msg); + + return; + } + + if (newState == BluetoothProfile.STATE_DISCONNECTED) { Log.i(TAG, "Services Disconnected"); } + mConnectionHandler.sendEmptyMessage(MSG_BLE_FAIL); } From b54eaf8b9ea47335a50d3db64aacc5de43300298 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 1 Nov 2024 12:48:50 -0400 Subject: [PATCH 048/121] Revert "Add new API so it's possible to not leak a key (#36299)" (#36339) This reverts commit 08024d2ddb5f330384411d55bc44e2ee9bbcad8d because it's failing CI as committed. --- .../commands/common/CHIPToolKeypair.h | 2 +- .../commands/common/CHIPToolKeypair.mm | 10 +--- src/darwin/Framework/CHIP/MTRCertificates.mm | 19 +----- .../CHIP/MTRDeviceControllerFactory.mm | 19 +----- src/darwin/Framework/CHIP/MTRKeypair.h | 15 ++--- .../Framework/CHIPTests/MTRCertificateTests.m | 60 +++++-------------- .../CHIPTests/MTRCertificateValidityTests.m | 5 +- .../CHIPTests/MTRControllerAdvertisingTests.m | 5 +- .../Framework/CHIPTests/MTRControllerTests.m | 59 ++++-------------- .../Framework/CHIPTests/MTRFabricInfoTests.m | 5 +- .../CHIPTests/MTRPerControllerStorageTests.m | 6 +- .../CHIPTests/TestHelpers/MTRTestKeys.m | 6 -- 12 files changed, 41 insertions(+), 170 deletions(-) diff --git a/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.h b/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.h index 58be7f2ac4b041..f0ee3f8db6092b 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.h +++ b/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.h @@ -22,7 +22,7 @@ @interface CHIPToolKeypair : NSObject - (BOOL)initialize; - (NSData *)signMessageECDSA_RAW:(NSData *)message; -- (SecKeyRef)copyPublicKey; +- (SecKeyRef)publicKey; - (CHIP_ERROR)Serialize:(chip::Crypto::P256SerializedKeypair &)output; - (CHIP_ERROR)Deserialize:(chip::Crypto::P256SerializedKeypair &)input; - (CHIP_ERROR)createOrLoadKeys:(id)storage; diff --git a/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.mm b/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.mm index a09975d68da41f..ce0ef5819b6ac1 100644 --- a/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.mm +++ b/examples/darwin-framework-tool/commands/common/CHIPToolKeypair.mm @@ -65,7 +65,7 @@ - (NSData *)signMessageECDSA_RAW:(NSData *)message return out_signature; } -- (SecKeyRef)copyPublicKey +- (SecKeyRef)publicKey { if (_mPublicKey == nil) { chip::Crypto::P256PublicKey publicKey = _mKeyPair.Pubkey(); @@ -79,13 +79,7 @@ - (SecKeyRef)copyPublicKey }; _mPublicKey = SecKeyCreateWithData((__bridge CFDataRef) publicKeyNSData, (__bridge CFDictionaryRef) attributes, nullptr); } - - if (_mPublicKey) { - CFRetain(_mPublicKey); - return _mPublicKey; - } - - return NULL; + return _mPublicKey; } - (CHIP_ERROR)Deserialize:(chip::Crypto::P256SerializedKeypair &)input diff --git a/src/darwin/Framework/CHIP/MTRCertificates.mm b/src/darwin/Framework/CHIP/MTRCertificates.mm index 7dcec96cba695b..b153cf4442b373 100644 --- a/src/darwin/Framework/CHIP/MTRCertificates.mm +++ b/src/darwin/Framework/CHIP/MTRCertificates.mm @@ -152,24 +152,7 @@ + (MTRCertificateDERBytes _Nullable)createOperationalCertificate:(id + (BOOL)keypair:(id)keypair matchesCertificate:(NSData *)certificate { P256PublicKey keypairPubKey; - SecKeyRef publicKey = NULL; - - if ([keypair respondsToSelector:@selector(copyPublicKey)]) { - publicKey = [keypair copyPublicKey]; - } else { - publicKey = [keypair publicKey]; - if (publicKey) { - CFRetain(publicKey); - } - } - - CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(publicKey, &keypairPubKey); - - if (publicKey != NULL) { - CFRelease(publicKey); - publicKey = NULL; - } - + CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(keypair.publicKey, &keypairPubKey); if (err != CHIP_NO_ERROR) { MTR_LOG_ERROR("Can't extract public key from keypair: %s", ErrorStr(err)); return NO; diff --git a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm index e287ef0446593f..9de51431bfe4f8 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceControllerFactory.mm @@ -819,24 +819,7 @@ - (BOOL)findMatchingFabric:(FabricTable &)fabricTable } else { // No root certificate means the nocSigner is using the root keys, because // consumers must provide a root certificate whenever an ICA is used. - SecKeyRef publicKey = NULL; - - if ([params.nocSigner respondsToSelector:@selector(copyPublicKey)]) { - publicKey = [params.nocSigner copyPublicKey]; - } else { - publicKey = [params.nocSigner publicKey]; - if (publicKey) { - CFRetain(publicKey); - } - } - - CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(publicKey, &pubKey); - - if (publicKey != NULL) { - CFRelease(publicKey); - publicKey = NULL; - } - + CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(params.nocSigner.publicKey, &pubKey); if (err != CHIP_NO_ERROR) { MTR_LOG_ERROR("Can't extract public key from MTRKeypair: %s", ErrorStr(err)); return NO; diff --git a/src/darwin/Framework/CHIP/MTRKeypair.h b/src/darwin/Framework/CHIP/MTRKeypair.h index d7381fe096f900..a4e4521b2864a6 100644 --- a/src/darwin/Framework/CHIP/MTRKeypair.h +++ b/src/darwin/Framework/CHIP/MTRKeypair.h @@ -16,7 +16,6 @@ */ #import -#import #import NS_ASSUME_NONNULL_BEGIN @@ -32,19 +31,13 @@ NS_ASSUME_NONNULL_BEGIN * framework APIs. */ @protocol MTRKeypair - -@optional +@required /** - * @brief Returns a copy of the public key for the keypair. + * @brief Return public key for the keypair. */ -- (SecKeyRef)copyPublicKey MTR_NEWLY_AVAILABLE; - -/** - * @brief Returns public key for the keypair without adding a reference. DEPRECATED - please use copyPublicKey, otherwise this will leak. - */ - -- (SecKeyRef)publicKey MTR_DEPRECATED("Please implement copyPublicKey, this will leak otherwise", ios(16.1, 18.3), macos(13.0, 15.3), watchos(9.1, 11.3), tvos(16.1, 18.3)); +- (SecKeyRef)publicKey; +@optional /** * @brief A function to sign a message using ECDSA * diff --git a/src/darwin/Framework/CHIPTests/MTRCertificateTests.m b/src/darwin/Framework/CHIPTests/MTRCertificateTests.m index d5be54e43816e9..fb6cfb9ecb7e67 100644 --- a/src/darwin/Framework/CHIPTests/MTRCertificateTests.m +++ b/src/darwin/Framework/CHIPTests/MTRCertificateTests.m @@ -127,13 +127,9 @@ - (void)testGenerateIntermediateCert __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); - __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; - XCTAssert(intermediatePublicKey != NULL); - CFAutorelease(intermediatePublicKey); - __auto_type * intermediateCert = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:rootCert - intermediatePublicKey:intermediatePublicKey + intermediatePublicKey:intermediateKeys.publicKey issuerID:nil fabricID:nil error:nil]; @@ -159,16 +155,13 @@ - (void)testGenerateIntermediateCertWithValidityPeriod __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); - __auto_type * intermediatePublicKey = intermediateKeys.copyPublicKey; - XCTAssert(intermediatePublicKey != NULL); - CFAutorelease(intermediatePublicKey); __auto_type * startDate = [MTRCertificateTests startDateWithTimeIntervalSinceNow:300]; __auto_type * validityPeriod = [[NSDateInterval alloc] initWithStartDate:startDate duration:400]; __auto_type * intermediateCert = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:rootCert - intermediatePublicKey:intermediatePublicKey + intermediatePublicKey:intermediateKeys.publicKey issuerID:nil fabricID:nil validityPeriod:validityPeriod @@ -199,16 +192,13 @@ - (void)testGenerateIntermediateCertWithInfiniteValidity __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); - __auto_type * intermediatePublicKey = intermediateKeys.copyPublicKey; - XCTAssert(intermediatePublicKey != NULL); - CFAutorelease(intermediatePublicKey); __auto_type * startDate = [MTRCertificateTests startDateWithTimeIntervalSinceNow:300]; __auto_type * validityPeriod = [[NSDateInterval alloc] initWithStartDate:startDate endDate:[NSDate distantFuture]]; __auto_type * intermediateCert = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:rootCert - intermediatePublicKey:intermediatePublicKey + intermediatePublicKey:intermediateKeys.publicKey issuerID:nil fabricID:nil validityPeriod:validityPeriod @@ -239,9 +229,6 @@ - (void)testGenerateOperationalCertNoIntermediate __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); - __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; - XCTAssert(operationalPublicKey != NULL); - CFAutorelease(operationalPublicKey); __auto_type * cats = [[NSMutableSet alloc] initWithCapacity:3]; // High bits are identifier, low bits are version. @@ -251,7 +238,7 @@ - (void)testGenerateOperationalCertNoIntermediate __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:cats @@ -278,9 +265,6 @@ - (void)testGenerateOperationalCertNoIntermediateWithValidityPeriod __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); - __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; - XCTAssert(operationalPublicKey != NULL); - CFAutorelease(operationalPublicKey); __auto_type * cats = [[NSMutableSet alloc] initWithCapacity:3]; // High bits are identifier, low bits are version. @@ -293,7 +277,7 @@ - (void)testGenerateOperationalCertNoIntermediateWithValidityPeriod __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:cats @@ -325,9 +309,6 @@ - (void)testGenerateOperationalCertNoIntermediateWithInfiniteValidity __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); - __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; - XCTAssert(operationalPublicKey != NULL); - CFAutorelease(operationalPublicKey); __auto_type * cats = [[NSMutableSet alloc] initWithCapacity:3]; // High bits are identifier, low bits are version. @@ -340,7 +321,7 @@ - (void)testGenerateOperationalCertNoIntermediateWithInfiniteValidity __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:cats @@ -372,13 +353,10 @@ - (void)testGenerateOperationalCertWithIntermediate __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); - __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; - XCTAssert(intermediatePublicKey != NULL); - CFAutorelease(intermediatePublicKey); __auto_type * intermediateCert = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:rootCert - intermediatePublicKey:intermediatePublicKey + intermediatePublicKey:intermediateKeys.publicKey issuerID:nil fabricID:nil error:nil]; @@ -386,13 +364,10 @@ - (void)testGenerateOperationalCertWithIntermediate __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); - __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; - XCTAssert(operationalPublicKey != NULL); - CFAutorelease(operationalPublicKey); __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:intermediateKeys signingCertificate:intermediateCert - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:nil @@ -419,9 +394,6 @@ - (void)testGenerateOperationalCertErrorCases __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); - __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; - XCTAssert(operationalPublicKey != NULL); - CFAutorelease(operationalPublicKey); __auto_type * longCats = [[NSMutableSet alloc] initWithCapacity:4]; [longCats addObject:@0x00010001]; @@ -443,7 +415,7 @@ - (void)testGenerateOperationalCertErrorCases // Check basic case works __auto_type * operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:nil @@ -453,7 +425,7 @@ - (void)testGenerateOperationalCertErrorCases // CATs too long operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:longCats @@ -463,7 +435,7 @@ - (void)testGenerateOperationalCertErrorCases // Multiple CATs with the same identifier but different versions operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:catsWithSameIdentifier @@ -473,7 +445,7 @@ - (void)testGenerateOperationalCertErrorCases // CAT with invalid version operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:catsWithInvalidVersion @@ -483,7 +455,7 @@ - (void)testGenerateOperationalCertErrorCases // Signing key mismatch operationalCert = [MTRCertificates createOperationalCertificate:operationalKeys signingCertificate:rootCert - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@1 nodeID:@1 caseAuthenticatedTags:nil @@ -493,7 +465,7 @@ - (void)testGenerateOperationalCertErrorCases // Invalid fabric id operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@0 nodeID:@1 caseAuthenticatedTags:nil @@ -503,7 +475,7 @@ - (void)testGenerateOperationalCertErrorCases // Undefined node id operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@1 nodeID:@0 caseAuthenticatedTags:nil @@ -513,7 +485,7 @@ - (void)testGenerateOperationalCertErrorCases // Non-operational node id operationalCert = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:rootCert - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@1 nodeID:@(0xFFFFFFFFFFFFFFFFLLU) caseAuthenticatedTags:nil diff --git a/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m b/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m index 719be071063fbe..ecc593e8432045 100644 --- a/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m +++ b/src/darwin/Framework/CHIPTests/MTRCertificateValidityTests.m @@ -259,13 +259,10 @@ - (void)initStack:(MTRTestCertificateIssuer *)certificateIssuer __auto_type * controllerOperationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(controllerOperationalKeys); - __auto_type * controllerPublicKey = controllerOperationalKeys.copyPublicKey; - XCTAssert(controllerPublicKey != NULL); - CFAutorelease(controllerPublicKey); __auto_type * controllerOperationalCert = [certificateIssuer issueOperationalCertificateForNode:@(kControllerId) - operationalPublicKey:controllerPublicKey]; + operationalPublicKey:controllerOperationalKeys.publicKey]; XCTAssertNotNil(controllerOperationalCert); __auto_type * params = [[MTRDeviceControllerStartupParams alloc] initWithIPK:certificateIssuer.rootKey.ipk diff --git a/src/darwin/Framework/CHIPTests/MTRControllerAdvertisingTests.m b/src/darwin/Framework/CHIPTests/MTRControllerAdvertisingTests.m index bee6ee90df3524..4092a38b56f84e 100644 --- a/src/darwin/Framework/CHIPTests/MTRControllerAdvertisingTests.m +++ b/src/darwin/Framework/CHIPTests/MTRControllerAdvertisingTests.m @@ -164,13 +164,10 @@ - (nullable MTRDeviceController *)startControllerWithRootKeys:(MTRTestKeys *)roo __auto_type * root = [MTRCertificates createRootCertificate:rootKeys issuerID:@(1) fabricID:nil error:error]; XCTAssertNil(*error); XCTAssertNotNil(root); - __auto_type * publicKey = operationalKeys.copyPublicKey; - XCTAssert(publicKey != NULL); - CFAutorelease(publicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:root - operationalPublicKey:publicKey + operationalPublicKey:operationalKeys.publicKey fabricID:fabricID nodeID:nodeID caseAuthenticatedTags:nil diff --git a/src/darwin/Framework/CHIPTests/MTRControllerTests.m b/src/darwin/Framework/CHIPTests/MTRControllerTests.m index afd755f8e5e757..436a0df230e3d9 100644 --- a/src/darwin/Framework/CHIPTests/MTRControllerTests.m +++ b/src/darwin/Framework/CHIPTests/MTRControllerTests.m @@ -620,13 +620,10 @@ - (void)testControllerSignerKeyWithIntermediate __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); - __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; - XCTAssert(intermediatePublicKey != NULL); - CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediatePublicKey + intermediatePublicKey:intermediateKeys.publicKey issuerID:nil fabricID:nil error:nil]; @@ -863,12 +860,10 @@ - (void)testControllerRotateToICA __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); - __auto_type * intermediatePublicKey = intermediateKeys.copyPublicKey; - CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediatePublicKey + intermediatePublicKey:intermediateKeys.publicKey issuerID:nil fabricID:nil error:nil]; @@ -927,13 +922,10 @@ - (void)testControllerRotateFromICA __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); - __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; - XCTAssert(intermediatePublicKey != NULL); - CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediatePublicKey + intermediatePublicKey:intermediateKeys.publicKey issuerID:nil fabricID:nil error:nil]; @@ -994,13 +986,10 @@ - (void)testControllerRotateICA __auto_type * intermediateKeys1 = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys1); - __auto_type * intermediate1PublicKey = [intermediateKeys1 copyPublicKey]; - XCTAssert(intermediate1PublicKey != NULL); - CFAutorelease(intermediate1PublicKey); __auto_type * intermediate1 = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediate1PublicKey + intermediatePublicKey:intermediateKeys1.publicKey issuerID:nil fabricID:nil error:nil]; @@ -1008,13 +997,10 @@ - (void)testControllerRotateICA __auto_type * intermediateKeys2 = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys2); - __auto_type * intermediate2PublicKey = [intermediateKeys2 copyPublicKey]; - XCTAssert(intermediate2PublicKey != NULL); - CFAutorelease(intermediate2PublicKey); __auto_type * intermediate2 = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediate2PublicKey + intermediatePublicKey:intermediateKeys2.publicKey issuerID:nil fabricID:nil error:nil]; @@ -1075,13 +1061,10 @@ - (void)testControllerICAWithoutRoot __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); - __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; - XCTAssert(intermediatePublicKey != NULL); - CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediatePublicKey + intermediatePublicKey:intermediateKeys.publicKey issuerID:nil fabricID:nil error:nil]; @@ -1121,13 +1104,10 @@ - (void)testControllerProvideFullCertChain __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); - __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; - XCTAssert(intermediatePublicKey != NULL); - CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediatePublicKey + intermediatePublicKey:intermediateKeys.publicKey issuerID:nil fabricID:nil error:nil]; @@ -1135,13 +1115,10 @@ - (void)testControllerProvideFullCertChain __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); - __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; - XCTAssert(operationalPublicKey != NULL); - CFAutorelease(operationalPublicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:intermediateKeys signingCertificate:intermediate - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@123 nodeID:@456 caseAuthenticatedTags:nil @@ -1202,13 +1179,10 @@ - (void)testControllerProvideCertChainNoICA __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); - __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; - XCTAssert(operationalPublicKey != NULL); - CFAutorelease(operationalPublicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:root - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@123 nodeID:@456 caseAuthenticatedTags:nil @@ -1255,13 +1229,10 @@ - (void)testControllerCertChainFabricMismatchRoot __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); - __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; - XCTAssert(operationalPublicKey != NULL); - CFAutorelease(operationalPublicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:root - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@123 nodeID:@456 caseAuthenticatedTags:nil @@ -1302,13 +1273,10 @@ - (void)testControllerCertChainFabricMismatchIntermediate __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); - __auto_type * intermediatePublicKey = [intermediateKeys copyPublicKey]; - XCTAssert(intermediatePublicKey != NULL); - CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediatePublicKey + intermediatePublicKey:intermediateKeys.publicKey issuerID:nil fabricID:@111 error:nil]; @@ -1316,13 +1284,10 @@ - (void)testControllerCertChainFabricMismatchIntermediate __auto_type * operationalKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(operationalKeys); - __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; - XCTAssert(operationalPublicKey != NULL); - CFAutorelease(operationalPublicKey); __auto_type * operational = [MTRCertificates createOperationalCertificate:intermediateKeys signingCertificate:intermediate - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:@123 nodeID:@456 caseAuthenticatedTags:nil diff --git a/src/darwin/Framework/CHIPTests/MTRFabricInfoTests.m b/src/darwin/Framework/CHIPTests/MTRFabricInfoTests.m index acdc0ea45ff572..a98067098688b5 100644 --- a/src/darwin/Framework/CHIPTests/MTRFabricInfoTests.m +++ b/src/darwin/Framework/CHIPTests/MTRFabricInfoTests.m @@ -157,13 +157,10 @@ - (void)testFabricInfoTwoFabrics __auto_type * intermediateKeys = [[MTRTestKeys alloc] init]; XCTAssertNotNil(intermediateKeys); - __auto_type * intermediatePublicKey = intermediateKeys.copyPublicKey; - XCTAssert(intermediatePublicKey != NULL); - CFAutorelease(intermediatePublicKey); __auto_type * intermediate = [MTRCertificates createIntermediateCertificate:rootKeys rootCertificate:root - intermediatePublicKey:intermediatePublicKey + intermediatePublicKey:intermediateKeys.publicKey issuerID:nil fabricID:nil error:nil]; diff --git a/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m b/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m index 3aeadf03730a78..1ead4692a2b335 100644 --- a/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m +++ b/src/darwin/Framework/CHIPTests/MTRPerControllerStorageTests.m @@ -403,13 +403,9 @@ - (nullable MTRDeviceController *)startControllerWithRootKeys:(MTRTestKeys *)roo XCTAssertNil(*error); XCTAssertNotNil(root); - __auto_type * operationalPublicKey = [operationalKeys copyPublicKey]; - XCTAssert(operationalPublicKey != NULL); - CFAutorelease(operationalPublicKey); - __auto_type * operational = [MTRCertificates createOperationalCertificate:rootKeys signingCertificate:root - operationalPublicKey:operationalPublicKey + operationalPublicKey:operationalKeys.publicKey fabricID:fabricID nodeID:nodeID caseAuthenticatedTags:caseAuthenticatedTags diff --git a/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestKeys.m b/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestKeys.m index 090593a41babfb..e6a74f25bdeccf 100644 --- a/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestKeys.m +++ b/src/darwin/Framework/CHIPTests/TestHelpers/MTRTestKeys.m @@ -31,12 +31,6 @@ - (NSData *)publicKeyData return (__bridge_transfer NSData *) SecKeyCopyExternalRepresentation([self publicKey], nil); } -- (SecKeyRef)copyPublicKey -{ - CFRetain(_publicKey); - return _publicKey; -} - - (instancetype)init { if (!(self = [super init])) { From ddd8e0b6e819459e2297e1fcf749628757c13058 Mon Sep 17 00:00:00 2001 From: Justin Wood Date: Fri, 1 Nov 2024 10:19:35 -0700 Subject: [PATCH 049/121] Update qemu.yaml Renaming this, so we can differentiate it --- .github/workflows/qemu.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/qemu.yaml b/.github/workflows/qemu.yaml index 783c46ef4100ee..5f9bbe7022826d 100644 --- a/.github/workflows/qemu.yaml +++ b/.github/workflows/qemu.yaml @@ -32,7 +32,7 @@ env: jobs: qemu-esp32: - name: ESP32 + name: ESP32_QEMU env: BUILD_TYPE: esp32-qemu From f3a9fe9df28b2008e8d0f6b2cb70ef6f3c73404b Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Fri, 1 Nov 2024 15:25:24 -0400 Subject: [PATCH 050/121] Remove unused checkIsRunning on MTRDeviceController. (#36337) Only MTRDeviceController_Concrete needs to do checkIsRunning at this point, and it implements that itself. --- .../Framework/CHIP/MTRDeviceController.mm | 22 ------------------- 1 file changed, 22 deletions(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController.mm b/src/darwin/Framework/CHIP/MTRDeviceController.mm index b5530e24117c17..5cee77cb663bb8 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController.mm @@ -57,9 +57,6 @@ #import -// TODO: These strings and their consumers in this file should probably go away, -// since none of them really apply to all controllers. -static NSString * const kErrorNotRunning = @"Controller is not running. Call startup first."; static NSString * const kErrorSpake2pVerifierGenerationFailed = @"PASE verifier generation failed"; static NSString * const kErrorSpake2pVerifierSerializationFailed = @"PASE verifier serialization failed"; @@ -473,25 +470,6 @@ + (BOOL)checkForError:(CHIP_ERROR)errorCode logMsg:(NSString *)logMsg error:(NSE return YES; } -- (BOOL)checkIsRunning -{ - return [self checkIsRunning:nil]; -} - -- (BOOL)checkIsRunning:(NSError * __autoreleasing *)error -{ - if ([self isRunning]) { - return YES; - } - - MTR_LOG_ERROR("%@: %@ Error: %s", NSStringFromClass(self.class), self, [kErrorNotRunning UTF8String]); - if (error) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; - } - - return NO; -} - - (void)asyncDispatchToMatterQueue:(dispatch_block_t)block errorHandler:(nullable MTRDeviceErrorHandler)errorHandler { // TODO: Figure out how to get callsites to have an MTRDeviceController_Concrete. From 744f45cc886210ee95404ea659fd0327f818e891 Mon Sep 17 00:00:00 2001 From: Justin Wood Date: Fri, 1 Nov 2024 18:13:13 -0700 Subject: [PATCH 051/121] Fixing crash (#36343) --- src/darwin/Framework/CHIP/MTRDeviceConnectivityMonitor.mm | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/darwin/Framework/CHIP/MTRDeviceConnectivityMonitor.mm b/src/darwin/Framework/CHIP/MTRDeviceConnectivityMonitor.mm index 6a9ac601d41b6f..530d608fd63b29 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceConnectivityMonitor.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceConnectivityMonitor.mm @@ -120,6 +120,10 @@ - (void)handleResolvedHostname:(const char *)hostName port:(uint16_t)port error: { std::lock_guard lock(sConnectivityMonitorLock); + if (hostName == NULL) { + MTR_LOG_ERROR("%@ NULL host resolved, ignoring", self); + return; + } // dns_sd.h: must check and call deallocate if error is kDNSServiceErr_ServiceNotRunning if (error == kDNSServiceErr_ServiceNotRunning) { MTR_LOG_ERROR("%@ disconnected from dns-sd subsystem", self); From eb551f70f9e818c4225db7afd69c6ba0b8d11cf0 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Mon, 4 Nov 2024 14:04:40 +0100 Subject: [PATCH 052/121] Create a Second Test Context for TestReadInteraction (#36314) * Run TestReadInteraction tests against sync fixture * Run all unit tests on both fixtures * Restyled by clang-format * Fix issues reported by clang-tidy --------- Co-authored-by: Restyled.io --- src/app/tests/TestReadInteraction.cpp | 400 +++++++++++++++------- src/lib/support/tests/ExtraPwTestMacros.h | 16 +- 2 files changed, 291 insertions(+), 125 deletions(-) diff --git a/src/app/tests/TestReadInteraction.cpp b/src/app/tests/TestReadInteraction.cpp index 5baab570f6e071..f997266b935c09 100644 --- a/src/app/tests/TestReadInteraction.cpp +++ b/src/app/tests/TestReadInteraction.cpp @@ -286,28 +286,23 @@ namespace app { using Seconds16 = System::Clock::Seconds16; using Milliseconds32 = System::Clock::Milliseconds32; -// TODO: Add support for a 2nd Test Context by making sSyncScheduler = true (this was not ported from NL Tests yet) class TestReadInteraction : public chip::Test::AppContext { - public: - static void SetUpTestSuite() + static void SetUpTestSuiteCommon(bool syncScheduler = false) { AppContext::SetUpTestSuite(); gRealClock = &chip::System::SystemClock(); chip::System::Clock::Internal::SetSystemClockForTesting(&gMockClock); - if (sSyncScheduler) - { - gReportScheduler = chip::app::reporting::GetSynchronizedReportScheduler(); - sUsingSubSync = true; - } - else - { - gReportScheduler = chip::app::reporting::GetDefaultReportScheduler(); - } + sUsingSubSync = syncScheduler; + gReportScheduler = syncScheduler ? chip::app::reporting::GetSynchronizedReportScheduler() + : chip::app::reporting::GetDefaultReportScheduler(); } + + static void SetUpTestSuite() { SetUpTestSuiteCommon(false); } + static void TearDownTestSuite() { chip::System::Clock::Internal::SetSystemClockForTesting(gRealClock); @@ -332,6 +327,7 @@ class TestReadInteraction : public chip::Test::AppContext chip::Test::SetMockNodeConfig(TestMockNodeConfig()); chip::Test::SetVersionTo(chip::Test::kTestDataVersion1); } + void TearDown() override { chip::Test::ResetMockNodeConfig(); @@ -340,43 +336,66 @@ class TestReadInteraction : public chip::Test::AppContext AppContext::TearDown(); } + void TestICDProcessSubscribeRequestInfMaxIntervalCeiling(); + void TestICDProcessSubscribeRequestInvalidIdleModeDuration(); + void TestICDProcessSubscribeRequestMaxMinInterval(); + void TestICDProcessSubscribeRequestSupMaxIntervalCeiling(); + void TestICDProcessSubscribeRequestSupMinInterval(); + void TestPostSubscribeRoundtripChunkReport(); + void TestPostSubscribeRoundtripChunkReportTimeout(); + void TestPostSubscribeRoundtripChunkStatusReportTimeout(); + void TestPostSubscribeRoundtripStatusReportTimeout(); + void TestProcessSubscribeRequest(); + void TestReadChunking(); + void TestReadChunkingInvalidSubscriptionId(); + void TestReadChunkingStatusReportTimeout(); void TestReadClient(); - void TestReadUnexpectedSubscriptionId(); - void TestReadHandler(); - void TestReadHandlerSetMaxReportingInterval(); void TestReadClientGenerateAttributePathList(); void TestReadClientGenerateInvalidAttributePathList(); - void TestReadClientInvalidReport(); - void TestReadClientInvalidAttributeId(); - void TestReadHandlerInvalidAttributePath(); void TestReadClientGenerateOneEventPaths(); void TestReadClientGenerateTwoEventPaths(); - void TestProcessSubscribeRequest(); - void TestICDProcessSubscribeRequestSupMaxIntervalCeiling(); - void TestICDProcessSubscribeRequestInfMaxIntervalCeiling(); - void TestICDProcessSubscribeRequestSupMinInterval(); - void TestICDProcessSubscribeRequestMaxMinInterval(); - void TestICDProcessSubscribeRequestInvalidIdleModeDuration(); - void TestSubscribeRoundtrip(); - void TestSubscribeEarlyReport(); - void TestSubscribeUrgentWildcardEvent(); - void TestSubscribeInvalidAttributePathRoundtrip(); - void TestPostSubscribeRoundtripStatusReportTimeout(); + void TestReadClientInvalidAttributeId(); + void TestReadClientInvalidReport(); void TestReadClientReceiveInvalidMessage(); - void TestSubscribeClientReceiveInvalidStatusResponse(); - void TestSubscribeClientReceiveWellFormedStatusResponse(); + void TestReadHandler(); + void TestReadHandlerInvalidAttributePath(); + void TestReadHandlerInvalidSubscribeRequest(); + void TestReadHandlerMalformedReadRequest1(); + void TestReadHandlerMalformedReadRequest2(); + void TestReadHandlerMalformedSubscribeRequest(); + void TestReadHandlerSetMaxReportingInterval(); + void TestReadInvalidAttributePathRoundtrip(); + void TestReadReportFailure(); + void TestReadRoundtrip(); + void TestReadRoundtripWithDataVersionFilter(); + void TestReadRoundtripWithMultiSamePathDifferentDataVersionFilter(); + void TestReadRoundtripWithNoMatchPathDataVersionFilter(); + void TestReadRoundtripWithSameDifferentPathsDataVersionFilter(); + void TestReadShutdown(); + void TestReadUnexpectedSubscriptionId(); + void TestReadWildcard(); + void TestSetDirtyBetweenChunks(); + void TestShutdownSubscription(); void TestSubscribeClientReceiveInvalidReportMessage(); - void TestSubscribeClientReceiveUnsolicitedInvalidReportMessage(); + void TestSubscribeClientReceiveInvalidStatusResponse(); void TestSubscribeClientReceiveInvalidSubscribeResponseMessage(); + void TestSubscribeClientReceiveUnsolicitedInvalidReportMessage(); void TestSubscribeClientReceiveUnsolicitedReportMessageWithInvalidSubscriptionId(); - void TestReadChunkingInvalidSubscriptionId(); - void TestReadHandlerMalformedSubscribeRequest(); - void TestReadHandlerMalformedReadRequest1(); - void TestReadHandlerMalformedReadRequest2(); - void TestSubscribeSendUnknownMessage(); + void TestSubscribeClientReceiveWellFormedStatusResponse(); + void TestSubscribeEarlyReport(); + void TestSubscribeEarlyShutdown(); + void TestSubscribeInvalidateFabric(); + void TestSubscribeInvalidAttributePathRoundtrip(); + void TestSubscribeInvalidInterval(); + void TestSubscribePartialOverlap(); + void TestSubscribeRoundtrip(); + void TestSubscribeRoundtripChunkStatusReportTimeout(); + void TestSubscribeRoundtripStatusReportTimeout(); void TestSubscribeSendInvalidStatusReport(); - void TestReadHandlerInvalidSubscribeRequest(); - void TestShutdownSubscription(); + void TestSubscribeSendUnknownMessage(); + void TestSubscribeSetDirtyFullyOverlap(); + void TestSubscribeUrgentWildcardEvent(); + void TestSubscribeWildcard(); void TestSubscriptionReportWithDefunctSession(); enum class ReportType : uint8_t @@ -385,16 +404,23 @@ class TestReadInteraction : public chip::Test::AppContext kInvalidNoAttributeId, kInvalidOutOfRangeAttributeId, }; + static void GenerateReportData(System::PacketBufferHandle & aPayload, ReportType aReportType, bool aSuppressResponse, bool aHasSubscriptionId); protected: chip::MonotonicallyIncreasingCounter mEventCounter; - static bool sSyncScheduler; chip::app::DataModel::Provider * mOldProvider = nullptr; }; -bool TestReadInteraction::sSyncScheduler = false; +class TestReadInteractionSync : public TestReadInteraction +{ +public: + static void SetUpTestSuite() { TestReadInteraction::SetUpTestSuiteCommon(true); } + static void TearDownTestSuite() { TestReadInteraction::TearDownTestSuite(); } + void SetUp() { TestReadInteraction::SetUp(); } + void TearDown() { TestReadInteraction::TearDown(); } +}; void TestReadInteraction::GenerateReportData(System::PacketBufferHandle & aPayload, ReportType aReportType, bool aSuppressResponse, bool aHasSubscriptionId = false) @@ -476,7 +502,9 @@ void TestReadInteraction::GenerateReportData(System::PacketBufferHandle & aPaylo EXPECT_EQ(writer.Finalize(&aPayload), CHIP_NO_ERROR); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClient) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadClient) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadClient) +void TestReadInteraction::TestReadClient() { MockInteractionModelApp delegate; app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, @@ -497,7 +525,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClient) EXPECT_EQ(readClient.ProcessReportData(std::move(buf), ReadClient::ReportType::kContinuingTransaction), CHIP_NO_ERROR); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadUnexpectedSubscriptionId) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadUnexpectedSubscriptionId) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadUnexpectedSubscriptionId) +void TestReadInteraction::TestReadUnexpectedSubscriptionId() { MockInteractionModelApp delegate; app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &GetExchangeManager(), delegate, @@ -520,7 +550,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadUnexpectedSubscriptionId) CHIP_ERROR_INVALID_ARGUMENT); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandler) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadHandler) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadHandler) +void TestReadInteraction::TestReadHandler() { System::PacketBufferTLVWriter writer; System::PacketBufferHandle reportDatabuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); @@ -569,7 +601,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandler) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerSetMaxReportingInterval) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadHandlerSetMaxReportingInterval) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadHandlerSetMaxReportingInterval) +void TestReadInteraction::TestReadHandlerSetMaxReportingInterval() { System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); @@ -678,7 +712,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerSetMaxReportingInterval) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateAttributePathList) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadClientGenerateAttributePathList) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadClientGenerateAttributePathList) +void TestReadInteraction::TestReadClientGenerateAttributePathList() { MockInteractionModelApp delegate; System::PacketBufferHandle msgBuf; @@ -703,7 +739,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateAttributePathList EXPECT_EQ(readClient.GenerateAttributePaths(attributePathListBuilder, attributePaths), CHIP_NO_ERROR); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateInvalidAttributePathList) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadClientGenerateInvalidAttributePathList) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadClientGenerateInvalidAttributePathList) +void TestReadInteraction::TestReadClientGenerateInvalidAttributePathList() { MockInteractionModelApp delegate; System::PacketBufferHandle msgBuf; @@ -729,7 +767,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateInvalidAttributeP CHIP_ERROR_IM_MALFORMED_ATTRIBUTE_PATH_IB); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientInvalidReport) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadClientInvalidReport) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadClientInvalidReport) +void TestReadInteraction::TestReadClientInvalidReport() { MockInteractionModelApp delegate; @@ -753,7 +793,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientInvalidReport) CHIP_ERROR_IM_MALFORMED_ATTRIBUTE_PATH_IB); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientInvalidAttributeId) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadClientInvalidAttributeId) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadClientInvalidAttributeId) +void TestReadInteraction::TestReadClientInvalidAttributeId() { MockInteractionModelApp delegate; @@ -783,7 +825,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientInvalidAttributeId) EXPECT_FALSE(delegate.mReadError); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerInvalidAttributePath) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadHandlerInvalidAttributePath) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadHandlerInvalidAttributePath) +void TestReadInteraction::TestReadHandlerInvalidAttributePath() { CHIP_ERROR err = CHIP_NO_ERROR; @@ -840,7 +884,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerInvalidAttributePath) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateOneEventPaths) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadClientGenerateOneEventPaths) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadClientGenerateOneEventPaths) +void TestReadInteraction::TestReadClientGenerateOneEventPaths() { MockInteractionModelApp delegate; System::PacketBufferHandle msgBuf; @@ -881,7 +927,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateOneEventPaths) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateTwoEventPaths) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadClientGenerateTwoEventPaths) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadClientGenerateTwoEventPaths) +void TestReadInteraction::TestReadClientGenerateTwoEventPaths() { MockInteractionModelApp delegate; System::PacketBufferHandle msgBuf; @@ -926,7 +974,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientGenerateTwoEventPaths) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F(TestReadInteraction, TestReadRoundtrip) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadRoundtrip) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadRoundtrip) +void TestReadInteraction::TestReadRoundtrip() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -1003,7 +1053,9 @@ TEST_F(TestReadInteraction, TestReadRoundtrip) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F(TestReadInteraction, TestReadRoundtripWithDataVersionFilter) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadRoundtripWithDataVersionFilter) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadRoundtripWithDataVersionFilter) +void TestReadInteraction::TestReadRoundtripWithDataVersionFilter() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -1055,7 +1107,9 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithDataVersionFilter) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F(TestReadInteraction, TestReadRoundtripWithNoMatchPathDataVersionFilter) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadRoundtripWithNoMatchPathDataVersionFilter) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadRoundtripWithNoMatchPathDataVersionFilter) +void TestReadInteraction::TestReadRoundtripWithNoMatchPathDataVersionFilter() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -1111,7 +1165,9 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithNoMatchPathDataVersionFilter) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F(TestReadInteraction, TestReadRoundtripWithMultiSamePathDifferentDataVersionFilter) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadRoundtripWithMultiSamePathDifferentDataVersionFilter) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadRoundtripWithMultiSamePathDifferentDataVersionFilter) +void TestReadInteraction::TestReadRoundtripWithMultiSamePathDifferentDataVersionFilter() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -1168,7 +1224,9 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithMultiSamePathDifferentDataVersi EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F(TestReadInteraction, TestReadRoundtripWithSameDifferentPathsDataVersionFilter) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadRoundtripWithSameDifferentPathsDataVersionFilter) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadRoundtripWithSameDifferentPathsDataVersionFilter) +void TestReadInteraction::TestReadRoundtripWithSameDifferentPathsDataVersionFilter() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -1225,7 +1283,9 @@ TEST_F(TestReadInteraction, TestReadRoundtripWithSameDifferentPathsDataVersionFi EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F(TestReadInteraction, TestReadWildcard) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadWildcard) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadWildcard) +void TestReadInteraction::TestReadWildcard() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -1271,7 +1331,9 @@ TEST_F(TestReadInteraction, TestReadWildcard) } // TestReadChunking will try to read a few large attributes, the report won't fit into the MTU and result in chunking. -TEST_F(TestReadInteraction, TestReadChunking) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadChunking) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadChunking) +void TestReadInteraction::TestReadChunking() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -1323,7 +1385,9 @@ TEST_F(TestReadInteraction, TestReadChunking) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F(TestReadInteraction, TestSetDirtyBetweenChunks) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSetDirtyBetweenChunks) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSetDirtyBetweenChunks) +void TestReadInteraction::TestSetDirtyBetweenChunks() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -1472,7 +1536,9 @@ TEST_F(TestReadInteraction, TestSetDirtyBetweenChunks) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F(TestReadInteraction, TestReadInvalidAttributePathRoundtrip) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadInvalidAttributePathRoundtrip) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadInvalidAttributePathRoundtrip) +void TestReadInteraction::TestReadInvalidAttributePathRoundtrip() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -1513,7 +1579,9 @@ TEST_F(TestReadInteraction, TestReadInvalidAttributePathRoundtrip) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestProcessSubscribeRequest) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestProcessSubscribeRequest) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestProcessSubscribeRequest) +void TestReadInteraction::TestProcessSubscribeRequest() { System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); @@ -1570,7 +1638,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestProcessSubscribeRequest) * @brief Test validates that an ICD will choose its IdleModeDuration (GetPublisherSelectedIntervalLimit) * as MaxInterval when the MaxIntervalCeiling is superior. */ -TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestSupMaxIntervalCeiling) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestICDProcessSubscribeRequestSupMaxIntervalCeiling) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestICDProcessSubscribeRequestSupMaxIntervalCeiling) +void TestReadInteraction::TestICDProcessSubscribeRequestSupMaxIntervalCeiling() { System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); @@ -1638,7 +1708,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestSupMaxInt * @brief Test validates that an ICD will choose its IdleModeDuration (GetPublisherSelectedIntervalLimit) * as MaxInterval when the MaxIntervalCeiling is inferior. */ -TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestInfMaxIntervalCeiling) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestICDProcessSubscribeRequestInfMaxIntervalCeiling) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestICDProcessSubscribeRequestInfMaxIntervalCeiling) +void TestReadInteraction::TestICDProcessSubscribeRequestInfMaxIntervalCeiling() { System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); @@ -1706,7 +1778,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestInfMaxInt * @brief Test validates that an ICD will choose a multiple of its IdleModeDuration (GetPublisherSelectedIntervalLimit) * as MaxInterval when the MinInterval > IdleModeDuration. */ -TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestSupMinInterval) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestICDProcessSubscribeRequestSupMinInterval) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestICDProcessSubscribeRequestSupMinInterval) +void TestReadInteraction::TestICDProcessSubscribeRequestSupMinInterval() { System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); @@ -1774,7 +1848,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestSupMinInt * @brief Test validates that an ICD will choose a maximal value for an uint16 if the multiple of the IdleModeDuration * is greater than variable size. */ -TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestMaxMinInterval) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestICDProcessSubscribeRequestMaxMinInterval) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestICDProcessSubscribeRequestMaxMinInterval) +void TestReadInteraction::TestICDProcessSubscribeRequestMaxMinInterval() { System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); @@ -1840,7 +1916,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestMaxMinInt * @brief Test validates that an ICD will choose the MaxIntervalCeiling as MaxInterval if the next multiple after the MinInterval * is greater than the IdleModeDuration and MaxIntervalCeiling */ -TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestInvalidIdleModeDuration) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestICDProcessSubscribeRequestInvalidIdleModeDuration) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestICDProcessSubscribeRequestInvalidIdleModeDuration) +void TestReadInteraction::TestICDProcessSubscribeRequestInvalidIdleModeDuration() { System::PacketBufferTLVWriter writer; System::PacketBufferHandle subscribeRequestbuf = System::PacketBufferHandle::New(System::PacketBuffer::kMaxSize); @@ -1904,7 +1982,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestICDProcessSubscribeRequestInvalidId #endif // CHIP_CONFIG_ENABLE_ICD_SERVER -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeRoundtrip) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeRoundtrip) +void TestReadInteraction::TestSubscribeRoundtrip() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -2099,7 +2179,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeRoundtrip) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeEarlyReport) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeEarlyReport) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeEarlyReport) +void TestReadInteraction::TestSubscribeEarlyReport() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -2260,7 +2342,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeEarlyReport) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeUrgentWildcardEvent) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeUrgentWildcardEvent) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeUrgentWildcardEvent) +void TestReadInteraction::TestSubscribeUrgentWildcardEvent() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -2504,7 +2588,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeUrgentWildcardEvent) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F(TestReadInteraction, TestSubscribeWildcard) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeWildcard) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeWildcard) +void TestReadInteraction::TestSubscribeWildcard() { // This test in particular is completely tied to the DefaultMockConfig in the mock // attribute storage, so reset to that (figuring out chunking location is extra hard to @@ -2525,10 +2611,10 @@ TEST_F(TestReadInteraction, TestSubscribeWildcard) ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mEventPathParamsListSize = 0; - std::unique_ptr attributePathParams(new chip::app::AttributePathParams[2]); - // Subscribe to full wildcard paths, repeat twice to ensure chunking. - readPrepareParams.mpAttributePathParamsList = attributePathParams.get(); readPrepareParams.mAttributePathParamsListSize = 2; + auto attributePathParams = std::make_unique(readPrepareParams.mAttributePathParamsListSize); + // Subscribe to full wildcard paths, repeat twice to ensure chunking. + readPrepareParams.mpAttributePathParamsList = attributePathParams.get(); readPrepareParams.mMinIntervalFloorSeconds = 0; readPrepareParams.mMaxIntervalCeilingSeconds = 1; @@ -2642,7 +2728,9 @@ TEST_F(TestReadInteraction, TestSubscribeWildcard) } // Subscribe (wildcard, C3, A1), then setDirty (E2, C3, wildcard), receive one attribute after setDirty -TEST_F(TestReadInteraction, TestSubscribePartialOverlap) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribePartialOverlap) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribePartialOverlap) +void TestReadInteraction::TestSubscribePartialOverlap() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -2657,11 +2745,11 @@ TEST_F(TestReadInteraction, TestSubscribePartialOverlap) ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mEventPathParamsListSize = 0; - std::unique_ptr attributePathParams(new chip::app::AttributePathParams[2]); - attributePathParams[0].mClusterId = chip::Test::MockClusterId(3); - attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(1); - readPrepareParams.mpAttributePathParamsList = attributePathParams.get(); readPrepareParams.mAttributePathParamsListSize = 1; + auto attributePathParams = std::make_unique(readPrepareParams.mAttributePathParamsListSize); + attributePathParams[0].mClusterId = chip::Test::MockClusterId(3); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(1); + readPrepareParams.mpAttributePathParamsList = attributePathParams.get(); readPrepareParams.mMinIntervalFloorSeconds = 0; readPrepareParams.mMaxIntervalCeilingSeconds = 1; @@ -2712,7 +2800,9 @@ TEST_F(TestReadInteraction, TestSubscribePartialOverlap) } // Subscribe (E2, C3, A1), then setDirty (wildcard, wildcard, wildcard), receive one attribute after setDirty -TEST_F(TestReadInteraction, TestSubscribeSetDirtyFullyOverlap) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeSetDirtyFullyOverlap) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeSetDirtyFullyOverlap) +void TestReadInteraction::TestSubscribeSetDirtyFullyOverlap() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -2727,12 +2817,12 @@ TEST_F(TestReadInteraction, TestSubscribeSetDirtyFullyOverlap) ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); readPrepareParams.mEventPathParamsListSize = 0; - std::unique_ptr attributePathParams(new chip::app::AttributePathParams[1]); - attributePathParams[0].mClusterId = chip::Test::kMockEndpoint2; - attributePathParams[0].mClusterId = chip::Test::MockClusterId(3); - attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(1); - readPrepareParams.mpAttributePathParamsList = attributePathParams.get(); readPrepareParams.mAttributePathParamsListSize = 1; + auto attributePathParams = std::make_unique(readPrepareParams.mAttributePathParamsListSize); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint2; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(3); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(1); + readPrepareParams.mpAttributePathParamsList = attributePathParams.get(); readPrepareParams.mMinIntervalFloorSeconds = 0; readPrepareParams.mMaxIntervalCeilingSeconds = 1; @@ -2781,7 +2871,9 @@ TEST_F(TestReadInteraction, TestSubscribeSetDirtyFullyOverlap) // Verify that subscription can be shut down just after receiving SUBSCRIBE RESPONSE, // before receiving any subsequent REPORT DATA. -TEST_F(TestReadInteraction, TestSubscribeEarlyShutdown) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeEarlyShutdown) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeEarlyShutdown) +void TestReadInteraction::TestSubscribeEarlyShutdown() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); InteractionModelEngine & engine = *InteractionModelEngine::GetInstance(); @@ -2830,7 +2922,9 @@ TEST_F(TestReadInteraction, TestSubscribeEarlyShutdown) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeInvalidAttributePathRoundtrip) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeInvalidAttributePathRoundtrip) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeInvalidAttributePathRoundtrip) +void TestReadInteraction::TestSubscribeInvalidAttributePathRoundtrip() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -2896,7 +2990,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeInvalidAttributePathRoundt EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F(TestReadInteraction, TestReadShutdown) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadShutdown) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadShutdown) +void TestReadInteraction::TestReadShutdown() { auto * engine = chip::app::InteractionModelEngine::GetInstance(); app::ReadClient * pClients[4]; @@ -2933,7 +3029,9 @@ TEST_F(TestReadInteraction, TestReadShutdown) Platform::Delete(pClients[2]); } -TEST_F(TestReadInteraction, TestSubscribeInvalidInterval) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeInvalidInterval) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeInvalidInterval) +void TestReadInteraction::TestSubscribeInvalidInterval() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -2977,7 +3075,9 @@ TEST_F(TestReadInteraction, TestSubscribeInvalidInterval) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestPostSubscribeRoundtripStatusReportTimeout) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestPostSubscribeRoundtripStatusReportTimeout) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestPostSubscribeRoundtripStatusReportTimeout) +void TestReadInteraction::TestPostSubscribeRoundtripStatusReportTimeout() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); // Shouldn't have anything in the retransmit table when starting the test. @@ -3094,7 +3194,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestPostSubscribeRoundtripStatusReportT CreateSessionBobToAlice(); } -TEST_F(TestReadInteraction, TestSubscribeRoundtripStatusReportTimeout) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeRoundtripStatusReportTimeout) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeRoundtripStatusReportTimeout) +void TestReadInteraction::TestSubscribeRoundtripStatusReportTimeout() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -3167,7 +3269,9 @@ TEST_F(TestReadInteraction, TestSubscribeRoundtripStatusReportTimeout) CreateSessionBobToAlice(); } -TEST_F(TestReadInteraction, TestReadChunkingStatusReportTimeout) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadChunkingStatusReportTimeout) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadChunkingStatusReportTimeout) +void TestReadInteraction::TestReadChunkingStatusReportTimeout() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -3219,7 +3323,9 @@ TEST_F(TestReadInteraction, TestReadChunkingStatusReportTimeout) // ReadClient sends the read request, but handler fails to send the one report (SendMessage returns an error). // Since this is an un-chunked read, we are not in the AwaitingReportResponse state, so the "reports in flight" // counter should not increase. -TEST_F(TestReadInteraction, TestReadReportFailure) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadReportFailure) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadReportFailure) +void TestReadInteraction::TestReadReportFailure() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -3263,7 +3369,9 @@ TEST_F(TestReadInteraction, TestReadReportFailure) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F(TestReadInteraction, TestSubscribeRoundtripChunkStatusReportTimeout) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeRoundtripChunkStatusReportTimeout) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeRoundtripChunkStatusReportTimeout) +void TestReadInteraction::TestSubscribeRoundtripChunkStatusReportTimeout() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -3331,7 +3439,9 @@ TEST_F(TestReadInteraction, TestSubscribeRoundtripChunkStatusReportTimeout) CreateSessionBobToAlice(); } -TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkStatusReportTimeout) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestPostSubscribeRoundtripChunkStatusReportTimeout) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestPostSubscribeRoundtripChunkStatusReportTimeout) +void TestReadInteraction::TestPostSubscribeRoundtripChunkStatusReportTimeout() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -3430,7 +3540,9 @@ TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkStatusReportTimeout) CreateSessionBobToAlice(); } -TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReportTimeout) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestPostSubscribeRoundtripChunkReportTimeout) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestPostSubscribeRoundtripChunkReportTimeout) +void TestReadInteraction::TestPostSubscribeRoundtripChunkReportTimeout() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -3528,7 +3640,9 @@ TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReportTimeout) CreateSessionBobToAlice(); } -TEST_F(TestReadInteraction, TestPostSubscribeRoundtripChunkReport) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestPostSubscribeRoundtripChunkReport) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestPostSubscribeRoundtripChunkReport) +void TestReadInteraction::TestPostSubscribeRoundtripChunkReport() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -3641,7 +3755,9 @@ void CheckForInvalidAction(Test::MessageCapturer & messageLog) // Read Client sends the read request, Read Handler drops the response, then test injects unknown status reponse message for // Read Client. -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientReceiveInvalidMessage) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadClientReceiveInvalidMessage) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadClientReceiveInvalidMessage) +void TestReadInteraction::TestReadClientReceiveInvalidMessage() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -3726,7 +3842,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadClientReceiveInvalidMessage) // Read Client sends the subscribe request, Read Handler drops the response, then test injects unknown status response message // for Read Client. -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidStatusResponse) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeClientReceiveInvalidStatusResponse) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeClientReceiveInvalidStatusResponse) +void TestReadInteraction::TestSubscribeClientReceiveInvalidStatusResponse() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -3817,7 +3935,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidStatus // Read Client sends the subscribe request, Read Handler drops the response, then test injects well-formed status response // message with Success for Read Client, we expect the error with CHIP_ERROR_INVALID_MESSAGE_TYPE -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveWellFormedStatusResponse) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeClientReceiveWellFormedStatusResponse) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeClientReceiveWellFormedStatusResponse) +void TestReadInteraction::TestSubscribeClientReceiveWellFormedStatusResponse() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -3907,7 +4027,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveWellFormedSta // Read Client sends the subscribe request, Read Handler drops the response, then test injects invalid report message for Read // Client. -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidReportMessage) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeClientReceiveInvalidReportMessage) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeClientReceiveInvalidReportMessage) +void TestReadInteraction::TestSubscribeClientReceiveInvalidReportMessage() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -3997,7 +4119,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidReport // Read Client create the subscription, handler sends unsolicited malformed report to client, // InteractionModelEngine::OnUnsolicitedReportData would process this malformed report and sends out status report -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedInvalidReportMessage) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedInvalidReportMessage) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeClientReceiveUnsolicitedInvalidReportMessage) +void TestReadInteraction::TestSubscribeClientReceiveUnsolicitedInvalidReportMessage() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -4068,7 +4192,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedIn // Read Client sends the subscribe request, Read Handler drops the subscribe response, then test injects invalid subscribe // response message -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidSubscribeResponseMessage) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeClientReceiveInvalidSubscribeResponseMessage) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeClientReceiveInvalidSubscribeResponseMessage) +void TestReadInteraction::TestSubscribeClientReceiveInvalidSubscribeResponseMessage() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -4159,7 +4285,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveInvalidSubscr // Read Client create the subscription, handler sends unsolicited malformed report with invalid subscription id to client, // InteractionModelEngine::OnUnsolicitedReportData would process this malformed report and sends out status report -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedReportMessageWithInvalidSubscriptionId) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedReportMessageWithInvalidSubscriptionId) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeClientReceiveUnsolicitedReportMessageWithInvalidSubscriptionId) +void TestReadInteraction::TestSubscribeClientReceiveUnsolicitedReportMessageWithInvalidSubscriptionId() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -4235,7 +4363,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeClientReceiveUnsolicitedRe // TestReadChunkingInvalidSubscriptionId will try to read a few large attributes, the report won't fit into the MTU and result // in chunking, second report has different subscription id from the first one, read client sends out the status report with // invalid subscription -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadChunkingInvalidSubscriptionId) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadChunkingInvalidSubscriptionId) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadChunkingInvalidSubscriptionId) +void TestReadInteraction::TestReadChunkingInvalidSubscriptionId() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -4325,7 +4455,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadChunkingInvalidSubscriptionId) // Read Client sends a malformed subscribe request, interaction model engine fails to parse the request and generates a status // report to client, and client is closed. -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedSubscribeRequest) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadHandlerMalformedSubscribeRequest) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadHandlerMalformedSubscribeRequest) +void TestReadInteraction::TestReadHandlerMalformedSubscribeRequest() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -4369,7 +4501,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedSubscribeReques // Read Client sends a malformed read request, interaction model engine fails to parse the request and generates a status report // to client, and client is closed. -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedReadRequest1) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadHandlerMalformedReadRequest1) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadHandlerMalformedReadRequest1) +void TestReadInteraction::TestReadHandlerMalformedReadRequest1() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -4411,7 +4545,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedReadRequest1) // Read Client sends a malformed read request, read handler fails to parse the request and generates a status report to client, // and client is closed. -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedReadRequest2) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadHandlerMalformedReadRequest2) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadHandlerMalformedReadRequest2) +void TestReadInteraction::TestReadHandlerMalformedReadRequest2() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -4454,7 +4590,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerMalformedReadRequest2) // Read Client creates a subscription with the server, server sends chunked reports, after the handler sends out the first // chunked report, client sends out invalid write request message, handler sends status report with invalid action and closes -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendUnknownMessage) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeSendUnknownMessage) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeSendUnknownMessage) +void TestReadInteraction::TestSubscribeSendUnknownMessage() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -4528,7 +4666,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendUnknownMessage) // Read Client creates a subscription with the server, server sends chunked reports, after the handler sends out invalid status // report, client sends out invalid status report message, handler sends status report with invalid action and close -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendInvalidStatusReport) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeSendInvalidStatusReport) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeSendInvalidStatusReport) +void TestReadInteraction::TestSubscribeSendInvalidStatusReport() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -4599,7 +4739,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscribeSendInvalidStatusReport) // Read Client sends a malformed subscribe request, the server fails to parse the request and generates a status report to the // client, and client closes itself. -TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerInvalidSubscribeRequest) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestReadHandlerInvalidSubscribeRequest) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestReadHandlerInvalidSubscribeRequest) +void TestReadInteraction::TestReadHandlerInvalidSubscribeRequest() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -4641,7 +4783,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestReadHandlerInvalidSubscribeRequest) // Create the subscription, then remove the corresponding fabric in client and handler, the corresponding // client and handler would be released as well. -TEST_F(TestReadInteraction, TestSubscribeInvalidateFabric) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscribeInvalidateFabric) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscribeInvalidateFabric) +void TestReadInteraction::TestSubscribeInvalidateFabric() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -4655,12 +4799,13 @@ TEST_F(TestReadInteraction, TestSubscribeInvalidateFabric) EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); - readPrepareParams.mpAttributePathParamsList = new chip::app::AttributePathParams[1]; - readPrepareParams.mAttributePathParamsListSize = 1; - readPrepareParams.mpAttributePathParamsList[0].mEndpointId = chip::Test::kMockEndpoint3; - readPrepareParams.mpAttributePathParamsList[0].mClusterId = chip::Test::MockClusterId(2); - readPrepareParams.mpAttributePathParamsList[0].mAttributeId = chip::Test::MockAttributeId(1); + readPrepareParams.mAttributePathParamsListSize = 1; + auto attributePathParams = std::make_unique(readPrepareParams.mAttributePathParamsListSize); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(1); + readPrepareParams.mpAttributePathParamsList = attributePathParams.get(); readPrepareParams.mMinIntervalFloorSeconds = 0; readPrepareParams.mMaxIntervalCeilingSeconds = 0; @@ -4671,6 +4816,7 @@ TEST_F(TestReadInteraction, TestSubscribeInvalidateFabric) delegate.mGotReport = false; + attributePathParams.release(); EXPECT_EQ(readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); DrainAndServiceIO(); @@ -4696,7 +4842,9 @@ TEST_F(TestReadInteraction, TestSubscribeInvalidateFabric) EXPECT_EQ(GetExchangeManager().GetNumActiveExchanges(), 0u); } -TEST_F_FROM_FIXTURE(TestReadInteraction, TestShutdownSubscription) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestShutdownSubscription) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestShutdownSubscription) +void TestReadInteraction::TestShutdownSubscription() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); @@ -4710,12 +4858,13 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestShutdownSubscription) EXPECT_EQ(engine->Init(&GetExchangeManager(), &GetFabricTable(), gReportScheduler), CHIP_NO_ERROR); ReadPrepareParams readPrepareParams(GetSessionBobToAlice()); - readPrepareParams.mpAttributePathParamsList = new chip::app::AttributePathParams[1]; - readPrepareParams.mAttributePathParamsListSize = 1; - readPrepareParams.mpAttributePathParamsList[0].mEndpointId = chip::Test::kMockEndpoint3; - readPrepareParams.mpAttributePathParamsList[0].mClusterId = chip::Test::MockClusterId(2); - readPrepareParams.mpAttributePathParamsList[0].mAttributeId = chip::Test::MockAttributeId(1); + readPrepareParams.mAttributePathParamsListSize = 1; + auto attributePathParams = std::make_unique(readPrepareParams.mAttributePathParamsListSize); + attributePathParams[0].mEndpointId = chip::Test::kMockEndpoint3; + attributePathParams[0].mClusterId = chip::Test::MockClusterId(2); + attributePathParams[0].mAttributeId = chip::Test::MockAttributeId(1); + readPrepareParams.mpAttributePathParamsList = attributePathParams.get(); readPrepareParams.mMinIntervalFloorSeconds = 0; readPrepareParams.mMaxIntervalCeilingSeconds = 0; @@ -4726,6 +4875,7 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestShutdownSubscription) delegate.mGotReport = false; + attributePathParams.release(); EXPECT_EQ(readClient.SendAutoResubscribeRequest(std::move(readPrepareParams)), CHIP_NO_ERROR); DrainAndServiceIO(); @@ -4747,7 +4897,9 @@ TEST_F_FROM_FIXTURE(TestReadInteraction, TestShutdownSubscription) * session it has is defunct. Makes sure we correctly tear down the ReadHandler * and don't increment the "reports in flight" count. */ -TEST_F_FROM_FIXTURE(TestReadInteraction, TestSubscriptionReportWithDefunctSession) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteraction, TestSubscriptionReportWithDefunctSession) +TEST_F_FROM_FIXTURE_NO_BODY(TestReadInteractionSync, TestSubscriptionReportWithDefunctSession) +void TestReadInteraction::TestSubscriptionReportWithDefunctSession() { Messaging::ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); diff --git a/src/lib/support/tests/ExtraPwTestMacros.h b/src/lib/support/tests/ExtraPwTestMacros.h index ab592800716592..6eda462f803db5 100644 --- a/src/lib/support/tests/ExtraPwTestMacros.h +++ b/src/lib/support/tests/ExtraPwTestMacros.h @@ -17,8 +17,9 @@ */ #pragma once -/* +/** * Run Fixture's class function as a test. + * * It is used to execute test cases that need to use private members of a particular class. * Unlike the pigweed macro `FRIEND_TEST`, this approach allows you to define the entire * test_fixture class as a friend, rather than having to define each testcase as a friend. @@ -54,3 +55,16 @@ test_name(); \ } \ void test_fixture::test_name() + +/** + * Run Fixture's class function as a test. + * + * This macro does not define the body of the test function. It can be used to + * run a single test case which needs to be run against different fixtures. + * + */ +#define TEST_F_FROM_FIXTURE_NO_BODY(test_fixture, test_name) \ + TEST_F(test_fixture, test_name) \ + { \ + test_name(); \ + } From 6c9a9e024e8203584c45908b2630e97d6526da99 Mon Sep 17 00:00:00 2001 From: Alex Tsitsiura Date: Mon, 4 Nov 2024 16:48:39 +0200 Subject: [PATCH 053/121] [Telink] Update Docker image (Zephyr update) (#36355) --- integrations/docker/images/base/chip-build/version | 2 +- integrations/docker/images/stage-2/chip-build-telink/Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/integrations/docker/images/base/chip-build/version b/integrations/docker/images/base/chip-build/version index 299a0b9cae5531..3c23aaad931620 100644 --- a/integrations/docker/images/base/chip-build/version +++ b/integrations/docker/images/base/chip-build/version @@ -1 +1 @@ -89 : [Silabs] Leave Simplicity SDK components for SLC generation CI +90 : [Telink] Update Docker image (Zephyr update) diff --git a/integrations/docker/images/stage-2/chip-build-telink/Dockerfile b/integrations/docker/images/stage-2/chip-build-telink/Dockerfile index 4311be77edddc4..2b84323d445955 100644 --- a/integrations/docker/images/stage-2/chip-build-telink/Dockerfile +++ b/integrations/docker/images/stage-2/chip-build-telink/Dockerfile @@ -18,7 +18,7 @@ RUN set -x \ && : # last line # Setup Zephyr -ARG ZEPHYR_REVISION=3ed7686a9378de6be1368c912f9a42f998bbfb18 +ARG ZEPHYR_REVISION=f762f1a1027284e63e338e6d83deeade62f355b0 WORKDIR /opt/telink/zephyrproject RUN set -x \ && python3 -m pip install --break-system-packages -U --no-cache-dir west \ From 50ad31c24ffd2723afd12fe9403bd70487744aa5 Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Mon, 4 Nov 2024 10:48:12 -0500 Subject: [PATCH 054/121] Add missing default arg for 917 dishwasher gn build (#36354) --- examples/dishwasher-app/silabs/build_for_wifi_gnfile.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/dishwasher-app/silabs/build_for_wifi_gnfile.gn b/examples/dishwasher-app/silabs/build_for_wifi_gnfile.gn index d391814190d09f..1d6a71e88dd16f 100644 --- a/examples/dishwasher-app/silabs/build_for_wifi_gnfile.gn +++ b/examples/dishwasher-app/silabs/build_for_wifi_gnfile.gn @@ -24,5 +24,6 @@ default_args = { target_cpu = "arm" target_os = "freertos" chip_enable_wifi = true + chip_device_platform = "SiWx917" import("//build_for_wifi_args.gni") } From 1752853176408607d075b80071d690534b036fc7 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Mon, 4 Nov 2024 16:08:03 -0500 Subject: [PATCH 055/121] Use DynamicString for dynamic strings in perfetto (#36360) --- src/tracing/perfetto/perfetto_tracing.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/tracing/perfetto/perfetto_tracing.cpp b/src/tracing/perfetto/perfetto_tracing.cpp index f9b00cc7ad96d3..d83007826f6e39 100644 --- a/src/tracing/perfetto/perfetto_tracing.cpp +++ b/src/tracing/perfetto/perfetto_tracing.cpp @@ -133,19 +133,19 @@ void PerfettoBackend::LogMetricEvent(const MetricEvent & event) switch (event.ValueType()) { case ValueType::kInt32: - TRACE_EVENT_INSTANT("Matter", event.key(), "value", event.ValueInt32()); + TRACE_EVENT_INSTANT("Matter", perfetto::DynamicString(event.key()), "value", event.ValueInt32()); break; case ValueType::kUInt32: - TRACE_EVENT_INSTANT("Matter", event.key(), "value", event.ValueUInt32()); + TRACE_EVENT_INSTANT("Matter", perfetto::DynamicString(event.key()), "value", event.ValueUInt32()); break; case ValueType::kChipErrorCode: - TRACE_EVENT_INSTANT("Matter", event.key(), "error", event.ValueErrorCode()); + TRACE_EVENT_INSTANT("Matter", perfetto::DynamicString(event.key()), "error", event.ValueErrorCode()); break; case ValueType::kUndefined: - TRACE_EVENT_INSTANT("Matter", event.key()); + TRACE_EVENT_INSTANT("Matter", perfetto::DynamicString(event.key())); break; default: - TRACE_EVENT_INSTANT("Matter", event.key(), "type", "UNKNOWN"); + TRACE_EVENT_INSTANT("Matter", perfetto::DynamicString(event.key()), "type", "UNKNOWN"); break; } } From 1efa8aeb519a47b1eed4956eb13fc33993f4e84a Mon Sep 17 00:00:00 2001 From: Kenneth Fu <80622799+fuxiaoming-lumi@users.noreply.github.com> Date: Tue, 5 Nov 2024 06:37:17 +0800 Subject: [PATCH 056/121] [Silabs] Drop BLE connection on endpoint close (#36336) --- src/platform/silabs/efr32/BLEManagerImpl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/platform/silabs/efr32/BLEManagerImpl.cpp b/src/platform/silabs/efr32/BLEManagerImpl.cpp index 1f8704896f71cb..44956572a68f91 100644 --- a/src/platform/silabs/efr32/BLEManagerImpl.cpp +++ b/src/platform/silabs/efr32/BLEManagerImpl.cpp @@ -343,7 +343,7 @@ CHIP_ERROR BLEManagerImpl::SendWriteRequest(BLE_CONNECTION_OBJECT conId, const C void BLEManagerImpl::NotifyChipConnectionClosed(BLE_CONNECTION_OBJECT conId) { - // Nothing to do + CloseConnection(conId); } CHIP_ERROR BLEManagerImpl::MapBLEError(int bleErr) From 62a4a9758ec9ce668fcc2e9617ea3e449511c097 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Mon, 4 Nov 2024 18:02:29 -0500 Subject: [PATCH 057/121] Update python tests to maintain the `test metadata` as a local file (#36359) * Add metadata that is shared for python tests * More updates * Fix typo * More metadata updates --- scripts/tests/local.py | 110 ++++-------------- src/python_testing/execute_python_tests.py | 43 +------ .../chip/testing/tasks.py | 2 +- src/python_testing/test_metadata.yaml | 102 ++++++++++++++++ 4 files changed, 134 insertions(+), 123 deletions(-) create mode 100644 src/python_testing/test_metadata.yaml diff --git a/scripts/tests/local.py b/scripts/tests/local.py index aaa4d88133a6dc..97a2d1daf83c28 100755 --- a/scripts/tests/local.py +++ b/scripts/tests/local.py @@ -33,6 +33,7 @@ import click import coloredlogs import tabulate +import yaml # We compile for the local architecture. Figure out what platform we need @@ -43,12 +44,12 @@ def _get_native_machine_target(): """ current_system_info = platform.uname() arch = current_system_info.machine - if arch == 'x86_64': - arch = 'x64' - elif arch == 'i386' or arch == 'i686': - arch = 'x86' - elif arch in ('aarch64', 'aarch64_be', 'armv8b', 'armv8l'): - arch = 'arm64' + if arch == "x86_64": + arch = "x64" + elif arch == "i386" or arch == "i686": + arch = "x86" + elif arch in ("aarch64", "aarch64_be", "armv8b", "armv8l"): + arch = "arm64" return f"{current_system_info.system.lower()}-{arch}" @@ -165,14 +166,17 @@ def _do_build_apps(): f"{target_prefix}-all-clusters-no-ble-clang-boringssl", f"{target_prefix}-bridge-no-ble-clang-boringssl", f"{target_prefix}-energy-management-no-ble-clang-boringssl", + f"{target_prefix}-fabric-admin-rpc-ipv6only-clang-boringssl", + f"{target_prefix}-fabric-bridge-rpc-ipv6only-clang-boringssl", + f"{target_prefix}-light-data-model-no-unique-id-ipv6only-no-ble-no-wifi-clang", f"{target_prefix}-lit-icd-no-ble-clang-boringssl", f"{target_prefix}-lock-no-ble-clang-boringssl", f"{target_prefix}-microwave-oven-no-ble-clang-boringssl", + f"{target_prefix}-network-manager-ipv6only-no-ble-clang-boringssl", f"{target_prefix}-ota-provider-no-ble-clang-boringssl", f"{target_prefix}-ota-requestor-no-ble-clang-boringssl", f"{target_prefix}-rvc-no-ble-clang-boringssl", f"{target_prefix}-tv-app-no-ble-clang-boringssl", - f"{target_prefix}-network-manager-ipv6only-no-ble-clang-boringssl", ] cmd = ["./scripts/build/build_examples.py"] @@ -354,6 +358,11 @@ def as_runner(path): CHIP_RVC_APP: {as_runner(f'out/{target_prefix}-rvc-no-ble-clang-boringssl/chip-rvc-app')} NETWORK_MANAGEMENT_APP: { as_runner(f'out/{target_prefix}-network-manager-ipv6only-no-ble-clang-boringssl/matter-network-manager-app')} + FABRIC_ADMIN_APP: { + as_runner(f'out/{target_prefix}-fabric-admin-rpc-ipv6only-clang-boringssl/fabric-admin')} + FABRIC_BRIDGE_APP: { + as_runner(f'out/{target_prefix}-fabric-bridge-rpc-ipv6only-clang-boringssl/fabric-bridge-app')} + LIGHTING_APP_NO_UNIQUE_ID: {as_runner(f'out/{target_prefix}-light-data-model-no-unique-id-ipv6only-no-ble-no-wifi-clang/chip-lighting-app')} TRACE_APP: out/trace_data/app-{{SCRIPT_BASE_NAME}} TRACE_TEST_JSON: out/trace_data/test-{{SCRIPT_BASE_NAME}} TRACE_TEST_PERFETTO: out/trace_data/test-{{SCRIPT_BASE_NAME}} @@ -382,58 +391,11 @@ def as_runner(path): if not os.path.exists("out/trace_data"): os.mkdir("out/trace_data") - # IGNORES are taken out of `src/python_testing/execute_python_tests.py` in the SDK - excluded_patterns = { - "MinimalRepresentation.py", - "TC_CNET_4_4.py", - "TC_CCTRL_2_1.py", - "TC_CCTRL_2_2.py", - "TC_CCTRL_2_3.py", - "TC_DGGEN_3_2.py", - "TC_EEVSE_Utils.py", - "TC_ECOINFO_2_1.py", - "TC_ECOINFO_2_2.py", - "TC_EWATERHTRBase.py", - "TC_EWATERHTR_2_1.py", - "TC_EWATERHTR_2_2.py", - "TC_EWATERHTR_2_3.py", - "TC_EnergyReporting_Utils.py", - "TC_OpstateCommon.py", - "TC_pics_checker.py", - "TC_TMP_2_1.py", - "TC_MCORE_FS_1_1.py", - "TC_MCORE_FS_1_2.py", - "TC_MCORE_FS_1_3.py", - "TC_MCORE_FS_1_4.py", - "TC_MCORE_FS_1_5.py", - "TC_OCC_3_1.py", - "TC_OCC_3_2.py", - "TC_BRBINFO_4_1.py", - "TestCommissioningTimeSync.py", - "TestConformanceSupport.py", - "TestChoiceConformanceSupport.py", - "TC_DEMTestBase.py", - "choice_conformance_support.py", - "TestConformanceTest.py", # Unit test of the conformance test (TC_DeviceConformance) - does not run against an app. - "TestIdChecks.py", - "TestSpecParsingDeviceType.py", - "TestMatterTestingSupport.py", - "TestSpecParsingSupport.py", - "TestTimeSyncTrustedTimeSource.py", - "basic_composition_support.py", - "conformance_support.py", - "drlk_2_x_common.py", - "execute_python_tests.py", - "global_attribute_ids.py", - "hello_external_runner.py", - "hello_test.py", - "matter_testing_support.py", - "pics_support.py", - "spec_parsing_support.py", - "taglist_and_topology_test_support.py", - "test_plan_support.py", - "test_plan_table_generator.py", - } + metadata = yaml.full_load(open("src/python_testing/test_metadata.yaml")) + excluded_patterns = set([item["name"] for item in metadata["not_automated"]]) + + # NOTE: for slow tests. we add logs to not get impatient + slow_test_duration = dict([(item["name"], item["duration"]) for item in metadata["slow_tests"]]) if not os.path.isdir("src/python_testing"): raise Exception( @@ -448,31 +410,6 @@ def as_runner(path): test_scripts.append("src/controller/python/test/test_scripts/mobile-device-test.py") test_scripts.sort() # order consistent - # NOTE: VERY slow tests. we add logs to not get impatient - slow_test_duration = { - "mobile-device-test.py": "3 minutes", - "TC_AccessChecker.py": "1.5 minutes", - "TC_CADMIN_1_9.py": "40 seconds", - "TC_CC_2_2.py": "1.5 minutes", - "TC_DEM_2_10.py": "40 seconds", - "TC_DeviceBasicComposition.py": "25 seconds", - "TC_DRLK_2_12.py": "30 seconds", - "TC_DRLK_2_3.py": "30 seconds", - "TC_EEVSE_2_6.py": "30 seconds", - "TC_FAN_3_1.py": "15 seconds", - "TC_OPSTATE_2_5.py": "1.25 minutes", - "TC_OPSTATE_2_6.py": "35 seconds", - "TC_PS_2_3.py": "30 seconds", - "TC_RR_1_1.py": "25 seconds", - "TC_SWTCH.py": "1 minute", - "TC_TIMESYNC_2_10.py": "20 seconds", - "TC_TIMESYNC_2_11.py": "30 seconds", - "TC_TIMESYNC_2_12.py": "20 seconds", - "TC_TIMESYNC_2_7.py": "20 seconds", - "TC_TIMESYNC_2_8.py": "1.5 minutes", - "TC_ICDM_5_1.py": "TODO", - } - execution_times = [] try: to_run = [] @@ -698,7 +635,10 @@ def chip_tool_tests(target, target_glob, include_tags, expected_failures, runner target_prefix = _get_native_machine_target() cmd.extend( - ["--chip-tool", f"./out/{target_prefix}-chip-tool-no-ble-clang-boringssl/chip-tool"] + [ + "--chip-tool", + f"./out/{target_prefix}-chip-tool-no-ble-clang-boringssl/chip-tool", + ] ) if target is not None: diff --git a/src/python_testing/execute_python_tests.py b/src/python_testing/execute_python_tests.py index 34a391873b3101..c85a02bc40952e 100644 --- a/src/python_testing/execute_python_tests.py +++ b/src/python_testing/execute_python_tests.py @@ -20,6 +20,8 @@ import os import subprocess +import yaml + # Function to load --app argument environment variables from a file @@ -36,11 +38,8 @@ def load_env_from_yaml(file_path): Args: file_path (str): The path to the YAML file containing the environment variables. """ - with open(file_path, 'r') as file: - for line in file: - if line.strip(): # Skip empty lines - key, value = line.strip().split(': ', 1) - os.environ[key] = value + for key, value in yaml.full_load(open(file_path, 'r')).items(): + os.environ[key] = value def main(search_directory, env_file): @@ -53,38 +52,8 @@ def main(search_directory, env_file): # Define the base command to run tests base_command = os.path.join(chip_root, "scripts/tests/run_python_test.py") - # Define the test python script files and patterns to exclude - excluded_patterns = { - "MinimalRepresentation.py", # Code/Test not being used or not shared code for any other tests - "TC_CNET_4_4.py", # It has no CI execution block, is not executed in CI - "TC_DGGEN_3_2.py", # src/python_testing/test_testing/test_TC_DGGEN_3_2.py is the Unit test of this test - "TC_EEVSE_Utils.py", # Shared code for TC_EEVSE, not a standalone test - "TC_EWATERHTRBase.py", # Shared code for TC_EWATERHTR, not a standalone test - "TC_EnergyReporting_Utils.py", # Shared code for TC_EEM and TC_EPM, not a standalone test - "TC_OpstateCommon.py", # Shared code for TC_OPSTATE, not a standalone test - "TC_pics_checker.py", # Currently isn't enabled because we don't have any examples with conformant PICS - "TC_TMP_2_1.py", # src/python_testing/test_testing/test_TC_TMP_2_1.py is the Unit test of this test - "TC_OCC_3_1.py", # There are CI issues for the test cases that implements manually controlling sensor device for the occupancy state ON/OFF change - "TC_OCC_3_2.py", # There are CI issues for the test cases that implements manually controlling sensor device for the occupancy state ON/OFF change - "TestCommissioningTimeSync.py", # Code/Test not being used or not shared code for any other tests - "TestConformanceSupport.py", # Unit test - does not run against an app - "TestChoiceConformanceSupport.py", # Unit test - does not run against an app - "TC_DEMTestBase.py", # Shared code for TC_DEM, not a standalone test - "TestConformanceTest.py", # Unit test of the conformance test (TC_DeviceConformance) - does not run against an app - "TestIdChecks.py", # Unit test - does not run against an app - "TestSpecParsingDeviceType.py", # Unit test - does not run against an app - "TestConformanceTest.py", # Unit test - does not run against an app - "TestMatterTestingSupport.py", # Unit test - does not run against an app - "TestSpecParsingSupport.py", # Unit test - does not run against an app - "TestTimeSyncTrustedTimeSource.py", # Unit test and shared code for scripts/tests/TestTimeSyncTrustedTimeSourceRunner.py - "drlk_2_x_common.py", # Shared code for TC_DRLK, not a standalone test - # Python code that runs all the python tests from src/python_testing (This code itself run via tests.yaml) - "execute_python_tests.py", - "hello_external_runner.py", # Code/Test not being used or not shared code for any other tests - "hello_test.py", # Is a template for tests - "test_plan_support.py", # Shared code for TC_*, not a standalone test - "test_plan_table_generator.py", # Code/Test not being used or not shared code for any other tests - } + metadata = yaml.full_load(open(os.path.join(chip_root, "src/python_testing/test_metadata.yaml"))) + excluded_patterns = set([item["name"] for item in metadata["not_automated"]]) # Get all .py files in the directory all_python_files = glob.glob(os.path.join(search_directory, "*.py")) diff --git a/src/python_testing/matter_testing_infrastructure/chip/testing/tasks.py b/src/python_testing/matter_testing_infrastructure/chip/testing/tasks.py index 39d1be3ec872e6..9b3a0b111fadbd 100644 --- a/src/python_testing/matter_testing_infrastructure/chip/testing/tasks.py +++ b/src/python_testing/matter_testing_infrastructure/chip/testing/tasks.py @@ -123,7 +123,7 @@ def start(self, # hang on the join call in our thread entry point in case of # Python process termination (not-caught exception). self.p.terminate() - raise TimeoutError("Expected output not found") + raise TimeoutError("Expected output '%r' not found within %s seconds" % (expected_output, timeout)) self.expected_output = None def send(self, message: str, end: str = "\n", diff --git a/src/python_testing/test_metadata.yaml b/src/python_testing/test_metadata.yaml new file mode 100644 index 00000000000000..3ff104a1a51f6b --- /dev/null +++ b/src/python_testing/test_metadata.yaml @@ -0,0 +1,102 @@ +# Tests that are NOT executed in CI, along with the reason on +# why they are not. +not_automated: + - name: MinimalRepresentation.py + reason: Code/Test not being used or not shared code for any other tests + - name: TC_CNET_4_4.py + reason: It has no CI execution block, is not executed in CI + - name: TC_DGGEN_3_2.py + reason: + src/python_testing/test_testing/test_TC_DGGEN_3_2.py is the Unit test + of this test + - name: TC_EEVSE_Utils.py + reason: Shared code for TC_EEVSE, not a standalone test + - name: TC_EWATERHTRBase.py + reason: Shared code for TC_EWATERHTR, not a standalone test + - name: TC_EnergyReporting_Utils.py + reason: Shared code for TC_EEM and TC_EPM, not a standalone test + - name: TC_OpstateCommon.py + reason: Shared code for TC_OPSTATE, not a standalone test + - name: TC_pics_checker.py + reason: + Currently isn't enabled because we don't have any examples with + conformant PICS + - name: TC_TMP_2_1.py + reason: + src/python_testing/test_testing/test_TC_TMP_2_1.py is the Unit test of + this test + - name: TC_OCC_3_1.py + reason: + There are CI issues for the test cases that implements manually + controlling sensor device for the occupancy state ON/OFF change + - name: TC_OCC_3_2.py + reason: + There are CI issues for the test cases that implements manually + controlling sensor device for the occupancy state ON/OFF change + - name: TestCommissioningTimeSync.py + reason: Code/Test not being used or not shared code for any other tests + - name: TestConformanceSupport.py + reason: Unit test - does not run against an app + - name: TestChoiceConformanceSupport.py + reason: Unit test - does not run against an app + - name: TC_DEMTestBase.py + reason: Shared code for TC_DEM, not a standalone test + - name: TestConformanceTest.py + reason: + Unit test of the conformance test (TC_DeviceConformance) - does not + run against an app + - name: TestIdChecks.py + reason: Unit test - does not run against an app + - name: TestSpecParsingDeviceType.py + reason: Unit test - does not run against an app + - name: TestConformanceTest.py + reason: Unit test - does not run against an app + - name: TestMatterTestingSupport.py + reason: Unit test - does not run against an app + - name: TestSpecParsingSupport.py + reason: Unit test - does not run against an app + - name: TestTimeSyncTrustedTimeSource.py + reason: + Unit test and shared code for + scripts/tests/TestTimeSyncTrustedTimeSourceRunner.py + - name: drlk_2_x_common.py + reason: Shared code for TC_DRLK, not a standalone test + - name: execute_python_tests.py + reason: + Python code that runs all the python tests from src/python_testing + (This code itself run via tests.yaml) + - name: hello_external_runner.py + reason: Code/Test not being used or not shared code for any other tests + - name: hello_test.py + reason: Is a template for tests + - name: test_plan_support.py + reason: Shared code for TC_*, not a standalone test + - name: test_plan_table_generator.py + reason: Code/Test not being used or not shared code for any other tests + +# This is a list of slow tests (just arbitrarely picked around 20 seconds) +# used in some script reporting for "be patient" messages as well as potentially +# to consider improving. May not be exhaustive +slow_tests: + - { name: mobile-device-test.py, duration: 3 minutes } + - { name: TC_AccessChecker.py, duration: 1.5 minutes } + - { name: TC_BRBINFO_4_1.py, duration: 2 minutes } + - { name: TC_CADMIN_1_9.py, duration: 40 seconds } + - { name: TC_CC_2_2.py, duration: 1.5 minutes } + - { name: TC_DEM_2_10.py, duration: 40 seconds } + - { name: TC_DeviceBasicComposition.py, duration: 25 seconds } + - { name: TC_DRLK_2_12.py, duration: 30 seconds } + - { name: TC_DRLK_2_3.py, duration: 30 seconds } + - { name: TC_EEVSE_2_6.py, duration: 30 seconds } + - { name: TC_FAN_3_1.py, duration: 15 seconds } + - { name: TC_MCORE_FS_1_4.py, duration: 20 seconds } + - { name: TC_OPSTATE_2_5.py, duration: 1.25 minutes } + - { name: TC_OPSTATE_2_6.py, duration: 35 seconds } + - { name: TC_PS_2_3.py, duration: 30 seconds } + - { name: TC_RR_1_1.py, duration: 25 seconds } + - { name: TC_SWTCH.py, duration: 1 minute } + - { name: TC_TIMESYNC_2_10.py, duration: 20 seconds } + - { name: TC_TIMESYNC_2_11.py, duration: 30 seconds } + - { name: TC_TIMESYNC_2_12.py, duration: 20 seconds } + - { name: TC_TIMESYNC_2_7.py, duration: 20 seconds } + - { name: TC_TIMESYNC_2_8.py, duration: 1.5 minutes } From 9c389ba953caa435d1f1ed34d5b799e9d1a7a4ea Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Mon, 4 Nov 2024 19:34:40 -0800 Subject: [PATCH 058/121] [Fabric-Sync] Port 'add-bridge' and 'remove-bridge' commands (#36241) * [Fabric-Sync] Implemenat 'add-bridge' command * Address review comments --- examples/fabric-sync/BUILD.gn | 16 +- examples/fabric-sync/admin/BUILD.gn | 30 + examples/fabric-sync/admin/DeviceManager.cpp | 111 ++++ examples/fabric-sync/admin/DeviceManager.h | 99 ++++ examples/fabric-sync/admin/PairingManager.cpp | 550 ++++++++++++++++++ examples/fabric-sync/admin/PairingManager.h | 203 +++++++ examples/fabric-sync/main.cpp | 18 + .../fabric-sync/shell/AddBridgeCommand.cpp | 80 +++ examples/fabric-sync/shell/AddBridgeCommand.h | 40 ++ examples/fabric-sync/shell/BUILD.gn | 44 ++ examples/fabric-sync/shell/CommandRegistry.h | 54 ++ .../fabric-sync/shell/RemoveBridgeCommand.cpp | 70 +++ .../fabric-sync/shell/RemoveBridgeCommand.h | 36 ++ examples/fabric-sync/shell/ShellCommands.cpp | 147 +++++ examples/fabric-sync/shell/ShellCommands.h | 27 + 15 files changed, 1524 insertions(+), 1 deletion(-) create mode 100644 examples/fabric-sync/admin/BUILD.gn create mode 100644 examples/fabric-sync/admin/DeviceManager.cpp create mode 100644 examples/fabric-sync/admin/DeviceManager.h create mode 100644 examples/fabric-sync/admin/PairingManager.cpp create mode 100644 examples/fabric-sync/admin/PairingManager.h create mode 100644 examples/fabric-sync/shell/AddBridgeCommand.cpp create mode 100644 examples/fabric-sync/shell/AddBridgeCommand.h create mode 100644 examples/fabric-sync/shell/BUILD.gn create mode 100644 examples/fabric-sync/shell/CommandRegistry.h create mode 100644 examples/fabric-sync/shell/RemoveBridgeCommand.cpp create mode 100644 examples/fabric-sync/shell/RemoveBridgeCommand.h create mode 100644 examples/fabric-sync/shell/ShellCommands.cpp create mode 100644 examples/fabric-sync/shell/ShellCommands.h diff --git a/examples/fabric-sync/BUILD.gn b/examples/fabric-sync/BUILD.gn index de193bd5f6207a..95b0ce3c60c46e 100644 --- a/examples/fabric-sync/BUILD.gn +++ b/examples/fabric-sync/BUILD.gn @@ -22,21 +22,35 @@ assert(chip_build_tools) executable("fabric-sync") { cflags = [ "-Wconversion" ] + defines = [] + + if (chip_build_libshell) { + defines += [ "ENABLE_CHIP_SHELL" ] + } + include_dirs = [ ".", "${chip_root}/src/lib", ] + if (chip_build_libshell) { + include_dirs += [ "shell" ] + } + sources = [ "main.cpp" ] deps = [ + "${chip_root}/examples/fabric-sync/admin:fabric-admin-lib", "${chip_root}/examples/fabric-sync/bridge:fabric-bridge-lib", - "${chip_root}/examples/fabric-sync/bridge:fabric-bridge-zap", "${chip_root}/examples/platform/linux:app-main", "${chip_root}/src/lib", "${chip_root}/third_party/inipp", ] + if (chip_build_libshell) { + deps += [ "${chip_root}/examples/fabric-sync/shell" ] + } + output_dir = root_out_dir } diff --git a/examples/fabric-sync/admin/BUILD.gn b/examples/fabric-sync/admin/BUILD.gn new file mode 100644 index 00000000000000..c2ab7152305204 --- /dev/null +++ b/examples/fabric-sync/admin/BUILD.gn @@ -0,0 +1,30 @@ +# Copyright (c) 2024 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("//build_overrides/chip.gni") +import("${chip_root}/src/app/chip_data_model.gni") + +source_set("fabric-admin-lib") { + sources = [ + "DeviceManager.cpp", + "DeviceManager.h", + "PairingManager.cpp", + "PairingManager.h", + ] + + deps = [ + "${chip_root}/examples/fabric-sync/bridge:fabric-bridge-lib", + "${chip_root}/src/lib", + ] +} diff --git a/examples/fabric-sync/admin/DeviceManager.cpp b/examples/fabric-sync/admin/DeviceManager.cpp new file mode 100644 index 00000000000000..79f41d5dc11c17 --- /dev/null +++ b/examples/fabric-sync/admin/DeviceManager.cpp @@ -0,0 +1,111 @@ +/* + * + * 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 "DeviceManager.h" + +#include +#include + +#include +#include + +using namespace chip; + +// Define the static member +DeviceManager DeviceManager::sInstance; + +void DeviceManager::Init() +{ + // TODO: (#34113) Init mLastUsedNodeId from chip config file + mLastUsedNodeId = 1; + mInitialized = true; + + ChipLogProgress(NotSpecified, "DeviceManager initialized: last used nodeId " ChipLogFormatX64, + ChipLogValueX64(mLastUsedNodeId)); +} + +NodeId DeviceManager::GetNextAvailableNodeId() +{ + mLastUsedNodeId++; + VerifyOrDieWithMsg(mLastUsedNodeId < std::numeric_limits::max(), NotSpecified, "No more available NodeIds."); + + return mLastUsedNodeId; +} + +void DeviceManager::UpdateLastUsedNodeId(NodeId nodeId) +{ + if (nodeId > mLastUsedNodeId) + { + mLastUsedNodeId = nodeId; + ChipLogProgress(NotSpecified, "Updating last used NodeId to " ChipLogFormatX64, ChipLogValueX64(mLastUsedNodeId)); + } +} + +void DeviceManager::SetRemoteBridgeNodeId(chip::NodeId nodeId) +{ + mRemoteBridgeNodeId = nodeId; +} + +CHIP_ERROR DeviceManager::PairRemoteFabricBridge(NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, + uint16_t deviceRemotePort) +{ + CHIP_ERROR err = PairingManager::Instance().PairDevice(nodeId, setupPINCode, deviceRemoteIp, deviceRemotePort); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, + "Failed to pair remote fabric bridge: Node ID " ChipLogFormatX64 " with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(nodeId), err.Format()); + return err; + } + + ChipLogProgress(NotSpecified, "Successfully paired remote fabric bridge: Node ID " ChipLogFormatX64, ChipLogValueX64(nodeId)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DeviceManager::UnpairRemoteFabricBridge() +{ + if (mRemoteBridgeNodeId == kUndefinedNodeId) + { + ChipLogError(NotSpecified, "Remote bridge node ID is undefined; cannot unpair device."); + return CHIP_ERROR_INCORRECT_STATE; + } + + CHIP_ERROR err = PairingManager::Instance().UnpairDevice(mRemoteBridgeNodeId); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to unpair remote bridge device " ChipLogFormatX64, ChipLogValueX64(mRemoteBridgeNodeId)); + return err; + } + + ChipLogProgress(NotSpecified, "Successfully unpaired remote fabric bridge: Node ID " ChipLogFormatX64, + ChipLogValueX64(mRemoteBridgeNodeId)); + return CHIP_NO_ERROR; +} + +void DeviceManager::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) +{ + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to remove synced device:(" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + return; + } + + ChipLogProgress(NotSpecified, "Synced device with NodeId:" ChipLogFormatX64 " has been removed.", ChipLogValueX64(deviceId)); +} diff --git a/examples/fabric-sync/admin/DeviceManager.h b/examples/fabric-sync/admin/DeviceManager.h new file mode 100644 index 00000000000000..5615df54a9cf32 --- /dev/null +++ b/examples/fabric-sync/admin/DeviceManager.h @@ -0,0 +1,99 @@ +/* + * + * 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. + */ + +#pragma once + +#include "PairingManager.h" + +#include +#include + +class DeviceManager : public PairingDelegate +{ +public: + DeviceManager() = default; + + void Init(); + + chip::NodeId GetNextAvailableNodeId(); + + chip::NodeId GetRemoteBridgeNodeId() const { return mRemoteBridgeNodeId; } + + void UpdateLastUsedNodeId(chip::NodeId nodeId); + + void SetRemoteBridgeNodeId(chip::NodeId nodeId); + + bool IsFabricSyncReady() const { return mRemoteBridgeNodeId != chip::kUndefinedNodeId; } + + /** + * @brief Determines whether a given nodeId corresponds to the remote bridge device. + * + * @param nodeId The ID of the node being checked. + * + * @return true if the nodeId matches the remote bridge device; otherwise, false. + */ + bool IsCurrentBridgeDevice(chip::NodeId nodeId) const { return nodeId == mRemoteBridgeNodeId; } + + /** + * @brief Pair a remote fabric bridge with a given node ID. + * + * This function initiates the pairing process for a remote fabric bridge using the specified parameters. + + * @param nodeId The user-defined ID for the node being commissioned. It doesn’t need to be the same ID, + * as for the first fabric. + * @param setupPINCode The setup PIN code used to authenticate the pairing process. + * @param deviceRemoteIp The IP address of the remote device that is being paired as part of the fabric bridge. + * @param deviceRemotePort The secured device port of the remote device that is being paired as part of the fabric bridge. + * + * @return CHIP_ERROR Returns CHIP_NO_ERROR on success or an appropriate error code on failure. + */ + CHIP_ERROR PairRemoteFabricBridge(chip::NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, + uint16_t deviceRemotePort); + + CHIP_ERROR UnpairRemoteFabricBridge(); + +private: + friend DeviceManager & DeviceMgr(); + + void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; + + static DeviceManager sInstance; + + chip::NodeId mLastUsedNodeId = 0; + + // The Node ID of the remote bridge used for Fabric-Sync + // This represents the bridge on the other ecosystem. + chip::NodeId mRemoteBridgeNodeId = chip::kUndefinedNodeId; + + bool mInitialized = false; +}; + +/** + * Returns the public interface of the DeviceManager singleton object. + * + * Applications should use this to access features of the DeviceManager + * object. + */ +inline DeviceManager & DeviceMgr() +{ + if (!DeviceManager::sInstance.mInitialized) + { + DeviceManager::sInstance.Init(); + } + return DeviceManager::sInstance; +} diff --git a/examples/fabric-sync/admin/PairingManager.cpp b/examples/fabric-sync/admin/PairingManager.cpp new file mode 100644 index 00000000000000..06c1f2b99b7336 --- /dev/null +++ b/examples/fabric-sync/admin/PairingManager.cpp @@ -0,0 +1,550 @@ +/* + * + * 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 "PairingManager.h" + +#include +#include +#include + +#include +#include +#include + +using namespace ::chip; +using namespace ::chip::Controller; + +namespace { + +CHIP_ERROR GetPayload(const char * setUpCode, SetupPayload & payload) +{ + VerifyOrReturnValue(setUpCode, CHIP_ERROR_INVALID_ARGUMENT); + bool isQRCode = strncmp(setUpCode, kQRCodePrefix, strlen(kQRCodePrefix)) == 0; + if (isQRCode) + { + ReturnErrorOnFailure(QRCodeSetupPayloadParser(setUpCode).populatePayload(payload)); + VerifyOrReturnError(payload.isValidQRCodePayload(), CHIP_ERROR_INVALID_ARGUMENT); + } + else + { + ReturnErrorOnFailure(ManualSetupPayloadParser(setUpCode).populatePayload(payload)); + VerifyOrReturnError(payload.isValidManualCode(), CHIP_ERROR_INVALID_ARGUMENT); + } + + return CHIP_NO_ERROR; +} + +bool ParseAddressWithInterface(const char * addressString, Inet::IPAddress & address, Inet::InterfaceId & interfaceId) +{ + struct addrinfo hints; + struct addrinfo * result; + int ret; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; + ret = getaddrinfo(addressString, nullptr, &hints, &result); + if (ret < 0) + { + ChipLogError(NotSpecified, "Invalid address: %s", addressString); + return false; + } + + if (result->ai_family == AF_INET6) + { + struct sockaddr_in6 * addr = reinterpret_cast(result->ai_addr); + address = Inet::IPAddress::FromSockAddr(*addr); + interfaceId = Inet::InterfaceId(addr->sin6_scope_id); + } +#if INET_CONFIG_ENABLE_IPV4 + else if (result->ai_family == AF_INET) + { + address = Inet::IPAddress::FromSockAddr(*reinterpret_cast(result->ai_addr)); + interfaceId = Inet::InterfaceId::Null(); + } +#endif // INET_CONFIG_ENABLE_IPV4 + else + { + ChipLogError(NotSpecified, "Unsupported address: %s", addressString); + freeaddrinfo(result); + return false; + } + + freeaddrinfo(result); + return true; +} + +} // namespace + +PairingManager::PairingManager() : + mOnOpenCommissioningWindowCallback(OnOpenCommissioningWindowResponse, this), + mOnOpenCommissioningWindowVerifierCallback(OnOpenCommissioningWindowVerifierResponse, this), + mCurrentFabricRemoveCallback(OnCurrentFabricRemove, this) +{} + +CHIP_ERROR PairingManager::Init(Controller::DeviceCommissioner * commissioner) +{ + VerifyOrReturnError(commissioner != nullptr, CHIP_ERROR_INCORRECT_STATE); + + mCommissioner = commissioner; + + return CHIP_NO_ERROR; +} + +CHIP_ERROR PairingManager::OpenCommissioningWindow(NodeId nodeId, EndpointId endpointId, uint16_t commissioningTimeoutSec, + uint32_t iterations, uint16_t discriminator, const ByteSpan & salt, + const ByteSpan & verifier) +{ + if (mCommissioner == nullptr) + { + ChipLogError(NotSpecified, "Commissioner is null, cannot open commissioning window"); + return CHIP_ERROR_INCORRECT_STATE; + } + + // Check if a window is already open + if (mWindowOpener != nullptr) + { + ChipLogError(NotSpecified, "A commissioning window is already open"); + return CHIP_ERROR_INCORRECT_STATE; + } + + // Ensure salt and verifier sizes are valid + if (!salt.empty() && salt.size() > chip::Crypto::kSpake2p_Max_PBKDF_Salt_Length) + { + ChipLogError(NotSpecified, "Salt size exceeds buffer capacity"); + return CHIP_ERROR_BUFFER_TOO_SMALL; + } + + if (!verifier.empty() && verifier.size() > chip::Crypto::kSpake2p_VerifierSerialized_Length) + { + ChipLogError(NotSpecified, "Verifier size exceeds buffer capacity"); + return CHIP_ERROR_BUFFER_TOO_SMALL; + } + + if (!salt.empty()) + { + memcpy(mSaltBuffer, salt.data(), salt.size()); + mSalt = ByteSpan(mSaltBuffer, salt.size()); + } + else + { + mSalt = ByteSpan(); + } + + if (!verifier.empty()) + { + memcpy(mVerifierBuffer, verifier.data(), verifier.size()); + mVerifier = ByteSpan(mVerifierBuffer, verifier.size()); + } + else + { + mVerifier = ByteSpan(); + } + + return DeviceLayer::SystemLayer().ScheduleLambda([nodeId, endpointId, commissioningTimeoutSec, iterations, discriminator]() { + PairingManager & self = PairingManager::Instance(); + + if (self.mCommissioner == nullptr) + { + ChipLogError(NotSpecified, "Commissioner is null, cannot open commissioning window"); + return; + } + + self.mWindowOpener = Platform::MakeUnique(self.mCommissioner); + + if (!self.mVerifier.empty()) + { + if (self.mSalt.empty()) + { + ChipLogError(NotSpecified, "Salt is required when verifier is set"); + self.mWindowOpener.reset(); + return; + } + + // Open the commissioning window with verifier parameters + CHIP_ERROR err = + self.mWindowOpener->OpenCommissioningWindow(Controller::CommissioningWindowVerifierParams() + .SetNodeId(nodeId) + .SetEndpointId(endpointId) + .SetTimeout(commissioningTimeoutSec) + .SetIteration(iterations) + .SetDiscriminator(discriminator) + .SetVerifier(self.mVerifier) + .SetSalt(self.mSalt) + .SetCallback(&self.mOnOpenCommissioningWindowVerifierCallback)); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to open commissioning window with verifier: %s", ErrorStr(err)); + self.mWindowOpener.reset(); + } + } + else + { + SetupPayload ignored; + // Open the commissioning window with passcode parameters + CHIP_ERROR err = self.mWindowOpener->OpenCommissioningWindow(Controller::CommissioningWindowPasscodeParams() + .SetNodeId(nodeId) + .SetEndpointId(endpointId) + .SetTimeout(commissioningTimeoutSec) + .SetIteration(iterations) + .SetDiscriminator(discriminator) + .SetSetupPIN(NullOptional) + .SetSalt(NullOptional) + .SetCallback(&self.mOnOpenCommissioningWindowCallback), + ignored); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to open commissioning window with passcode: %s", ErrorStr(err)); + self.mWindowOpener.reset(); + } + } + }); +} + +void PairingManager::OnOpenCommissioningWindowResponse(void * context, NodeId remoteId, CHIP_ERROR err, SetupPayload payload) +{ + VerifyOrDie(context != nullptr); + PairingManager * self = static_cast(context); + if (self->mCommissioningWindowDelegate) + { + self->mCommissioningWindowDelegate->OnCommissioningWindowOpened(remoteId, err, payload); + self->SetOpenCommissioningWindowDelegate(nullptr); + } + + OnOpenCommissioningWindowVerifierResponse(context, remoteId, err); +} + +void PairingManager::OnOpenCommissioningWindowVerifierResponse(void * context, NodeId remoteId, CHIP_ERROR err) +{ + VerifyOrDie(context != nullptr); + PairingManager * self = static_cast(context); + LogErrorOnFailure(err); + + // Reset the window opener once the window operation is complete + self->mWindowOpener.reset(); +} + +void PairingManager::OnStatusUpdate(DevicePairingDelegate::Status status) +{ + switch (status) + { + case DevicePairingDelegate::Status::SecurePairingSuccess: + ChipLogProgress(NotSpecified, "CASE establishment successful"); + break; + case DevicePairingDelegate::Status::SecurePairingFailed: + ChipLogError(NotSpecified, "Secure Pairing Failed"); + break; + } +} + +void PairingManager::OnPairingComplete(CHIP_ERROR err) +{ + if (err == CHIP_NO_ERROR) + { + ChipLogProgress(NotSpecified, "PASE establishment successful"); + } + else + { + ChipLogProgress(NotSpecified, "Pairing Failure: %s", ErrorStr(err)); + } +} + +void PairingManager::OnPairingDeleted(CHIP_ERROR err) +{ + if (err == CHIP_NO_ERROR) + { + ChipLogProgress(NotSpecified, "Pairing Deleted Success"); + } + else + { + ChipLogProgress(NotSpecified, "Pairing Deleted Failure: %s", ErrorStr(err)); + } +} + +void PairingManager::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err) +{ + if (err == CHIP_NO_ERROR) + { + // print to console + fprintf(stderr, "New device with Node ID: " ChipLogFormatX64 " has been successfully added.\n", ChipLogValueX64(nodeId)); + } + else + { + ChipLogProgress(NotSpecified, "Device commissioning Failure: %s", ErrorStr(err)); + } + + if (mCommissioningDelegate) + { + mCommissioningDelegate->OnCommissioningComplete(nodeId, err); + SetCommissioningDelegate(nullptr); + } +} + +void PairingManager::OnReadCommissioningInfo(const Controller::ReadCommissioningInfo & info) +{ + ChipLogProgress(AppServer, "OnReadCommissioningInfo - vendorId=0x%04X productId=0x%04X", info.basic.vendorId, + info.basic.productId); + + // The string in CharSpan received from the device is not null-terminated, we use std::string here for coping and + // appending a null-terminator at the end of the string. + std::string userActiveModeTriggerInstruction; + + // Note: the callback doesn't own the buffer, should make a copy if it will be used it later. + if (info.icd.userActiveModeTriggerInstruction.size() != 0) + { + userActiveModeTriggerInstruction = + std::string(info.icd.userActiveModeTriggerInstruction.data(), info.icd.userActiveModeTriggerInstruction.size()); + } + + if (info.icd.userActiveModeTriggerHint.HasAny()) + { + ChipLogProgress(AppServer, "OnReadCommissioningInfo - LIT UserActiveModeTriggerHint=0x%08x", + info.icd.userActiveModeTriggerHint.Raw()); + ChipLogProgress(AppServer, "OnReadCommissioningInfo - LIT UserActiveModeTriggerInstruction=%s", + userActiveModeTriggerInstruction.c_str()); + } + ChipLogProgress(AppServer, "OnReadCommissioningInfo ICD - IdleModeDuration=%u activeModeDuration=%u activeModeThreshold=%u", + info.icd.idleModeDuration, info.icd.activeModeDuration, info.icd.activeModeThreshold); +} + +void PairingManager::OnDiscoveredDevice(const Dnssd::CommissionNodeData & nodeData) +{ + // Ignore nodes with closed commissioning window + VerifyOrReturn(nodeData.commissioningMode != 0); + + auto & resolutionData = nodeData; + + const uint16_t port = resolutionData.port; + char buf[Inet::IPAddress::kMaxStringLength]; + resolutionData.ipAddress[0].ToString(buf); + ChipLogProgress(NotSpecified, "Discovered Device: %s:%u", buf, port); + + // Stop Mdns discovery. + auto err = mCommissioner->StopCommissionableDiscovery(); + + // Some platforms does not implement a mechanism to stop mdns browse, so + // we just ignore CHIP_ERROR_NOT_IMPLEMENTED instead of bailing out. + if (CHIP_NO_ERROR != err && CHIP_ERROR_NOT_IMPLEMENTED != err) + { + return; + } + + mCommissioner->RegisterDeviceDiscoveryDelegate(nullptr); + + auto interfaceId = resolutionData.ipAddress[0].IsIPv6LinkLocal() ? resolutionData.interfaceId : Inet::InterfaceId::Null(); + auto peerAddress = Transport::PeerAddress::UDP(resolutionData.ipAddress[0], port, interfaceId); + err = Pair(mNodeId, peerAddress); + if (CHIP_NO_ERROR != err) + { + ChipLogProgress(NotSpecified, "Failed to pair device: " ChipLogFormatX64 " %s", ChipLogValueX64(mNodeId), ErrorStr(err)); + } +} + +Optional PairingManager::FailSafeExpiryTimeoutSecs() const +{ + // No manual input, so do not need to extend. + return Optional(); +} + +bool PairingManager::ShouldWaitAfterDeviceAttestation() +{ + // If there is a vendor ID and product ID, request OnDeviceAttestationCompleted(). + // Currently this is added in the case that the example is performing reverse commissioning, + // but it would be an improvement to store that explicitly. + // TODO: Issue #35297 - [Fabric Sync] Improve where we get VID and PID when validating CCTRL CommissionNode command + SetupPayload payload; + CHIP_ERROR err = GetPayload(mOnboardingPayload, payload); + return err == CHIP_NO_ERROR && (payload.vendorID != 0 || payload.productID != 0); +} + +void PairingManager::OnDeviceAttestationCompleted(Controller::DeviceCommissioner * deviceCommissioner, DeviceProxy * device, + const Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, + Credentials::AttestationVerificationResult attestationResult) +{ + SetupPayload payload; + CHIP_ERROR parse_error = GetPayload(mOnboardingPayload, payload); + if (parse_error == CHIP_NO_ERROR && (payload.vendorID != 0 || payload.productID != 0)) + { + if (payload.vendorID == 0 || payload.productID == 0) + { + ChipLogProgress(NotSpecified, + "Failed validation: vendorID or productID must not be 0." + "Requested VID: %u, Requested PID: %u.", + payload.vendorID, payload.productID); + deviceCommissioner->ContinueCommissioningAfterDeviceAttestation( + device, Credentials::AttestationVerificationResult::kInvalidArgument); + return; + } + + if (payload.vendorID != info.BasicInformationVendorId() || payload.productID != info.BasicInformationProductId()) + { + ChipLogProgress(NotSpecified, + "Failed validation of vendorID or productID." + "Requested VID: %u, Requested PID: %u," + "Detected VID: %u, Detected PID %u.", + payload.vendorID, payload.productID, info.BasicInformationVendorId(), info.BasicInformationProductId()); + deviceCommissioner->ContinueCommissioningAfterDeviceAttestation( + device, + payload.vendorID == info.BasicInformationVendorId() + ? Credentials::AttestationVerificationResult::kDacProductIdMismatch + : Credentials::AttestationVerificationResult::kDacVendorIdMismatch); + return; + } + + // NOTE: This will log errors even if the attestion was successful. + CHIP_ERROR err = deviceCommissioner->ContinueCommissioningAfterDeviceAttestation(device, attestationResult); + if (CHIP_NO_ERROR != err) + { + ChipLogError(NotSpecified, "Failed to continue commissioning after device attestation, error: %s", ErrorStr(err)); + } + return; + } + + // Don't bypass attestation, continue with error. + CHIP_ERROR err = deviceCommissioner->ContinueCommissioningAfterDeviceAttestation(device, attestationResult); + if (CHIP_NO_ERROR != err) + { + ChipLogError(NotSpecified, "Failed to continue commissioning after device attestation, error: %s", ErrorStr(err)); + } +} + +CommissioningParameters PairingManager::GetCommissioningParameters() +{ + auto params = CommissioningParameters(); + params.SetSkipCommissioningComplete(false); + params.SetDeviceAttestationDelegate(this); + + return params; +} + +CHIP_ERROR PairingManager::Pair(NodeId remoteId, Transport::PeerAddress address) +{ + auto params = RendezvousParameters().SetSetupPINCode(mSetupPINCode).SetDiscriminator(mDiscriminator).SetPeerAddress(address); + + CHIP_ERROR err = CHIP_NO_ERROR; + auto commissioningParams = GetCommissioningParameters(); + err = CurrentCommissioner().PairDevice(remoteId, params, commissioningParams); + + return err; +} + +void PairingManager::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_ERROR err) +{ + PairingManager * self = reinterpret_cast(context); + VerifyOrReturn(self != nullptr, ChipLogError(NotSpecified, "OnCurrentFabricRemove: context is null")); + + if (err == CHIP_NO_ERROR) + { + // print to console + fprintf(stderr, "Device with Node ID: " ChipLogFormatX64 "has been successfully removed.\n", ChipLogValueX64(nodeId)); + } + else + { + ChipLogProgress(NotSpecified, "Device unpair Failure: " ChipLogFormatX64 " %s", ChipLogValueX64(nodeId), ErrorStr(err)); + } +} + +void PairingManager::InitPairingCommand() +{ + mCommissioner->RegisterPairingDelegate(this); +} + +CHIP_ERROR PairingManager::PairDeviceWithCode(NodeId nodeId, const char * payload) +{ + if (payload == nullptr || strlen(payload) > kMaxManualCodeLength + 1) + { + ChipLogError(NotSpecified, "PairDeviceWithCode failed: Invalid pairing payload"); + return CHIP_ERROR_INVALID_STRING_LENGTH; + } + + Platform::CopyString(mOnboardingPayload, sizeof(mOnboardingPayload), payload); + + return DeviceLayer::SystemLayer().ScheduleLambda([nodeId]() { + PairingManager & self = PairingManager::Instance(); + + self.InitPairingCommand(); + + CommissioningParameters commissioningParams = self.GetCommissioningParameters(); + auto discoveryType = DiscoveryType::kDiscoveryNetworkOnly; + + self.mNodeId = nodeId; + + CHIP_ERROR err = self.mCommissioner->PairDevice(nodeId, self.mOnboardingPayload, commissioningParams, discoveryType); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to pair device with code, error: %s", ErrorStr(err)); + } + }); +} + +CHIP_ERROR PairingManager::PairDevice(chip::NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, + uint16_t deviceRemotePort) +{ + if (deviceRemoteIp == nullptr || strlen(deviceRemoteIp) > Inet::IPAddress::kMaxStringLength) + { + ChipLogError(NotSpecified, "PairDevice failed: Invalid device remote IP address"); + return CHIP_ERROR_INVALID_STRING_LENGTH; + } + + Platform::CopyString(mRemoteIpAddr, sizeof(mRemoteIpAddr), deviceRemoteIp); + + return DeviceLayer::SystemLayer().ScheduleLambda([nodeId, setupPINCode, deviceRemotePort]() { + PairingManager & self = PairingManager::Instance(); + + self.InitPairingCommand(); + self.mSetupPINCode = setupPINCode; + + Inet::IPAddress address; + Inet::InterfaceId interfaceId; + + if (!ParseAddressWithInterface(self.mRemoteIpAddr, address, interfaceId)) + { + ChipLogError(NotSpecified, "Invalid IP address: %s", self.mRemoteIpAddr); + return; + } + + CHIP_ERROR err = self.Pair(nodeId, Transport::PeerAddress::UDP(address, deviceRemotePort, interfaceId)); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to pair device, error: %s", ErrorStr(err)); + } + }); +} + +CHIP_ERROR PairingManager::UnpairDevice(NodeId nodeId) +{ + return DeviceLayer::SystemLayer().ScheduleLambda([nodeId]() { + PairingManager & self = PairingManager::Instance(); + + self.InitPairingCommand(); + + self.mCurrentFabricRemover = Platform::MakeUnique(self.mCommissioner); + + if (!self.mCurrentFabricRemover) + { + ChipLogError(NotSpecified, "Failed to unpair device, mCurrentFabricRemover is null"); + return; + } + + CHIP_ERROR err = self.mCurrentFabricRemover->RemoveCurrentFabric(nodeId, &self.mCurrentFabricRemoveCallback); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to unpair device, error: %s", ErrorStr(err)); + } + }); +} diff --git a/examples/fabric-sync/admin/PairingManager.h b/examples/fabric-sync/admin/PairingManager.h new file mode 100644 index 00000000000000..07cba7488154f8 --- /dev/null +++ b/examples/fabric-sync/admin/PairingManager.h @@ -0,0 +1,203 @@ +/* + * + * 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. + */ + +#pragma once + +#include +#include +#include +#include +#include + +// Constants +constexpr uint16_t kMaxManualCodeLength = 22; + +class CommissioningWindowDelegate +{ +public: + virtual void OnCommissioningWindowOpened(chip::NodeId deviceId, CHIP_ERROR err, chip::SetupPayload payload) = 0; + virtual ~CommissioningWindowDelegate() = default; +}; + +class CommissioningDelegate +{ +public: + virtual void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) = 0; + virtual ~CommissioningDelegate() = default; +}; + +class PairingDelegate +{ +public: + virtual void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) = 0; + virtual ~PairingDelegate() = default; +}; + +/** + * The PairingManager class is responsible for managing the commissioning and pairing process + * of Matter devices. PairingManager is designed to be used as a singleton, meaning that there + * should only be one instance of it running at any given time. + * + * Usage: + * + * 1. The class should be initialized when the system starts up, typically by invoking the static + * instance method to get the singleton. + * 2. To open a commissioning window, the appropriate method should be called on the PairingManager instance. + * 3. The PairingManager will handle the lifecycle of the CommissioningWindowOpener and ensure that + * resources are cleaned up appropriately when pairing is complete or the process is aborted. + * + * Example: + * + * @code + * PairingManager& manager = PairingManager::Instance(); + * manager.OpenCommissioningWindow(); + * @endcode + */ +class PairingManager : public chip::Controller::DevicePairingDelegate, + public chip::Controller::DeviceDiscoveryDelegate, + public chip::Credentials::DeviceAttestationDelegate +{ +public: + static PairingManager & Instance() + { + static PairingManager instance; + return instance; + } + + CHIP_ERROR Init(chip::Controller::DeviceCommissioner * commissioner); + + void SetOpenCommissioningWindowDelegate(CommissioningWindowDelegate * delegate) { mCommissioningWindowDelegate = delegate; } + void SetCommissioningDelegate(CommissioningDelegate * delegate) { mCommissioningDelegate = delegate; } + void SetPairingDelegate(PairingDelegate * delegate) { mPairingDelegate = delegate; } + PairingDelegate * GetPairingDelegate() { return mPairingDelegate; } + + chip::Controller::DeviceCommissioner & CurrentCommissioner() { return *mCommissioner; }; + + /** + * Opens a commissioning window on the specified node and endpoint. + * Only one commissioning window can be active at a time. If a commissioning + * window is already open, this function will return an error. + * + * @param nodeId The target node ID for commissioning. + * @param endpointId The target endpoint ID for commissioning. + * @param commissioningTimeoutSec Timeout for the commissioning window in seconds. + * @param iterations Iterations for PBKDF calculations. + * @param discriminator Discriminator for commissioning. + * @param salt Optional salt for verifier-based commissioning. + * @param verifier Optional verifier for enhanced commissioning security. + * + * @return CHIP_ERROR_INCORRECT_STATE if a commissioning window is already open. + */ + CHIP_ERROR OpenCommissioningWindow(chip::NodeId nodeId, chip::EndpointId endpointId, uint16_t commissioningTimeoutSec, + uint32_t iterations, uint16_t discriminator, const chip::ByteSpan & salt, + const chip::ByteSpan & verifier); + + /** + * Pairs a device using a setup code payload. + * + * @param nodeId The target node ID for pairing. + * @param payload The setup code payload, which typically contains device-specific pairing information. + * + * @return CHIP_NO_ERROR on successful initiation of the pairing process, or an appropriate CHIP_ERROR if pairing fails. + */ + CHIP_ERROR PairDeviceWithCode(chip::NodeId nodeId, const char * payload); + + /** + * Pairs a device using its setup PIN code and remote IP address. + * + * @param nodeId The target node ID for pairing. + * @param setupPINCode The setup PIN code for the device, used for establishing a secure connection. + * @param deviceRemoteIp The IP address of the remote device. + * @param deviceRemotePort The port number on which the device is listening for pairing requests. + * + * @return CHIP_NO_ERROR if the pairing process is initiated successfully, or an appropriate CHIP_ERROR if pairing fails. + */ + CHIP_ERROR PairDevice(chip::NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, uint16_t deviceRemotePort); + + /** + * Unpairs a device with the specified node ID. + * + * @param nodeId The node ID of the device to be unpaired. + * + * @return CHIP_NO_ERROR if the device is successfully unpaired, or an appropriate CHIP_ERROR if the process fails. + */ + CHIP_ERROR UnpairDevice(chip::NodeId nodeId); + +private: + // Constructors + PairingManager(); + PairingManager(const PairingManager &) = delete; + PairingManager & operator=(const PairingManager &) = delete; + + // Private member functions (static and non-static) + chip::Controller::CommissioningParameters GetCommissioningParameters(); + void InitPairingCommand(); + CHIP_ERROR Pair(chip::NodeId remoteId, chip::Transport::PeerAddress address); + + /////////// DevicePairingDelegate Interface ///////// + void OnStatusUpdate(chip::Controller::DevicePairingDelegate::Status status) override; + void OnPairingComplete(CHIP_ERROR error) override; + void OnPairingDeleted(CHIP_ERROR error) override; + void OnReadCommissioningInfo(const chip::Controller::ReadCommissioningInfo & info) override; + void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR error) override; + + /////////// DeviceDiscoveryDelegate Interface ///////// + void OnDiscoveredDevice(const chip::Dnssd::CommissionNodeData & nodeData) override; + + /////////// DeviceAttestationDelegate Interface ///////// + chip::Optional FailSafeExpiryTimeoutSecs() const override; + bool ShouldWaitAfterDeviceAttestation() override; + void OnDeviceAttestationCompleted(chip::Controller::DeviceCommissioner * deviceCommissioner, chip::DeviceProxy * device, + const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, + chip::Credentials::AttestationVerificationResult attestationResult) override; + + static void OnOpenCommissioningWindowResponse(void * context, chip::NodeId deviceId, CHIP_ERROR status, + chip::SetupPayload payload); + static void OnOpenCommissioningWindowVerifierResponse(void * context, chip::NodeId deviceId, CHIP_ERROR status); + static void OnCurrentFabricRemove(void * context, chip::NodeId remoteNodeId, CHIP_ERROR status); + + // Private data members + chip::Controller::DeviceCommissioner * mCommissioner = nullptr; + + CommissioningWindowDelegate * mCommissioningWindowDelegate = nullptr; + CommissioningDelegate * mCommissioningDelegate = nullptr; + PairingDelegate * mPairingDelegate = nullptr; + + chip::NodeId mNodeId = chip::kUndefinedNodeId; + chip::ByteSpan mVerifier; + chip::ByteSpan mSalt; + uint16_t mDiscriminator = 0; + uint32_t mSetupPINCode = 0; + uint8_t mVerifierBuffer[chip::Crypto::kSpake2p_VerifierSerialized_Length]; + uint8_t mSaltBuffer[chip::Crypto::kSpake2p_Max_PBKDF_Salt_Length]; + char mRemoteIpAddr[chip::Inet::IPAddress::kMaxStringLength]; + char mOnboardingPayload[kMaxManualCodeLength + 1]; + + /** + * Holds the unique_ptr to the current CommissioningWindowOpener. + * Only one commissioning window opener can be active at a time. + * The pointer is reset when the commissioning window is closed or when an error occurs. + */ + chip::Platform::UniquePtr mWindowOpener; + chip::Callback::Callback mOnOpenCommissioningWindowCallback; + chip::Callback::Callback mOnOpenCommissioningWindowVerifierCallback; + + // For Unpair + chip::Platform::UniquePtr mCurrentFabricRemover; + chip::Callback::Callback mCurrentFabricRemoveCallback; +}; diff --git a/examples/fabric-sync/main.cpp b/examples/fabric-sync/main.cpp index 66541b32de91f9..45e0ce388ef0ff 100644 --- a/examples/fabric-sync/main.cpp +++ b/examples/fabric-sync/main.cpp @@ -17,6 +17,11 @@ */ #include +#include + +#if defined(ENABLE_CHIP_SHELL) +#include "ShellCommands.h" +#endif using namespace chip; @@ -90,6 +95,19 @@ int main(int argc, char * argv[]) VerifyOrDie(ChipLinuxAppInit(argc, argv) == 0); +#if defined(ENABLE_CHIP_SHELL) + Shell::RegisterCommands(); +#endif + + CHIP_ERROR err = PairingManager::Instance().Init(GetDeviceCommissioner()); + if (err != CHIP_NO_ERROR) + { + ChipLogProgress(NotSpecified, "Failed to init PairingManager: %s ", ErrorStr(err)); + + // End the program with non zero error code to indicate a error. + return 1; + } + ChipLinuxAppMainLoop(); return 0; diff --git a/examples/fabric-sync/shell/AddBridgeCommand.cpp b/examples/fabric-sync/shell/AddBridgeCommand.cpp new file mode 100644 index 00000000000000..d02ad9f58dba11 --- /dev/null +++ b/examples/fabric-sync/shell/AddBridgeCommand.cpp @@ -0,0 +1,80 @@ +/* + * 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 "AddBridgeCommand.h" + +#include +#include + +using namespace ::chip; + +namespace commands { + +AddBridgeCommand::AddBridgeCommand(chip::NodeId nodeId, uint32_t setupPINCode, const char * remoteAddr, uint16_t remotePort) : + mBridgeNodeId(nodeId), mSetupPINCode(setupPINCode), mRemoteAddr(remoteAddr), mRemotePort(remotePort) +{} + +void AddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) +{ + if (mBridgeNodeId != deviceId) + { + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to pair non-bridge device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + else + { + ChipLogProgress(NotSpecified, "Commissioning complete for non-bridge device: NodeId: " ChipLogFormatX64, + ChipLogValueX64(deviceId)); + } + return; + } + + if (err == CHIP_NO_ERROR) + { + DeviceMgr().SetRemoteBridgeNodeId(mBridgeNodeId); + ChipLogProgress(NotSpecified, "Successfully paired bridge device: NodeId: " ChipLogFormatX64, + ChipLogValueX64(mBridgeNodeId)); + + DeviceMgr().UpdateLastUsedNodeId(mBridgeNodeId); + } + else + { + ChipLogError(NotSpecified, "Failed to pair bridge device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + + CommandRegistry::Instance().ResetActiveCommand(); +} + +CHIP_ERROR AddBridgeCommand::RunCommand() +{ + if (DeviceMgr().IsFabricSyncReady()) + { + // print to console + fprintf(stderr, "Remote Fabric Bridge has already been configured.\n"); + return CHIP_ERROR_BUSY; + } + + PairingManager::Instance().SetCommissioningDelegate(this); + + return DeviceMgr().PairRemoteFabricBridge(mBridgeNodeId, mSetupPINCode, mRemoteAddr, mRemotePort); +} + +} // namespace commands diff --git a/examples/fabric-sync/shell/AddBridgeCommand.h b/examples/fabric-sync/shell/AddBridgeCommand.h new file mode 100644 index 00000000000000..d4b2c16f1e21d9 --- /dev/null +++ b/examples/fabric-sync/shell/AddBridgeCommand.h @@ -0,0 +1,40 @@ +/* + * 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. + * + */ + +#pragma once + +#include +#include + +namespace commands { + +class AddBridgeCommand : public Command, public CommissioningDelegate +{ +public: + AddBridgeCommand(chip::NodeId nodeId, uint32_t setupPINCode, const char * remoteAddr, uint16_t remotePort); + void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) override; + CHIP_ERROR RunCommand() override; + +private: + chip::NodeId mBridgeNodeId; + uint32_t mSetupPINCode; + const char * mRemoteAddr; + uint16_t mRemotePort; +}; + +} // namespace commands diff --git a/examples/fabric-sync/shell/BUILD.gn b/examples/fabric-sync/shell/BUILD.gn new file mode 100644 index 00000000000000..6f64b9106ab2bf --- /dev/null +++ b/examples/fabric-sync/shell/BUILD.gn @@ -0,0 +1,44 @@ +# Copyright (c) 2024 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("//build_overrides/chip.gni") +import("${chip_root}/src/app/chip_data_model.gni") + +config("config") { + include_dirs = [ + ".", + "${chip_root}/examples/common", + "${chip_root}/examples/fabric-sync", + ] +} + +source_set("shell") { + public_configs = [ ":config" ] + + sources = [ + "AddBridgeCommand.cpp", + "AddBridgeCommand.h", + "CommandRegistry.h", + "RemoveBridgeCommand.cpp", + "RemoveBridgeCommand.h", + "ShellCommands.cpp", + "ShellCommands.h", + ] + + deps = [ + "${chip_root}/examples/fabric-sync/admin:fabric-admin-lib", + "${chip_root}/examples/fabric-sync/bridge:fabric-bridge-lib", + "${chip_root}/src/lib", + ] +} diff --git a/examples/fabric-sync/shell/CommandRegistry.h b/examples/fabric-sync/shell/CommandRegistry.h new file mode 100644 index 00000000000000..ec53e17960d98c --- /dev/null +++ b/examples/fabric-sync/shell/CommandRegistry.h @@ -0,0 +1,54 @@ +/* + * 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. + * + */ + +#pragma once + +#include + +namespace commands { + +class Command +{ +public: + virtual ~Command() = default; + virtual CHIP_ERROR RunCommand() = 0; +}; + +class CommandRegistry +{ +public: + static CommandRegistry & Instance() + { + static CommandRegistry instance; + return instance; + } + + void SetActiveCommand(std::unique_ptr command) { mActiveCommand = std::move(command); } + + Command * GetActiveCommand() { return mActiveCommand.get(); } + + void ResetActiveCommand() { mActiveCommand.reset(); } + + bool IsCommandActive() const { return mActiveCommand != nullptr; } + +private: + CommandRegistry() = default; + std::unique_ptr mActiveCommand; +}; + +} // namespace commands diff --git a/examples/fabric-sync/shell/RemoveBridgeCommand.cpp b/examples/fabric-sync/shell/RemoveBridgeCommand.cpp new file mode 100644 index 00000000000000..9e8f1ed5fa8cd5 --- /dev/null +++ b/examples/fabric-sync/shell/RemoveBridgeCommand.cpp @@ -0,0 +1,70 @@ +/* + * 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 "RemoveBridgeCommand.h" + +#include +#include + +using namespace ::chip; + +namespace commands { + +void RemoveBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) +{ + if (mBridgeNodeId != deviceId) + { + ChipLogProgress(NotSpecified, "An non-bridge device: NodeId: " ChipLogFormatX64 " is removed.", ChipLogValueX64(deviceId)); + return; + } + + if (err == CHIP_NO_ERROR) + { + DeviceMgr().SetRemoteBridgeNodeId(kUndefinedNodeId); + ChipLogProgress(NotSpecified, "Successfully removed bridge device: NodeId: " ChipLogFormatX64, + ChipLogValueX64(mBridgeNodeId)); + } + else + { + ChipLogError(NotSpecified, "Failed to remove bridge device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + + CommandRegistry::Instance().ResetActiveCommand(); +} + +CHIP_ERROR RemoveBridgeCommand::RunCommand() +{ + NodeId bridgeNodeId = DeviceMgr().GetRemoteBridgeNodeId(); + + if (bridgeNodeId == kUndefinedNodeId) + { + // print to console + fprintf(stderr, "Remote Fabric Bridge is not configured yet, nothing to remove.\n"); + return CHIP_ERROR_BUSY; + } + + mBridgeNodeId = bridgeNodeId; + + PairingManager::Instance().SetPairingDelegate(this); + DeviceMgr().UnpairRemoteFabricBridge(); + + return CHIP_NO_ERROR; +} + +} // namespace commands diff --git a/examples/fabric-sync/shell/RemoveBridgeCommand.h b/examples/fabric-sync/shell/RemoveBridgeCommand.h new file mode 100644 index 00000000000000..401a5390be8fd9 --- /dev/null +++ b/examples/fabric-sync/shell/RemoveBridgeCommand.h @@ -0,0 +1,36 @@ +/* + * 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. + * + */ + +#pragma once + +#include +#include + +namespace commands { + +class RemoveBridgeCommand : public Command, public PairingDelegate +{ +public: + void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; + CHIP_ERROR RunCommand() override; + +private: + chip::NodeId mBridgeNodeId = chip::kUndefinedNodeId; +}; + +} // namespace commands diff --git a/examples/fabric-sync/shell/ShellCommands.cpp b/examples/fabric-sync/shell/ShellCommands.cpp new file mode 100644 index 00000000000000..1edbd433eac64a --- /dev/null +++ b/examples/fabric-sync/shell/ShellCommands.cpp @@ -0,0 +1,147 @@ +/* + * + * Copyright (c) 2024 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. + */ + +#include "ShellCommands.h" +#include "AddBridgeCommand.h" +#include "RemoveBridgeCommand.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace chip { +namespace Shell { + +static CHIP_ERROR PrintAllCommands() +{ + streamer_t * sout = streamer_get(); + streamer_printf(sout, " help Usage: app \r\n"); + streamer_printf(sout, + " add-bridge Pair remote fabric bridge to local fabric. Usage: app add-bridge node-id setup-pin-code " + "device-remote-ip device-remote-port\r\n"); + streamer_printf(sout, " remove-bridge Remove the remote fabric bridge from the local fabric. Usage: app remove-bridge\r\n"); + streamer_printf(sout, " sync-device Sync a device from other ecosystem. Usage: app sync-device endpointid\r\n"); + streamer_printf(sout, "\r\n"); + + return CHIP_NO_ERROR; +} + +static CHIP_ERROR HandleAddBridgeCommand(int argc, char ** argv) +{ + if (argc != 5) + { + fprintf(stderr, + "Invalid arguments. Usage: app add-bridge \n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + // Check if there is already an active command + if (commands::CommandRegistry::Instance().IsCommandActive()) + { + fprintf(stderr, "Another command is currently active. Please wait until it completes.\n"); + return CHIP_ERROR_BUSY; + } + + // Parse arguments + chip::NodeId nodeId = static_cast(strtoull(argv[1], nullptr, 10)); + uint32_t setupPINCode = static_cast(strtoul(argv[2], nullptr, 10)); + const char * remoteAddr = argv[3]; + uint16_t remotePort = static_cast(strtoul(argv[4], nullptr, 10)); + + auto command = std::make_unique(nodeId, setupPINCode, remoteAddr, remotePort); + + CHIP_ERROR result = command->RunCommand(); + if (result == CHIP_NO_ERROR) + { + commands::CommandRegistry::Instance().SetActiveCommand(std::move(command)); + } + + return result; +} + +static CHIP_ERROR HandleRemoveBridgeCommand(int argc, char ** argv) +{ + if (argc != 1) + { + fprintf(stderr, "Invalid arguments. Usage: app remove-bridge\n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + // Check if there is already an active command + if (commands::CommandRegistry::Instance().IsCommandActive()) + { + fprintf(stderr, "Another command is currently active. Please wait until it completes.\n"); + return CHIP_ERROR_BUSY; + } + + auto command = std::make_unique(); + + CHIP_ERROR result = command->RunCommand(); + if (result == CHIP_NO_ERROR) + { + commands::CommandRegistry::Instance().SetActiveCommand(std::move(command)); + } + + return result; +} + +static CHIP_ERROR AppPlatformHandler(int argc, char ** argv) +{ + CHIP_ERROR error = CHIP_NO_ERROR; + + if (argc == 0 || strcmp(argv[0], "help") == 0) + { + return PrintAllCommands(); + } + else if (argc == 0 || strcmp(argv[0], "?") == 0) + { + return PrintAllCommands(); + } + else if (strcmp(argv[0], "add-bridge") == 0) + { + return HandleAddBridgeCommand(argc, argv); + } + else if (strcmp(argv[0], "remove-bridge") == 0) + { + return HandleRemoveBridgeCommand(argc, argv); + } + else + { + return CHIP_ERROR_INVALID_ARGUMENT; + } + return error; +} + +void RegisterCommands() +{ + + static const shell_command_t sDeviceComand = { &AppPlatformHandler, "app", "App commands. Usage: app [command_name]" }; + + // Register the root `device` command with the top-level shell. + Engine::Root().RegisterCommands(&sDeviceComand, 1); + return; +} + +} // namespace Shell +} // namespace chip diff --git a/examples/fabric-sync/shell/ShellCommands.h b/examples/fabric-sync/shell/ShellCommands.h new file mode 100644 index 00000000000000..ab957bc8cd92d7 --- /dev/null +++ b/examples/fabric-sync/shell/ShellCommands.h @@ -0,0 +1,27 @@ +/* + * + * 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 + +namespace chip { +namespace Shell { + +void RegisterCommands(); + +} // namespace Shell +} // namespace chip From 12484a95500a8dfca92e4864e53b04404035f65a Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Mon, 4 Nov 2024 23:48:29 -0800 Subject: [PATCH 059/121] Put fabric sync logic into namespace admin (#36361) --- examples/fabric-admin/commands/common/CHIPCommand.cpp | 2 +- examples/fabric-admin/commands/fabric-sync/Commands.h | 10 +++++----- .../commands/fabric-sync/FabricSyncCommand.cpp | 4 ++++ .../commands/fabric-sync/FabricSyncCommand.h | 4 ++++ .../commands/interactive/InteractiveCommands.cpp | 6 +++--- .../fabric-admin/commands/pairing/PairingCommand.cpp | 4 ++-- .../fabric-admin/device_manager/BridgeSubscription.cpp | 6 +++++- .../fabric-admin/device_manager/BridgeSubscription.h | 4 ++++ .../device_manager/CommissionerControl.cpp | 9 ++++++++- .../fabric-admin/device_manager/CommissionerControl.h | 4 ++++ examples/fabric-admin/device_manager/DeviceManager.cpp | 4 ++++ examples/fabric-admin/device_manager/DeviceManager.h | 4 ++++ .../fabric-admin/device_manager/DeviceSubscription.cpp | 4 ++++ .../fabric-admin/device_manager/DeviceSubscription.h | 5 ++++- .../device_manager/DeviceSubscriptionManager.cpp | 4 ++++ .../device_manager/DeviceSubscriptionManager.h | 4 ++++ .../device_manager/DeviceSynchronization.cpp | 4 ++++ .../device_manager/DeviceSynchronization.h | 5 ++++- .../fabric-admin/device_manager/FabricSyncGetter.cpp | 4 ++++ .../fabric-admin/device_manager/FabricSyncGetter.h | 4 ++++ .../fabric-admin/device_manager/PairingManager.cpp | 4 ++++ examples/fabric-admin/device_manager/PairingManager.h | 4 ++++ .../fabric-admin/device_manager/UniqueIdGetter.cpp | 4 ++++ examples/fabric-admin/device_manager/UniqueIdGetter.h | 4 ++++ examples/fabric-admin/main.cpp | 2 +- examples/fabric-admin/rpc/RpcClient.cpp | 4 ++++ examples/fabric-admin/rpc/RpcClient.h | 4 ++++ examples/fabric-admin/rpc/RpcServer.cpp | 4 ++++ examples/fabric-admin/rpc/RpcServer.h | 4 ++++ 29 files changed, 113 insertions(+), 16 deletions(-) diff --git a/examples/fabric-admin/commands/common/CHIPCommand.cpp b/examples/fabric-admin/commands/common/CHIPCommand.cpp index c23ea82f202cf7..e7f4071d122b31 100644 --- a/examples/fabric-admin/commands/common/CHIPCommand.cpp +++ b/examples/fabric-admin/commands/common/CHIPCommand.cpp @@ -182,7 +182,7 @@ CHIP_ERROR CHIPCommand::MaybeSetUpStack() mCredIssuerCmds->SetCredentialIssuerOption(CredentialIssuerCommands::CredentialIssuerOptions::kAllowTestCdSigningKey, allowTestCdSigningKey); - ReturnLogErrorOnFailure(PairingManager::Instance().Init(&CurrentCommissioner(), mCredIssuerCmds)); + ReturnLogErrorOnFailure(admin::PairingManager::Instance().Init(&CurrentCommissioner(), mCredIssuerCmds)); return CHIP_NO_ERROR; } diff --git a/examples/fabric-admin/commands/fabric-sync/Commands.h b/examples/fabric-admin/commands/fabric-sync/Commands.h index 47f7207922beae..0f2f3f64c35d5c 100644 --- a/examples/fabric-admin/commands/fabric-sync/Commands.h +++ b/examples/fabric-admin/commands/fabric-sync/Commands.h @@ -26,11 +26,11 @@ void registerCommandsFabricSync(Commands & commands, CredentialIssuerCommands * const char * clusterName = "FabricSync"; commands_list clusterCommands = { - make_unique(credsIssuerConfig), - make_unique(credsIssuerConfig), - make_unique(credsIssuerConfig), - make_unique(credsIssuerConfig), - make_unique(credsIssuerConfig), + make_unique(credsIssuerConfig), + make_unique(credsIssuerConfig), + make_unique(credsIssuerConfig), + make_unique(credsIssuerConfig), + make_unique(credsIssuerConfig), }; commands.RegisterCommandSet(clusterName, clusterCommands, "Commands for fabric synchronization."); diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp index f10db13e939acd..6d42b04722fec6 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp @@ -30,6 +30,8 @@ using namespace ::chip; +namespace admin { + void FabricSyncAddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) { if (mBridgeNodeId != deviceId) @@ -305,3 +307,5 @@ CHIP_ERROR FabricSyncDeviceCommand::RunCommand(EndpointId remoteId) return CHIP_NO_ERROR; } + +} // namespace admin diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h index 8d14529155cab4..809cc7d322b364 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h @@ -21,6 +21,8 @@ #include #include +namespace admin { + // Constants constexpr uint32_t kCommissionPrepareTimeMs = 500; @@ -136,3 +138,5 @@ class FabricSyncDeviceCommand : public CHIPCommand, public CommissioningWindowDe CHIP_ERROR RunCommand(chip::EndpointId remoteId); }; + +} // namespace admin diff --git a/examples/fabric-admin/commands/interactive/InteractiveCommands.cpp b/examples/fabric-admin/commands/interactive/InteractiveCommands.cpp index 0209a783739b74..bd352257266828 100644 --- a/examples/fabric-admin/commands/interactive/InteractiveCommands.cpp +++ b/examples/fabric-admin/commands/interactive/InteractiveCommands.cpp @@ -117,7 +117,7 @@ void ENFORCE_FORMAT(3, 0) LoggingCallback(const char * module, uint8_t category, #if defined(PW_RPC_ENABLED) void AttemptRpcClientConnect(System::Layer * systemLayer, void * appState) { - if (StartRpcClient() == CHIP_NO_ERROR) + if (admin::StartRpcClient() == CHIP_NO_ERROR) { // print to console fprintf(stderr, "Connected to Fabric-Bridge\n"); @@ -199,8 +199,8 @@ CHIP_ERROR InteractiveStartCommand::RunCommand() } #if defined(PW_RPC_ENABLED) - SetRpcRemoteServerPort(mFabricBridgeServerPort.Value()); - InitRpcServer(mLocalServerPort.Value()); + admin::SetRpcRemoteServerPort(mFabricBridgeServerPort.Value()); + admin::InitRpcServer(mLocalServerPort.Value()); ChipLogProgress(NotSpecified, "PW_RPC initialized."); DeviceLayer::PlatformMgr().ScheduleWork(ExecuteDeferredConnect, 0); #endif diff --git a/examples/fabric-admin/commands/pairing/PairingCommand.cpp b/examples/fabric-admin/commands/pairing/PairingCommand.cpp index 37578472b70fbd..031b57ef5444f7 100644 --- a/examples/fabric-admin/commands/pairing/PairingCommand.cpp +++ b/examples/fabric-admin/commands/pairing/PairingCommand.cpp @@ -405,7 +405,7 @@ void PairingCommand::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err) fprintf(stderr, "New device with Node ID: 0x%lx has been successfully added.\n", nodeId); // CurrentCommissioner() has a lifetime that is the entire life of the application itself // so it is safe to provide to StartDeviceSynchronization. - DeviceSynchronizer::Instance().StartDeviceSynchronization(&CurrentCommissioner(), mNodeId, mDeviceIsICD); + admin::DeviceSynchronizer::Instance().StartDeviceSynchronization(&CurrentCommissioner(), mNodeId, mDeviceIsICD); } else { @@ -542,7 +542,7 @@ void PairingCommand::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E #if defined(PW_RPC_ENABLED) app::InteractionModelEngine::GetInstance()->ShutdownSubscriptions(command->CurrentCommissioner().GetFabricIndex(), nodeId); ScopedNodeId scopedNodeId(nodeId, command->CurrentCommissioner().GetFabricIndex()); - RemoveSynchronizedDevice(scopedNodeId); + admin::RemoveSynchronizedDevice(scopedNodeId); #endif } else diff --git a/examples/fabric-admin/device_manager/BridgeSubscription.cpp b/examples/fabric-admin/device_manager/BridgeSubscription.cpp index 2efcadaaa63ee5..e7052d7df08a96 100644 --- a/examples/fabric-admin/device_manager/BridgeSubscription.cpp +++ b/examples/fabric-admin/device_manager/BridgeSubscription.cpp @@ -17,12 +17,14 @@ */ #include "BridgeSubscription.h" -#include +#include "DeviceManager.h" using namespace ::chip; using namespace ::chip::app; using chip::app::ReadClient; +namespace admin { + namespace { constexpr uint16_t kSubscribeMinInterval = 0; @@ -157,3 +159,5 @@ void BridgeSubscription::OnDeviceConnectionFailure(const ScopedNodeId & peerId, ChipLogError(NotSpecified, "BridgeSubscription failed to connect to " ChipLogFormatX64, ChipLogValueX64(peerId.GetNodeId())); OnDone(nullptr); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/BridgeSubscription.h b/examples/fabric-admin/device_manager/BridgeSubscription.h index bd2a70279af065..e5f8c73fc14257 100644 --- a/examples/fabric-admin/device_manager/BridgeSubscription.h +++ b/examples/fabric-admin/device_manager/BridgeSubscription.h @@ -24,6 +24,8 @@ #include #include +namespace admin { + /** * @brief Class used to subscribe to attributes and events from the remote bridged device. * @@ -75,3 +77,5 @@ class BridgeSubscription : public chip::app::ReadClient::Callback chip::EndpointId mEndpointId; bool subscriptionStarted = false; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/CommissionerControl.cpp b/examples/fabric-admin/device_manager/CommissionerControl.cpp index b919ceb0683192..80c9437450cc80 100644 --- a/examples/fabric-admin/device_manager/CommissionerControl.cpp +++ b/examples/fabric-admin/device_manager/CommissionerControl.cpp @@ -1,8 +1,10 @@ #include "CommissionerControl.h" -#include +#include "DeviceManager.h" using namespace ::chip; +namespace admin { + void CommissionerControl::Init(Controller::DeviceCommissioner & commissioner, NodeId nodeId, EndpointId endpointId) { // Ensure that mCommissioner is not already initialized @@ -102,6 +104,9 @@ void CommissionerControl::OnDone(app::CommandSender * client) CHIP_ERROR CommissionerControl::SendCommandForType(CommandType commandType, DeviceProxy * device) { + ChipLogProgress(AppServer, "Sending command with Endpoint ID: %d, Command Type: %d", mEndpointId, + static_cast(commandType)); + switch (commandType) { case CommandType::kRequestCommissioningApproval: @@ -139,3 +144,5 @@ void CommissionerControl::OnDeviceConnectionFailureFn(void * context, const Scop VerifyOrReturn(self != nullptr, ChipLogError(NotSpecified, "OnDeviceConnectedFn: context is null")); self->OnDone(nullptr); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/CommissionerControl.h b/examples/fabric-admin/device_manager/CommissionerControl.h index 1fad323e125c2a..392367d6c04367 100644 --- a/examples/fabric-admin/device_manager/CommissionerControl.h +++ b/examples/fabric-admin/device_manager/CommissionerControl.h @@ -21,6 +21,8 @@ #include #include +namespace admin { + /** * @class CommissionerControl * @brief This class handles sending CHIP commands related to commissioning, including sending @@ -123,3 +125,5 @@ class CommissionerControl : public chip::app::CommandSender::Callback chip::app::Clusters::CommissionerControl::Commands::RequestCommissioningApproval::Type mRequestCommissioningApproval; chip::app::Clusters::CommissionerControl::Commands::CommissionNode::Type mCommissionNode; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index e52027c8f533f1..fafae0eb00115d 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -27,6 +27,8 @@ using namespace chip; +namespace admin { + namespace { constexpr EndpointId kAggregatorEndpointId = 1; @@ -465,3 +467,5 @@ void DeviceManager::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) RemoveSyncedDevice(deviceId); ChipLogProgress(NotSpecified, "Synced device with NodeId:" ChipLogFormatX64 " has been removed.", ChipLogValueX64(deviceId)); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceManager.h b/examples/fabric-admin/device_manager/DeviceManager.h index 6adc8f243e6b1a..9d2a37ab5ab721 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.h +++ b/examples/fabric-admin/device_manager/DeviceManager.h @@ -26,6 +26,8 @@ #include #include +namespace admin { + constexpr uint32_t kDefaultSetupPinCode = 20202021; constexpr uint16_t kDefaultLocalBridgePort = 5540; constexpr uint16_t kResponseTimeoutSeconds = 30; @@ -226,3 +228,5 @@ inline DeviceManager & DeviceMgr() } return DeviceManager::sInstance; } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSubscription.cpp b/examples/fabric-admin/device_manager/DeviceSubscription.cpp index 434d349e8c5113..996656a0de2bdc 100644 --- a/examples/fabric-admin/device_manager/DeviceSubscription.cpp +++ b/examples/fabric-admin/device_manager/DeviceSubscription.cpp @@ -33,6 +33,8 @@ using namespace ::chip; using namespace ::chip::app; using chip::app::ReadClient; +namespace admin { + namespace { void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) @@ -281,3 +283,5 @@ void DeviceSubscription::StopSubscription() MoveToState(State::AwaitingDestruction); mOnDoneCallback(mScopedNodeId); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSubscription.h b/examples/fabric-admin/device_manager/DeviceSubscription.h index 8db31d6e9037fc..808da10c321851 100644 --- a/examples/fabric-admin/device_manager/DeviceSubscription.h +++ b/examples/fabric-admin/device_manager/DeviceSubscription.h @@ -20,7 +20,6 @@ #include #include #include - #include #if defined(PW_RPC_ENABLED) @@ -28,6 +27,8 @@ #include "fabric_bridge_service/fabric_bridge_service.rpc.pb.h" #endif +namespace admin { + class DeviceSubscriptionManager; /// Attribute subscription to attributes that are important to keep track and send to fabric-bridge @@ -95,3 +96,5 @@ class DeviceSubscription : public chip::app::ReadClient::Callback bool mChangeDetected = false; State mState = State::Idle; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSubscriptionManager.cpp b/examples/fabric-admin/device_manager/DeviceSubscriptionManager.cpp index 0410c162a8e43a..ca79cd0fd04887 100644 --- a/examples/fabric-admin/device_manager/DeviceSubscriptionManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceSubscriptionManager.cpp @@ -32,6 +32,8 @@ using namespace ::chip; using namespace ::chip::app; +namespace admin { + DeviceSubscriptionManager & DeviceSubscriptionManager::Instance() { static DeviceSubscriptionManager instance; @@ -78,3 +80,5 @@ void DeviceSubscriptionManager::DeviceSubscriptionTerminated(ScopedNodeId scoped VerifyOrDie(it != mDeviceSubscriptionMap.end()); mDeviceSubscriptionMap.erase(scopedNodeId); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSubscriptionManager.h b/examples/fabric-admin/device_manager/DeviceSubscriptionManager.h index 1b5c45fd05ae16..eb32d3f439276d 100644 --- a/examples/fabric-admin/device_manager/DeviceSubscriptionManager.h +++ b/examples/fabric-admin/device_manager/DeviceSubscriptionManager.h @@ -25,6 +25,8 @@ #include +namespace admin { + class DeviceSubscriptionManager { public: @@ -52,3 +54,5 @@ class DeviceSubscriptionManager std::unordered_map, ScopedNodeIdHasher> mDeviceSubscriptionMap; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSynchronization.cpp b/examples/fabric-admin/device_manager/DeviceSynchronization.cpp index 1e8728ee59b567..a88df405617707 100644 --- a/examples/fabric-admin/device_manager/DeviceSynchronization.cpp +++ b/examples/fabric-admin/device_manager/DeviceSynchronization.cpp @@ -35,6 +35,8 @@ using namespace ::chip; using namespace ::chip::app; using chip::app::ReadClient; +namespace admin { + namespace { void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) @@ -324,3 +326,5 @@ const char * DeviceSynchronizer::GetStateStr() const } return "N/A"; } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSynchronization.h b/examples/fabric-admin/device_manager/DeviceSynchronization.h index 28880c6faec7a1..8f089ef6534d5f 100644 --- a/examples/fabric-admin/device_manager/DeviceSynchronization.h +++ b/examples/fabric-admin/device_manager/DeviceSynchronization.h @@ -22,7 +22,6 @@ #include #include #include - #include #if defined(PW_RPC_ENABLED) @@ -30,6 +29,8 @@ #include "fabric_bridge_service/fabric_bridge_service.rpc.pb.h" #endif +namespace admin { + /// Ensures that device data is synchronized to the remote fabric bridge. /// /// Includes a state machine that: @@ -100,3 +101,5 @@ class DeviceSynchronizer : public chip::app::ReadClient::Callback #endif UniqueIdGetter mUniqueIdGetter; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/FabricSyncGetter.cpp b/examples/fabric-admin/device_manager/FabricSyncGetter.cpp index 5201048c3faea6..7e5118090716c0 100644 --- a/examples/fabric-admin/device_manager/FabricSyncGetter.cpp +++ b/examples/fabric-admin/device_manager/FabricSyncGetter.cpp @@ -22,6 +22,8 @@ using namespace ::chip; using namespace ::chip::app; using chip::app::ReadClient; +namespace admin { + namespace { void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) @@ -119,3 +121,5 @@ void FabricSyncGetter::OnDeviceConnectionFailure(const ScopedNodeId & peerId, CH OnDone(nullptr); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/FabricSyncGetter.h b/examples/fabric-admin/device_manager/FabricSyncGetter.h index d6d3a5bce8c9f5..bed3c2fbb54385 100644 --- a/examples/fabric-admin/device_manager/FabricSyncGetter.h +++ b/examples/fabric-admin/device_manager/FabricSyncGetter.h @@ -24,6 +24,8 @@ #include #include +namespace admin { + /** * @brief Class used to get FabricSynchronization from SupportedDeviceCategories attribute of Commissioner Control Cluster. * @@ -73,3 +75,5 @@ class FabricSyncGetter : public chip::app::ReadClient::Callback chip::Callback::Callback mOnDeviceConnectedCallback; chip::Callback::Callback mOnDeviceConnectionFailureCallback; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/PairingManager.cpp b/examples/fabric-admin/device_manager/PairingManager.cpp index 41b4c8744e16b3..64e4fb4b56c64b 100644 --- a/examples/fabric-admin/device_manager/PairingManager.cpp +++ b/examples/fabric-admin/device_manager/PairingManager.cpp @@ -35,6 +35,8 @@ using namespace ::chip; using namespace ::chip::Controller; +namespace admin { + namespace { CHIP_ERROR GetPayload(const char * setUpCode, SetupPayload & payload) @@ -655,3 +657,5 @@ CHIP_ERROR PairingManager::UnpairDevice(NodeId nodeId) } }); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/PairingManager.h b/examples/fabric-admin/device_manager/PairingManager.h index 50e64f9f0ca67f..2318acd5f97297 100644 --- a/examples/fabric-admin/device_manager/PairingManager.h +++ b/examples/fabric-admin/device_manager/PairingManager.h @@ -25,6 +25,8 @@ #include #include +namespace admin { + // Constants constexpr uint16_t kMaxManualCodeLength = 22; @@ -214,3 +216,5 @@ class PairingManager : public chip::Controller::DevicePairingDelegate, chip::Platform::UniquePtr mCurrentFabricRemover; chip::Callback::Callback mCurrentFabricRemoveCallback; }; + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/UniqueIdGetter.cpp b/examples/fabric-admin/device_manager/UniqueIdGetter.cpp index 3a6d6af69d032b..cc3567deda6bd2 100644 --- a/examples/fabric-admin/device_manager/UniqueIdGetter.cpp +++ b/examples/fabric-admin/device_manager/UniqueIdGetter.cpp @@ -22,6 +22,8 @@ using namespace ::chip; using namespace ::chip::app; using chip::app::ReadClient; +namespace admin { + namespace { void OnDeviceConnectedWrapper(void * context, Messaging::ExchangeManager & exchangeMgr, const SessionHandle & sessionHandle) @@ -139,3 +141,5 @@ void UniqueIdGetter::OnDeviceConnectionFailure(const ScopedNodeId & peerId, CHIP OnDone(nullptr); } + +} // namespace admin diff --git a/examples/fabric-admin/device_manager/UniqueIdGetter.h b/examples/fabric-admin/device_manager/UniqueIdGetter.h index 86d5d82f656bd5..eba4451599c3ee 100644 --- a/examples/fabric-admin/device_manager/UniqueIdGetter.h +++ b/examples/fabric-admin/device_manager/UniqueIdGetter.h @@ -24,6 +24,8 @@ #include #include +namespace admin { + /** * @brief Class used to get UniqueID from Bridged Device Basic Information Cluster * @@ -73,3 +75,5 @@ class UniqueIdGetter : public chip::app::ReadClient::Callback char mUniqueId[33]; chip::EndpointId mEndpointId; }; + +} // namespace admin diff --git a/examples/fabric-admin/main.cpp b/examples/fabric-admin/main.cpp index 5768abf496fefc..15471eed0530f6 100644 --- a/examples/fabric-admin/main.cpp +++ b/examples/fabric-admin/main.cpp @@ -32,7 +32,7 @@ using namespace chip; void ApplicationInit() { - DeviceMgr().Init(); + admin::DeviceMgr().Init(); } // ================================================================================ diff --git a/examples/fabric-admin/rpc/RpcClient.cpp b/examples/fabric-admin/rpc/RpcClient.cpp index 9964dc6767b67e..a3bc459235a0cb 100644 --- a/examples/fabric-admin/rpc/RpcClient.cpp +++ b/examples/fabric-admin/rpc/RpcClient.cpp @@ -28,6 +28,8 @@ using namespace chip; +namespace admin { + namespace { // Constants @@ -227,3 +229,5 @@ CHIP_ERROR DeviceReachableChanged(const chip_rpc_ReachabilityChanged & data) return WaitForResponse(call); } + +} // namespace admin diff --git a/examples/fabric-admin/rpc/RpcClient.h b/examples/fabric-admin/rpc/RpcClient.h index a4cefe8bd8e076..642e2637710ad4 100644 --- a/examples/fabric-admin/rpc/RpcClient.h +++ b/examples/fabric-admin/rpc/RpcClient.h @@ -23,6 +23,8 @@ #include "fabric_bridge_service/fabric_bridge_service.rpc.pb.h" +namespace admin { + /** * @brief Sets the RPC server port to which the RPC client will connect. * @@ -99,3 +101,5 @@ CHIP_ERROR AdminCommissioningAttributeChanged(const chip_rpc_AdministratorCommis * - CHIP_ERROR_INTERNAL: An internal error occurred while activating the RPC call. */ CHIP_ERROR DeviceReachableChanged(const chip_rpc_ReachabilityChanged & data); + +} // namespace admin diff --git a/examples/fabric-admin/rpc/RpcServer.cpp b/examples/fabric-admin/rpc/RpcServer.cpp index e10bb64cdc050f..1b084ef2157ce7 100644 --- a/examples/fabric-admin/rpc/RpcServer.cpp +++ b/examples/fabric-admin/rpc/RpcServer.cpp @@ -38,6 +38,8 @@ using namespace ::chip; +namespace admin { + namespace { #if defined(PW_RPC_FABRIC_ADMIN_SERVICE) && PW_RPC_FABRIC_ADMIN_SERVICE @@ -254,3 +256,5 @@ void InitRpcServer(uint16_t rpcServerPort) std::thread rpc_service(RunRpcService); rpc_service.detach(); } + +} // namespace admin diff --git a/examples/fabric-admin/rpc/RpcServer.h b/examples/fabric-admin/rpc/RpcServer.h index d283c0db5a0248..c8fcd33324588e 100644 --- a/examples/fabric-admin/rpc/RpcServer.h +++ b/examples/fabric-admin/rpc/RpcServer.h @@ -18,4 +18,8 @@ #pragma once +namespace admin { + void InitRpcServer(uint16_t rpcServerPort); + +} // namespace admin From 123570cfc8fa71da7fce3008a6cd4347251f4e8e Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Mon, 4 Nov 2024 23:49:15 -0800 Subject: [PATCH 060/121] [Fabric-Bridge] Put fabric sync logic into namespace 'bridge' (#36362) --- .../BridgedAdministratorCommissioning.h | 4 +++ .../include/BridgedDevice.h | 4 +++ .../BridgedDeviceBasicInformationImpl.h | 4 +++ .../include/BridgedDeviceManager.h | 4 +++ .../src/BridgedAdministratorCommissioning.cpp | 4 +++ .../src/BridgedDevice.cpp | 4 +++ .../src/BridgedDeviceBasicInformationImpl.cpp | 4 +++ .../src/BridgedDeviceManager.cpp | 4 +++ .../linux/CommissionerControlDelegate.cpp | 18 ++++++++----- .../fabric-bridge-app/linux/RpcClient.cpp | 4 +++ .../fabric-bridge-app/linux/RpcServer.cpp | 4 +++ .../include/CommissionerControlDelegate.h | 4 +++ .../linux/include/RpcClient.h | 4 +++ .../linux/include/RpcServer.h | 4 +++ examples/fabric-bridge-app/linux/main.cpp | 26 +++++++++++-------- 15 files changed, 78 insertions(+), 18 deletions(-) diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedAdministratorCommissioning.h b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedAdministratorCommissioning.h index 06fd9026d44225..7b5711d39557e9 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedAdministratorCommissioning.h +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedAdministratorCommissioning.h @@ -20,6 +20,8 @@ #include #include +namespace bridge { + /** * @brief CADMIN cluster implementation for handling attribute interactions of bridged device endpoints. * @@ -56,3 +58,5 @@ class BridgedAdministratorCommissioning : public chip::app::AttributeAccessInter // to reflect this change. chip::app::AttributeAccessInterface * mOriginalAttributeInterface = nullptr; }; + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDevice.h b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDevice.h index d2c5a64b9ef4b7..ed5c9710624225 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDevice.h +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDevice.h @@ -23,6 +23,8 @@ #include +namespace bridge { + class BridgedDevice { public: @@ -90,3 +92,5 @@ class BridgedDevice BridgedAttributes mAttributes; AdminCommissioningAttributes mAdminCommissioningAttributes; }; + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceBasicInformationImpl.h b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceBasicInformationImpl.h index 23403438ab2be8..f57f7d0362ae73 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceBasicInformationImpl.h +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceBasicInformationImpl.h @@ -18,6 +18,8 @@ #include #include +namespace bridge { + class BridgedDeviceBasicInformationImpl : public chip::app::AttributeAccessInterface { public: @@ -30,3 +32,5 @@ class BridgedDeviceBasicInformationImpl : public chip::app::AttributeAccessInter CHIP_ERROR Read(const chip::app::ConcreteReadAttributePath & path, chip::app::AttributeValueEncoder & encoder) override; CHIP_ERROR Write(const chip::app::ConcreteDataAttributePath & path, chip::app::AttributeValueDecoder & decoder) override; }; + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceManager.h b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceManager.h index 127898fc5b2fab..1a6a57948f340a 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceManager.h +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceManager.h @@ -24,6 +24,8 @@ #include +namespace bridge { + class BridgedDeviceManager { public: @@ -134,3 +136,5 @@ inline BridgedDeviceManager & BridgeDeviceMgr() { return BridgedDeviceManager::sInstance; } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp index a0d87cbb3b81ef..3299df75a9039e 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp @@ -26,6 +26,8 @@ using namespace chip::app; using namespace chip::app::Clusters; using namespace chip::app::Clusters::AdministratorCommissioning; +namespace bridge { + CHIP_ERROR BridgedAdministratorCommissioning::Init() { // We expect initialization after emberAfInit(). This allows us to unregister the existing @@ -79,3 +81,5 @@ CHIP_ERROR BridgedAdministratorCommissioning::Read(const ConcreteReadAttributePa return CHIP_NO_ERROR; } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDevice.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDevice.cpp index f462d1cce6efd5..bd88c89145930e 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDevice.cpp +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDevice.cpp @@ -27,6 +27,8 @@ using namespace chip; using namespace chip::app::Clusters::Actions; +namespace bridge { + BridgedDevice::BridgedDevice(ScopedNodeId scopedNodeId) { mReachable = false; @@ -116,3 +118,5 @@ void BridgedDevice::SetAdminCommissioningAttributes(const AdminCommissioningAttr } }); } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceBasicInformationImpl.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceBasicInformationImpl.cpp index 7fa48a4a158ddd..d021671c8bf1bd 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceBasicInformationImpl.cpp +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceBasicInformationImpl.cpp @@ -29,6 +29,8 @@ using namespace ::chip; using namespace ::chip::app; using namespace ::chip::app::Clusters; +namespace bridge { + CHIP_ERROR BridgedDeviceBasicInformationImpl::Read(const ConcreteReadAttributePath & path, AttributeValueEncoder & encoder) { // Registration is done for the bridged device basic information only @@ -105,3 +107,5 @@ CHIP_ERROR BridgedDeviceBasicInformationImpl::Write(const ConcreteDataAttributeP return CHIP_ERROR_INVALID_ARGUMENT; } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceManager.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceManager.cpp index 0265f912027ca0..babe2db9172259 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceManager.cpp +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceManager.cpp @@ -45,6 +45,8 @@ using namespace chip::Transport; using namespace chip::DeviceLayer; using namespace chip::app::Clusters; +namespace bridge { + namespace { constexpr uint8_t kMaxRetries = 10; @@ -343,3 +345,5 @@ std::optional BridgedDeviceManager::RemoveDeviceByScopedNodeId(chip::S } return std::nullopt; } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/CommissionerControlDelegate.cpp b/examples/fabric-bridge-app/linux/CommissionerControlDelegate.cpp index 8a5c5af3db0566..aa12a4274ca0f8 100644 --- a/examples/fabric-bridge-app/linux/CommissionerControlDelegate.cpp +++ b/examples/fabric-bridge-app/linux/CommissionerControlDelegate.cpp @@ -186,13 +186,13 @@ CHIP_ERROR CommissionerControlDelegate::HandleCommissionNode(const Commissioning VerifyOrReturnError(mNextStep == Step::kStartCommissionNode, CHIP_ERROR_INCORRECT_STATE); #if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE - err = CommissionNode(Controller::CommissioningWindowPasscodeParams() - .SetSetupPIN(kSetupPinCode) - .SetTimeout(params.commissioningTimeout) - .SetDiscriminator(params.discriminator) - .SetIteration(params.iterations) - .SetSalt(params.salt), - mVendorId, mProductId); + err = bridge::CommissionNode(Controller::CommissioningWindowPasscodeParams() + .SetSetupPIN(kSetupPinCode) + .SetTimeout(params.commissioningTimeout) + .SetDiscriminator(params.discriminator) + .SetIteration(params.iterations) + .SetSalt(params.salt), + mVendorId, mProductId); #else ChipLogProgress(NotSpecified, "Failed to reverse commission bridge: PW_RPC_FABRIC_BRIDGE_SERVICE not defined"); err = CHIP_ERROR_NOT_IMPLEMENTED; @@ -209,6 +209,8 @@ CHIP_ERROR CommissionerControlDelegate::HandleCommissionNode(const Commissioning } // namespace app } // namespace chip +namespace bridge { + CHIP_ERROR CommissionerControlInit() { CHIP_ERROR err; @@ -262,3 +264,5 @@ CHIP_ERROR CommissionerControlShutdown() return CHIP_NO_ERROR; } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/RpcClient.cpp b/examples/fabric-bridge-app/linux/RpcClient.cpp index 732fdf8aa1bf80..ef41ae261dab9b 100644 --- a/examples/fabric-bridge-app/linux/RpcClient.cpp +++ b/examples/fabric-bridge-app/linux/RpcClient.cpp @@ -35,6 +35,8 @@ using namespace chip; +namespace bridge { + namespace { // Constants @@ -205,3 +207,5 @@ CHIP_ERROR KeepActive(chip::ScopedNodeId scopedNodeId, uint32_t stayActiveDurati return WaitForResponse(call); } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/RpcServer.cpp b/examples/fabric-bridge-app/linux/RpcServer.cpp index 5fea43c6ef2953..a34692b177cc56 100644 --- a/examples/fabric-bridge-app/linux/RpcServer.cpp +++ b/examples/fabric-bridge-app/linux/RpcServer.cpp @@ -37,6 +37,8 @@ using namespace chip; using namespace chip::app; using namespace chip::app::Clusters; +namespace bridge { + namespace { #if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE @@ -256,3 +258,5 @@ void InitRpcServer(uint16_t rpcServerPort) std::thread rpc_service(RunRpcService); rpc_service.detach(); } + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/include/CommissionerControlDelegate.h b/examples/fabric-bridge-app/linux/include/CommissionerControlDelegate.h index fceb80c2d802f5..2f9e15f508cccb 100644 --- a/examples/fabric-bridge-app/linux/include/CommissionerControlDelegate.h +++ b/examples/fabric-bridge-app/linux/include/CommissionerControlDelegate.h @@ -89,5 +89,9 @@ class CommissionerControlDelegate : public Delegate } // namespace app } // namespace chip +namespace bridge { + CHIP_ERROR CommissionerControlInit(); CHIP_ERROR CommissionerControlShutdown(); + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/include/RpcClient.h b/examples/fabric-bridge-app/linux/include/RpcClient.h index 1ede84ff446ecd..9a06686f068455 100644 --- a/examples/fabric-bridge-app/linux/include/RpcClient.h +++ b/examples/fabric-bridge-app/linux/include/RpcClient.h @@ -22,6 +22,8 @@ #include #include +namespace bridge { + /** * Sets the RPC server port to which the RPC client will connect. * @@ -70,3 +72,5 @@ CHIP_ERROR CommissionNode(chip::Controller::CommissioningWindowPasscodeParams params, chip::VendorId vendorId, uint16_t productId); CHIP_ERROR KeepActive(chip::ScopedNodeId scopedNodeId, uint32_t stayActiveDurationMs, uint32_t timeoutMs); + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/include/RpcServer.h b/examples/fabric-bridge-app/linux/include/RpcServer.h index d283c0db5a0248..ab0626c866d1a8 100644 --- a/examples/fabric-bridge-app/linux/include/RpcServer.h +++ b/examples/fabric-bridge-app/linux/include/RpcServer.h @@ -18,4 +18,8 @@ #pragma once +namespace bridge { + void InitRpcServer(uint16_t rpcServerPort); + +} // namespace bridge diff --git a/examples/fabric-bridge-app/linux/main.cpp b/examples/fabric-bridge-app/linux/main.cpp index 574053424f7895..cca3fbc8d0d19c 100644 --- a/examples/fabric-bridge-app/linux/main.cpp +++ b/examples/fabric-bridge-app/linux/main.cpp @@ -98,7 +98,7 @@ ArgParser::OptionSet sProgramCustomOptions = { HandleCustomOption, sProgramCusto #if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE void AttemptRpcClientConnect(System::Layer * systemLayer, void * appState) { - if (StartRpcClient() == CHIP_NO_ERROR) + if (bridge::StartRpcClient() == CHIP_NO_ERROR) { ChipLogProgress(NotSpecified, "Connected to Fabric-Admin"); } @@ -110,6 +110,10 @@ void AttemptRpcClientConnect(System::Layer * systemLayer, void * appState) } #endif // defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE +} // namespace + +namespace bridge { + class AdministratorCommissioningCommandHandler : public CommandHandlerInterface { public: @@ -241,27 +245,27 @@ BridgedDeviceBasicInformationImpl gBridgedDeviceBasicInformationAttributes; AdministratorCommissioningCommandHandler gAdministratorCommissioningCommandHandler; BridgedDeviceInformationCommandHandler gBridgedDeviceInformationCommandHandler; -} // namespace +} // namespace bridge void ApplicationInit() { ChipLogDetail(NotSpecified, "Fabric-Bridge: ApplicationInit()"); MatterEcosystemInformationPluginServerInitCallback(); - CommandHandlerInterfaceRegistry::Instance().RegisterCommandHandler(&gAdministratorCommissioningCommandHandler); - CommandHandlerInterfaceRegistry::Instance().RegisterCommandHandler(&gBridgedDeviceInformationCommandHandler); - AttributeAccessInterfaceRegistry::Instance().Register(&gBridgedDeviceBasicInformationAttributes); + CommandHandlerInterfaceRegistry::Instance().RegisterCommandHandler(&bridge::gAdministratorCommissioningCommandHandler); + CommandHandlerInterfaceRegistry::Instance().RegisterCommandHandler(&bridge::gBridgedDeviceInformationCommandHandler); + AttributeAccessInterfaceRegistry::Instance().Register(&bridge::gBridgedDeviceBasicInformationAttributes); #if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE - SetRpcRemoteServerPort(gFabricAdminServerPort); - InitRpcServer(gLocalServerPort); + bridge::SetRpcRemoteServerPort(gFabricAdminServerPort); + bridge::InitRpcServer(gLocalServerPort); AttemptRpcClientConnect(&DeviceLayer::SystemLayer(), nullptr); #endif - BridgeDeviceMgr().Init(); - VerifyOrDie(gBridgedAdministratorCommissioning.Init() == CHIP_NO_ERROR); + bridge::BridgeDeviceMgr().Init(); + VerifyOrDie(bridge::gBridgedAdministratorCommissioning.Init() == CHIP_NO_ERROR); - VerifyOrDieWithMsg(CommissionerControlInit() == CHIP_NO_ERROR, NotSpecified, + VerifyOrDieWithMsg(bridge::CommissionerControlInit() == CHIP_NO_ERROR, NotSpecified, "Failed to initialize Commissioner Control Server"); } @@ -269,7 +273,7 @@ void ApplicationShutdown() { ChipLogDetail(NotSpecified, "Fabric-Bridge: ApplicationShutdown()"); - if (CommissionerControlShutdown() != CHIP_NO_ERROR) + if (bridge::CommissionerControlShutdown() != CHIP_NO_ERROR) { ChipLogError(NotSpecified, "Failed to shutdown Commissioner Control Server"); } From c05110f0250c25db7a953720e9433f9dbccae7a6 Mon Sep 17 00:00:00 2001 From: Alex Tsitsiura Date: Tue, 5 Nov 2024 12:04:50 +0200 Subject: [PATCH 061/121] [Telink] Add OTA LZMA image compression & Update builds to docker version 90 (#36356) * [Telink] Decrease MCUboot RAM usage for LZMA compression * [Telink] Update process_binaries script for LZMA compression * [Telink] Optimize MCUboot flash usage for LZMA * [Telink] BOOT_BOOTSTRAP is not needed with BOOT_UPGRADE_ONLY mode * [Telink] Enable support LZMA compression * [Telink] Remove LZMA properties for RAW * [Telink] image update initiation via button press * [Telink] Increase heap size * [Telink] Use DEBUG log level as default * [Telink] Add Flash overay to test LZMA slot-1 smaller then slot-0 * Revert "[Telink] Add Flash overay to test LZMA" This reverts commit 88ec4cb2c9a6642c9ddb4d24c7afb3f1c4d7db6e. * [Telink] Fix matter.ota regenaration without remove build folder * [Telink] Add LZMA CI build * [Telink] Temporarry use latest Zephyr to check CI builds * Restyled by autopep8 * Restyled by isort * [Telink] Update builds to docker version 90 * [Telink] Fix targets * [Telink] use compress-lzma instead of compress_lzma --------- Co-authored-by: Serhii Salamakha Co-authored-by: Restyled.io --- .github/workflows/bloat_check.yaml | 2 +- .github/workflows/build.yaml | 10 +-- .github/workflows/chef.yaml | 10 +-- .github/workflows/doxygen.yaml | 2 +- .github/workflows/examples-ameba.yaml | 2 +- .github/workflows/examples-asr.yaml | 2 +- .github/workflows/examples-bouffalolab.yaml | 2 +- .github/workflows/examples-cc13xx_26xx.yaml | 2 +- .github/workflows/examples-cc32xx.yaml | 2 +- .github/workflows/examples-efr32.yaml | 2 +- .github/workflows/examples-esp32.yaml | 4 +- .github/workflows/examples-infineon.yaml | 2 +- .github/workflows/examples-linux-arm.yaml | 2 +- .github/workflows/examples-linux-imx.yaml | 2 +- .../workflows/examples-linux-standalone.yaml | 2 +- .../examples-linux-tv-casting-app.yaml | 2 +- .github/workflows/examples-mw320.yaml | 2 +- .github/workflows/examples-nrfconnect.yaml | 2 +- .github/workflows/examples-nuttx.yaml | 2 +- .github/workflows/examples-nxp.yaml | 4 +- .github/workflows/examples-openiotsdk.yaml | 2 +- .github/workflows/examples-qpg.yaml | 2 +- .github/workflows/examples-stm32.yaml | 2 +- .github/workflows/examples-telink.yaml | 12 ++-- .github/workflows/examples-tizen.yaml | 2 +- .github/workflows/full-android.yaml | 2 +- .github/workflows/fuzzing-build.yaml | 2 +- .github/workflows/java-tests.yaml | 2 +- .github/workflows/lint.yml | 2 +- .github/workflows/minimal-build.yaml | 4 +- .github/workflows/qemu.yaml | 4 +- .github/workflows/release_artifacts.yaml | 4 +- .github/workflows/smoketest-android.yaml | 2 +- .github/workflows/tests.yaml | 4 +- .github/workflows/unit_integration_test.yaml | 2 +- .github/workflows/zap_regeneration.yaml | 2 +- .github/workflows/zap_templates.yaml | 2 +- .../telink/app/bootloader_compress_lzma.conf | 46 +++++++++++++ config/telink/chip-module/CMakeLists.txt | 11 ++- config/telink/chip-module/Kconfig | 21 ++++++ examples/all-clusters-app/ameba/README.md | 4 +- .../all-clusters-minimal-app/ameba/README.md | 4 +- examples/fabric-admin/README.md | 4 +- examples/fabric-bridge-app/linux/README.md | 4 +- examples/fabric-sync/README.md | 4 +- examples/light-switch-app/ameba/README.md | 4 +- examples/lighting-app/ameba/README.md | 4 +- examples/lighting-app/telink/prj.conf | 1 + examples/ota-requestor-app/ameba/README.md | 4 +- examples/pigweed-app/ameba/README.md | 4 +- examples/platform/telink/common.cmake | 6 +- .../telink/common/include/AppTaskCommon.h | 5 ++ .../telink/common/src/AppTaskCommon.cpp | 24 +++++++ integrations/cloudbuild/chef.yaml | 8 +-- integrations/cloudbuild/smoke-test.yaml | 14 ++-- scripts/build/build/targets.py | 1 + scripts/build/builders/telink.py | 5 ++ .../build/testdata/all_targets_linux_x64.txt | 2 +- scripts/tools/telink/process_binaries.py | 67 ++++++++++++++++++- 59 files changed, 270 insertions(+), 89 deletions(-) create mode 100644 config/telink/app/bootloader_compress_lzma.conf diff --git a/.github/workflows/bloat_check.yaml b/.github/workflows/bloat_check.yaml index 7ec2a6bf692011..43a3993eee6a91 100644 --- a/.github/workflows/bloat_check.yaml +++ b/.github/workflows/bloat_check.yaml @@ -34,7 +34,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 steps: - name: Checkout diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 210106ccc08e0c..85bb7955810aae 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -43,7 +43,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" @@ -139,7 +139,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" @@ -308,7 +308,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" @@ -371,7 +371,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" @@ -490,7 +490,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/chef.yaml b/.github/workflows/chef.yaml index a1e5907cb91a70..d7360f6cc4876d 100644 --- a/.github/workflows/chef.yaml +++ b/.github/workflows/chef.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 options: --user root steps: @@ -57,7 +57,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-esp32:81 + image: ghcr.io/project-chip/chip-build-esp32:90 options: --user root steps: @@ -78,7 +78,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nrf-platform:81 + image: ghcr.io/project-chip/chip-build-nrf-platform:90 options: --user root steps: @@ -99,7 +99,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-telink:81 + image: ghcr.io/project-chip/chip-build-telink:90 options: --user root steps: @@ -111,7 +111,7 @@ jobs: platform: telink # - name: Update Zephyr to specific revision (for developers purpose) # shell: bash - # run: scripts/run_in_build_env.sh "python3 scripts/tools/telink/update_zephyr.py 3ed7686a9378de6be1368c912f9a42f998bbfb18" + # run: scripts/run_in_build_env.sh "python3 scripts/tools/telink/update_zephyr.py f762f1a1027284e63e338e6d83deeade62f355b0" - name: CI Examples Telink shell: bash run: | diff --git a/.github/workflows/doxygen.yaml b/.github/workflows/doxygen.yaml index 9dc5bbab1ac574..e345ff2a75a70e 100644 --- a/.github/workflows/doxygen.yaml +++ b/.github/workflows/doxygen.yaml @@ -84,7 +84,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-doxygen:81 + image: ghcr.io/project-chip/chip-build-doxygen:90 if: github.actor != 'restyled-io[bot]' diff --git a/.github/workflows/examples-ameba.yaml b/.github/workflows/examples-ameba.yaml index 1c87787cf67ecc..a4b40a19339507 100644 --- a/.github/workflows/examples-ameba.yaml +++ b/.github/workflows/examples-ameba.yaml @@ -39,7 +39,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-ameba:81 + image: ghcr.io/project-chip/chip-build-ameba:90 options: --user root steps: diff --git a/.github/workflows/examples-asr.yaml b/.github/workflows/examples-asr.yaml index 7597ef1783eea4..143ce3364fafad 100644 --- a/.github/workflows/examples-asr.yaml +++ b/.github/workflows/examples-asr.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-asr:81 + image: ghcr.io/project-chip/chip-build-asr:90 options: --user root steps: diff --git a/.github/workflows/examples-bouffalolab.yaml b/.github/workflows/examples-bouffalolab.yaml index 9a51b612a18a7c..2e9cf4a8849edd 100644 --- a/.github/workflows/examples-bouffalolab.yaml +++ b/.github/workflows/examples-bouffalolab.yaml @@ -38,7 +38,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-bouffalolab:81 + image: ghcr.io/project-chip/chip-build-bouffalolab:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-cc13xx_26xx.yaml b/.github/workflows/examples-cc13xx_26xx.yaml index 31988e66385236..097a7d103eac95 100644 --- a/.github/workflows/examples-cc13xx_26xx.yaml +++ b/.github/workflows/examples-cc13xx_26xx.yaml @@ -42,7 +42,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-ti:81 + image: ghcr.io/project-chip/chip-build-ti:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-cc32xx.yaml b/.github/workflows/examples-cc32xx.yaml index 24edcb3fa92603..25afa79903f12d 100644 --- a/.github/workflows/examples-cc32xx.yaml +++ b/.github/workflows/examples-cc32xx.yaml @@ -41,7 +41,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-ti:81 + image: ghcr.io/project-chip/chip-build-ti:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-efr32.yaml b/.github/workflows/examples-efr32.yaml index ab85bc1f6c9cdf..dd9fb120a365b2 100644 --- a/.github/workflows/examples-efr32.yaml +++ b/.github/workflows/examples-efr32.yaml @@ -41,7 +41,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-efr32:89 + image: ghcr.io/project-chip/chip-build-efr32:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-esp32.yaml b/.github/workflows/examples-esp32.yaml index b3a6ed24e66568..9853c0df51885d 100644 --- a/.github/workflows/examples-esp32.yaml +++ b/.github/workflows/examples-esp32.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-esp32:81 + image: ghcr.io/project-chip/chip-build-esp32:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" @@ -124,7 +124,7 @@ jobs: if: github.actor != 'restyled-io[bot]' && github.repository_owner == 'espressif' container: - image: ghcr.io/project-chip/chip-build-esp32:81 + image: ghcr.io/project-chip/chip-build-esp32:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-infineon.yaml b/.github/workflows/examples-infineon.yaml index ada44f1557baaf..49c2097cd696e8 100644 --- a/.github/workflows/examples-infineon.yaml +++ b/.github/workflows/examples-infineon.yaml @@ -38,7 +38,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-infineon:81 + image: ghcr.io/project-chip/chip-build-infineon:90 env: # TODO: this should probably be part of the dockerfile itself CY_TOOLS_PATHS: /opt/Tools/ModusToolbox/tools_3.2 diff --git a/.github/workflows/examples-linux-arm.yaml b/.github/workflows/examples-linux-arm.yaml index 5aeeb4d5494c4d..46c2173530c6be 100644 --- a/.github/workflows/examples-linux-arm.yaml +++ b/.github/workflows/examples-linux-arm.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-crosscompile:81 + image: ghcr.io/project-chip/chip-build-crosscompile:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-linux-imx.yaml b/.github/workflows/examples-linux-imx.yaml index d2f1014eb576cf..e1d64f7a058f1e 100644 --- a/.github/workflows/examples-linux-imx.yaml +++ b/.github/workflows/examples-linux-imx.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-imx:81 + image: ghcr.io/project-chip/chip-build-imx:90 steps: - name: Checkout diff --git a/.github/workflows/examples-linux-standalone.yaml b/.github/workflows/examples-linux-standalone.yaml index 2bed5acd82f040..8c483cacd45651 100644 --- a/.github/workflows/examples-linux-standalone.yaml +++ b/.github/workflows/examples-linux-standalone.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-linux-tv-casting-app.yaml b/.github/workflows/examples-linux-tv-casting-app.yaml index 31275c78501f5c..14bfb6fb91b17c 100644 --- a/.github/workflows/examples-linux-tv-casting-app.yaml +++ b/.github/workflows/examples-linux-tv-casting-app.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 steps: - name: Checkout diff --git a/.github/workflows/examples-mw320.yaml b/.github/workflows/examples-mw320.yaml index 8f76321a0c0242..077bdbbfb7f2b6 100644 --- a/.github/workflows/examples-mw320.yaml +++ b/.github/workflows/examples-mw320.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-nrfconnect.yaml b/.github/workflows/examples-nrfconnect.yaml index d781087fc84760..0db5e82e81d8e4 100644 --- a/.github/workflows/examples-nrfconnect.yaml +++ b/.github/workflows/examples-nrfconnect.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nrf-platform:81 + image: ghcr.io/project-chip/chip-build-nrf-platform:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/examples-nuttx.yaml b/.github/workflows/examples-nuttx.yaml index f1f682e00898f6..cccfa44557a4ba 100644 --- a/.github/workflows/examples-nuttx.yaml +++ b/.github/workflows/examples-nuttx.yaml @@ -38,7 +38,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nuttx:81 + image: ghcr.io/project-chip/chip-build-nuttx:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-nxp.yaml b/.github/workflows/examples-nxp.yaml index f9c6392bdc71ed..aa782544d2ae1d 100644 --- a/.github/workflows/examples-nxp.yaml +++ b/.github/workflows/examples-nxp.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nxp:81 + image: ghcr.io/project-chip/chip-build-nxp:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: @@ -240,7 +240,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-nxp-zephyr:81 + image: ghcr.io/project-chip/chip-build-nxp-zephyr:90 steps: - name: Checkout diff --git a/.github/workflows/examples-openiotsdk.yaml b/.github/workflows/examples-openiotsdk.yaml index 95389cb157f5ee..2d59643eeb3aac 100644 --- a/.github/workflows/examples-openiotsdk.yaml +++ b/.github/workflows/examples-openiotsdk.yaml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-openiotsdk:81 + image: ghcr.io/project-chip/chip-build-openiotsdk:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" options: --privileged diff --git a/.github/workflows/examples-qpg.yaml b/.github/workflows/examples-qpg.yaml index 312c49329283cd..3287b281dc77ef 100644 --- a/.github/workflows/examples-qpg.yaml +++ b/.github/workflows/examples-qpg.yaml @@ -40,7 +40,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-stm32.yaml b/.github/workflows/examples-stm32.yaml index 2e8f8576735bfe..d10c91a8e8ca6d 100644 --- a/.github/workflows/examples-stm32.yaml +++ b/.github/workflows/examples-stm32.yaml @@ -41,7 +41,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" steps: diff --git a/.github/workflows/examples-telink.yaml b/.github/workflows/examples-telink.yaml index a1d7244ab8f02f..6c8b9bd5217f32 100644 --- a/.github/workflows/examples-telink.yaml +++ b/.github/workflows/examples-telink.yaml @@ -39,7 +39,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-telink:81 + image: ghcr.io/project-chip/chip-build-telink:90 volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" @@ -58,7 +58,7 @@ jobs: gh-context: ${{ toJson(github) }} # - name: Update Zephyr to specific revision (for developers purpose) - # run: scripts/run_in_build_env.sh "python3 scripts/tools/telink/update_zephyr.py 3ed7686a9378de6be1368c912f9a42f998bbfb18" + # run: scripts/run_in_build_env.sh "python3 scripts/tools/telink/update_zephyr.py f762f1a1027284e63e338e6d83deeade62f355b0" - name: Build example Telink (B92 retention) Air Quality Sensor App # Run test for master and s07641069 PRs @@ -167,14 +167,14 @@ jobs: - name: clean out build output (keep tools) run: rm -rf ./out/telink* - - name: Build example Telink (B92) Light Switch App with OTA, Shell, Factory Data + - name: Build example Telink (B92) Light Switch App with OTA (LZMA), Shell, Factory Data # Run test for master and all PRs run: | ./scripts/run_in_build_env.sh \ - "./scripts/build/build_examples.py --target 'telink-tlsr9528a-light-switch-ota-shell-factory-data' build" + "./scripts/build/build_examples.py --target 'telink-tlsr9528a-light-switch-ota-compress-lzma-shell-factory-data' build" .environment/pigweed-venv/bin/python3 scripts/tools/memory/gh_sizes.py \ - telink tlsr9528a light-switch-app-ota-shell-factory-data \ - out/telink-tlsr9528a-light-switch-ota-shell-factory-data/zephyr/zephyr.elf \ + telink tlsr9528a light-switch-app-ota-compress-lzma-shell-factory-data \ + out/telink-tlsr9528a-light-switch-ota-compress-lzma-shell-factory-data/zephyr/zephyr.elf \ /tmp/bloat_reports/ - name: clean out build output diff --git a/.github/workflows/examples-tizen.yaml b/.github/workflows/examples-tizen.yaml index f0e4dfb3a206dd..f465f3999f0f26 100644 --- a/.github/workflows/examples-tizen.yaml +++ b/.github/workflows/examples-tizen.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-tizen:81 + image: ghcr.io/project-chip/chip-build-tizen:90 options: --user root volumes: - "/tmp/bloat_reports:/tmp/bloat_reports" diff --git a/.github/workflows/full-android.yaml b/.github/workflows/full-android.yaml index c3871ad8815152..6acc150c03a111 100644 --- a/.github/workflows/full-android.yaml +++ b/.github/workflows/full-android.yaml @@ -39,7 +39,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-android:81 + image: ghcr.io/project-chip/chip-build-android:90 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/fuzzing-build.yaml b/.github/workflows/fuzzing-build.yaml index c37ca98e1a513e..f36b370448fa66 100644 --- a/.github/workflows/fuzzing-build.yaml +++ b/.github/workflows/fuzzing-build.yaml @@ -33,7 +33,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/java-tests.yaml b/.github/workflows/java-tests.yaml index abf2e75027b489..f416be3a4d2998 100644 --- a/.github/workflows/java-tests.yaml +++ b/.github/workflows/java-tests.yaml @@ -43,7 +43,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-java:81 + image: ghcr.io/project-chip/chip-build-java:90 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=0 net.ipv6.conf.all.forwarding=0" diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 2471529f4170fb..590a2595ee6f96 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -36,7 +36,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 steps: - name: Checkout diff --git a/.github/workflows/minimal-build.yaml b/.github/workflows/minimal-build.yaml index dae8a2b8ce0a7f..da55158cc7c57f 100644 --- a/.github/workflows/minimal-build.yaml +++ b/.github/workflows/minimal-build.yaml @@ -34,7 +34,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-minimal:81 + image: ghcr.io/project-chip/chip-build-minimal:90 steps: - name: Checkout @@ -56,7 +56,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-minimal:81 + image: ghcr.io/project-chip/chip-build-minimal:90 steps: - name: Checkout diff --git a/.github/workflows/qemu.yaml b/.github/workflows/qemu.yaml index 5f9bbe7022826d..07b31eec0ddb11 100644 --- a/.github/workflows/qemu.yaml +++ b/.github/workflows/qemu.yaml @@ -41,7 +41,7 @@ jobs: if: github.actor != 'restyled-io[bot]' && github.repository_owner == 'espressif' container: - image: ghcr.io/project-chip/chip-build-esp32-qemu:81 + image: ghcr.io/project-chip/chip-build-esp32-qemu:90 volumes: - "/tmp/log_output:/tmp/test_logs" @@ -79,7 +79,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-tizen-qemu:81 + image: ghcr.io/project-chip/chip-build-tizen-qemu:90 options: --user root volumes: - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/release_artifacts.yaml b/.github/workflows/release_artifacts.yaml index 54997b6efa9b39..14b2c327452194 100644 --- a/.github/workflows/release_artifacts.yaml +++ b/.github/workflows/release_artifacts.yaml @@ -32,7 +32,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-esp32:81 + image: ghcr.io/project-chip/chip-build-esp32:90 steps: - name: Checkout @@ -64,7 +64,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build-efr32:85 + image: ghcr.io/project-chip/chip-build-efr32:90 steps: - name: Checkout uses: actions/checkout@v4 diff --git a/.github/workflows/smoketest-android.yaml b/.github/workflows/smoketest-android.yaml index 7d0e124ca5656b..38a614e71246f5 100644 --- a/.github/workflows/smoketest-android.yaml +++ b/.github/workflows/smoketest-android.yaml @@ -37,7 +37,7 @@ jobs: if: github.actor != 'restyled-io[bot]' container: - image: ghcr.io/project-chip/chip-build-android:81 + image: ghcr.io/project-chip/chip-build-android:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 77c31b8be7212e..3b2fcb093a9158 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -50,7 +50,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=1 net.ipv6.conf.all.forwarding=1" @@ -457,7 +457,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 options: --privileged --sysctl "net.ipv6.conf.all.disable_ipv6=0 net.ipv4.conf.all.forwarding=0 net.ipv6.conf.all.forwarding=0" diff --git a/.github/workflows/unit_integration_test.yaml b/.github/workflows/unit_integration_test.yaml index 1cc021375d7b1c..b2fc345bda1a9d 100644 --- a/.github/workflows/unit_integration_test.yaml +++ b/.github/workflows/unit_integration_test.yaml @@ -40,7 +40,7 @@ jobs: runs-on: ubuntu-latest container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 volumes: - "/:/runner-root-volume" - "/tmp/log_output:/tmp/test_logs" diff --git a/.github/workflows/zap_regeneration.yaml b/.github/workflows/zap_regeneration.yaml index 483b9486d1bdc6..0d6d9b6db70ca8 100644 --- a/.github/workflows/zap_regeneration.yaml +++ b/.github/workflows/zap_regeneration.yaml @@ -30,7 +30,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 defaults: run: shell: sh diff --git a/.github/workflows/zap_templates.yaml b/.github/workflows/zap_templates.yaml index 383a98583bd9fc..c4edd57421ba6f 100644 --- a/.github/workflows/zap_templates.yaml +++ b/.github/workflows/zap_templates.yaml @@ -35,7 +35,7 @@ jobs: runs-on: ubuntu-20.04 container: - image: ghcr.io/project-chip/chip-build:81 + image: ghcr.io/project-chip/chip-build:90 defaults: run: shell: sh diff --git a/config/telink/app/bootloader_compress_lzma.conf b/config/telink/app/bootloader_compress_lzma.conf new file mode 100644 index 00000000000000..cb349eed0ce387 --- /dev/null +++ b/config/telink/app/bootloader_compress_lzma.conf @@ -0,0 +1,46 @@ +# +# Copyright (c) 2024 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. +# + +# Enable overwrite the primary slot with the upgrade image instead of swapping them. +# This prevents the fallback recovery. +CONFIG_BOOT_UPGRADE_ONLY=y + +# Enable this option in case if the whole slot0 image need to be validated +# With disabled option the only image magic is validated +CONFIG_BOOT_VALIDATE_SLOT0=y + +# Maximum number of image sectors supported by the bootloader. +# Maximum signed image size: 512 * 4096 = 2M Bytes +CONFIG_BOOT_MAX_IMG_SECTORS=512 + +# Sets log level for modules which don't specify it explicitly. +# When set to 0 it means log will not be activated for those modules. +# Levels are: +# - 0 OFF, do not write by default +# - 1 ERROR, default to only write LOG_LEVEL_ERR +# - 2 WARNING, default to write LOG_LEVEL_WRN +# - 3 INFO, default to write LOG_LEVEL_INFO +# - 4 DEBUG, default to write LOG_LEVEL_DBG +CONFIG_LOG_DEFAULT_LEVEL=3 + +# LZMA used sys_heap based allocators +CONFIG_COMMON_LIBC_MALLOC_ARENA_SIZE=78000 + +# Enable build size optimizations +CONFIG_SIZE_OPTIMIZATIONS=y + +# Enable support LZMA compression +CONFIG_COMPRESS_LZMA=y diff --git a/config/telink/chip-module/CMakeLists.txt b/config/telink/chip-module/CMakeLists.txt index 7490cc497079cd..1b148476f3e0d8 100644 --- a/config/telink/chip-module/CMakeLists.txt +++ b/config/telink/chip-module/CMakeLists.txt @@ -185,8 +185,17 @@ endif() # ============================================================================== if (CONFIG_CHIP_OTA_IMAGE_BUILD) + if (CONFIG_COMPRESS_LZMA) + add_custom_command( + OUTPUT ${PROJECT_BINARY_DIR}/${CONFIG_SIGNED_OTA_IMAGE_FILE_NAME} + COMMAND ${CMAKE_COMMAND} -E true + COMMENT "Fake command, ${CONFIG_SIGNED_OTA_IMAGE_FILE_NAME} file created in process_binaries target" + DEPENDS ${ZEPHYR_FINAL_EXECUTABLE} + ) + endif() + chip_ota_image(chip-ota-image - INPUT_FILES ${PROJECT_BINARY_DIR}/zephyr.signed.bin + INPUT_FILES ${PROJECT_BINARY_DIR}/${CONFIG_SIGNED_OTA_IMAGE_FILE_NAME} OUTPUT_FILE ${PROJECT_BINARY_DIR}/${CONFIG_CHIP_OTA_IMAGE_FILE_NAME} ) add_dependencies(chip-ota-image process_binaries) diff --git a/config/telink/chip-module/Kconfig b/config/telink/chip-module/Kconfig index 7d9296bed5dfcc..ee87af2bbe9731 100644 --- a/config/telink/chip-module/Kconfig +++ b/config/telink/chip-module/Kconfig @@ -71,6 +71,27 @@ config CHIP_OTA_IMAGE_BUILD bool default y if CHIP_OTA_REQUESTOR +config SIGNED_OTA_IMAGE_FILE_NAME + string "Zephyr signed image file name" + default "zephyr.signed.lzma.signed.bin" if COMPRESS_LZMA + default "zephyr.signed.bin" + depends on CHIP_OTA_REQUESTOR + help + Provides the file name of the generated Zephyr signed image. + +config TELINK_OTA_BUTTON_TEST + bool "Enable image update initiation via button press" + default n + depends on CHIP_OTA_REQUESTOR + help + Merge the signed binary with the same version as the main into slot-1 of merged.hex. + Pressing the button initiates a forced image update. + +config TELINK_OTA_PARTITION_ADDR + hex "image-1 partition address" + default $(dt_node_reg_addr_hex,$(dt_nodelabel_path,slot1_partition),0) + depends on TELINK_OTA_BUTTON_TEST + config CHIP_ROTATING_DEVICE_ID bool "Generate rotating device ID" default y diff --git a/examples/all-clusters-app/ameba/README.md b/examples/all-clusters-app/ameba/README.md index 9c442d6652e84f..5cf2c9aab87015 100644 --- a/examples/all-clusters-app/ameba/README.md +++ b/examples/all-clusters-app/ameba/README.md @@ -27,11 +27,11 @@ The CHIP demo application is supported on - Pull docker image: - $ docker pull ghcr.io/project-chip/chip-build-ameba:81 + $ docker pull ghcr.io/project-chip/chip-build-ameba:90 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:81 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:90 - Setup build environment: diff --git a/examples/all-clusters-minimal-app/ameba/README.md b/examples/all-clusters-minimal-app/ameba/README.md index b120d9c4bfebfa..447d950be39f86 100644 --- a/examples/all-clusters-minimal-app/ameba/README.md +++ b/examples/all-clusters-minimal-app/ameba/README.md @@ -27,13 +27,13 @@ The CHIP demo application is supported on - Pull docker image: ``` - $ docker pull ghcr.io/project-chip/chip-build-ameba:81 + $ docker pull ghcr.io/project-chip/chip-build-ameba:90 ``` - Run docker container: ``` - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:81 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:90 ``` - Setup build environment: diff --git a/examples/fabric-admin/README.md b/examples/fabric-admin/README.md index bdfb82d5ac5d8d..92fdffda6b830f 100644 --- a/examples/fabric-admin/README.md +++ b/examples/fabric-admin/README.md @@ -23,13 +23,13 @@ For Raspberry Pi 4 example: ### Pull Docker Images ``` -docker pull ghcr.io/project-chip/chip-build-crosscompile:81 +docker pull ghcr.io/project-chip/chip-build-crosscompile:90 ``` ### Run docker ``` -docker run -it -v ~/connectedhomeip:/var/connectedhomeip ghcr.io/project-chip/chip-build-crosscompile:81 /bin/bash +docker run -it -v ~/connectedhomeip:/var/connectedhomeip ghcr.io/project-chip/chip-build-crosscompile:90 /bin/bash ``` ### Build diff --git a/examples/fabric-bridge-app/linux/README.md b/examples/fabric-bridge-app/linux/README.md index fdb466147e3cf4..912bb32c01dafb 100644 --- a/examples/fabric-bridge-app/linux/README.md +++ b/examples/fabric-bridge-app/linux/README.md @@ -100,13 +100,13 @@ defined: Pull Docker Images ``` - docker pull ghcr.io/project-chip/chip-build-crosscompile:81 + docker pull ghcr.io/project-chip/chip-build-crosscompile:90 ``` Run docker ``` - docker run -it -v ~/connectedhomeip:/var/connectedhomeip ghcr.io/project-chip/chip-build-crosscompile:81 /bin/bash + docker run -it -v ~/connectedhomeip:/var/connectedhomeip ghcr.io/project-chip/chip-build-crosscompile:90 /bin/bash ``` Build diff --git a/examples/fabric-sync/README.md b/examples/fabric-sync/README.md index 0309218725f02b..0fd4735c745552 100644 --- a/examples/fabric-sync/README.md +++ b/examples/fabric-sync/README.md @@ -92,13 +92,13 @@ defined: Pull Docker Images ``` - docker pull ghcr.io/project-chip/chip-build-crosscompile:81 + docker pull ghcr.io/project-chip/chip-build-crosscompile:90 ``` Run docker ``` - docker run -it -v ~/connectedhomeip:/var/connectedhomeip ghcr.io/project-chip/chip-build-crosscompile:81 /bin/bash + docker run -it -v ~/connectedhomeip:/var/connectedhomeip ghcr.io/project-chip/chip-build-crosscompile:90 /bin/bash ``` Build diff --git a/examples/light-switch-app/ameba/README.md b/examples/light-switch-app/ameba/README.md index a0d02751a830c1..ea9304fe7ca4a9 100644 --- a/examples/light-switch-app/ameba/README.md +++ b/examples/light-switch-app/ameba/README.md @@ -26,11 +26,11 @@ The CHIP demo application is supported on - Pull docker image: - $ docker pull ghcr.io/project-chip/chip-build-ameba:81 + $ docker pull ghcr.io/project-chip/chip-build-ameba:90 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:81 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:90 - Setup build environment: diff --git a/examples/lighting-app/ameba/README.md b/examples/lighting-app/ameba/README.md index 7527d02f725099..e91aec075b50c0 100644 --- a/examples/lighting-app/ameba/README.md +++ b/examples/lighting-app/ameba/README.md @@ -23,11 +23,11 @@ The CHIP demo application is supported on - Pull docker image: - $ docker pull ghcr.io/project-chip/chip-build-ameba:81 + $ docker pull ghcr.io/project-chip/chip-build-ameba:90 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:81 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:90 - Setup build environment: diff --git a/examples/lighting-app/telink/prj.conf b/examples/lighting-app/telink/prj.conf index 39eb720b20e2b9..9c7bab3e5f98f7 100644 --- a/examples/lighting-app/telink/prj.conf +++ b/examples/lighting-app/telink/prj.conf @@ -31,6 +31,7 @@ CONFIG_BT_DEVICE_NAME="TelinkLight" # Disable Matter OTA DFU CONFIG_CHIP_OTA_REQUESTOR=n CONFIG_CHIP_DEVICE_SOFTWARE_VERSION=1 +CONFIG_TELINK_OTA_BUTTON_TEST=n # Disable CHIP shell support CONFIG_CHIP_LIB_SHELL=n diff --git a/examples/ota-requestor-app/ameba/README.md b/examples/ota-requestor-app/ameba/README.md index 1af661767dfd77..e748f41dc9b090 100644 --- a/examples/ota-requestor-app/ameba/README.md +++ b/examples/ota-requestor-app/ameba/README.md @@ -6,11 +6,11 @@ A prototype application that demonstrates OTA Requestor capabilities. - Pull docker image: - $ docker pull ghcr.io/project-chip/chip-build-ameba:81 + $ docker pull ghcr.io/project-chip/chip-build-ameba:90 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:81 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:90 - Setup build environment: diff --git a/examples/pigweed-app/ameba/README.md b/examples/pigweed-app/ameba/README.md index 647809108e65ac..136a37a14caf41 100644 --- a/examples/pigweed-app/ameba/README.md +++ b/examples/pigweed-app/ameba/README.md @@ -31,11 +31,11 @@ following features are available: - Pull docker image: - $ docker pull ghcr.io/project-chip/chip-build-ameba:81 + $ docker pull ghcr.io/project-chip/chip-build-ameba:90 - Run docker container: - $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:81 + $ docker run -it -v ${CHIP_DIR}:/root/chip ghcr.io/project-chip/chip-build-ameba:90 - Setup build environment: diff --git a/examples/platform/telink/common.cmake b/examples/platform/telink/common.cmake index 34ff2dbffdf471..80050c81b3b641 100644 --- a/examples/platform/telink/common.cmake +++ b/examples/platform/telink/common.cmake @@ -63,7 +63,11 @@ else() unset(USB_CONF_OVERLAY_FILE) endif() -set(BOOT_CONF_OVERLAY_FILE "${CHIP_ROOT}/config/telink/app/bootloader.conf") +if(${CONFIG_COMPRESS_LZMA} MATCHES y) + set(BOOT_CONF_OVERLAY_FILE "${CHIP_ROOT}/config/telink/app/bootloader_compress_lzma.conf") +else() + set(BOOT_CONF_OVERLAY_FILE "${CHIP_ROOT}/config/telink/app/bootloader.conf") +endif() if(NOT EXISTS "${BOOT_CONF_OVERLAY_FILE}") message(FATAL_ERROR "${BOOT_CONF_OVERLAY_FILE} doesn't exist") endif() diff --git a/examples/platform/telink/common/include/AppTaskCommon.h b/examples/platform/telink/common/include/AppTaskCommon.h index ff3f7bf174a939..22c5f51a937dcc 100644 --- a/examples/platform/telink/common/include/AppTaskCommon.h +++ b/examples/platform/telink/common/include/AppTaskCommon.h @@ -111,6 +111,11 @@ class AppTaskCommon static void StartWiFiHandler(AppEvent * aEvent); #endif +#if CONFIG_TELINK_OTA_BUTTON_TEST + static void TestOTAButtonEventHandler(void); + static void TestOTAHandler(AppEvent * aEvent); +#endif + static void ExampleActionButtonEventHandler(void); void SetExampleButtonCallbacks(EventHandler aAction_CB); diff --git a/examples/platform/telink/common/src/AppTaskCommon.cpp b/examples/platform/telink/common/src/AppTaskCommon.cpp index 13036743a5db65..858334aaa72dd7 100644 --- a/examples/platform/telink/common/src/AppTaskCommon.cpp +++ b/examples/platform/telink/common/src/AppTaskCommon.cpp @@ -447,7 +447,11 @@ void AppTaskCommon::LinkButtons(ButtonManager & buttonManager) { buttonManager.addCallback(FactoryResetButtonEventHandler, 0, true); buttonManager.addCallback(ExampleActionButtonEventHandler, 1, true); +#if CONFIG_TELINK_OTA_BUTTON_TEST + buttonManager.addCallback(TestOTAButtonEventHandler, 2, true); +#else buttonManager.addCallback(StartBleAdvButtonEventHandler, 2, true); +#endif #if CHIP_DEVICE_CONFIG_ENABLE_THREAD buttonManager.addCallback(StartThreadButtonEventHandler, 3, true); #elif CHIP_DEVICE_CONFIG_ENABLE_WIFI @@ -595,6 +599,26 @@ void AppTaskCommon::FactoryResetTimerEventHandler(AppEvent * aEvent) LOG_INF("Factory Reset Trigger Counter is cleared"); } +#if CONFIG_TELINK_OTA_BUTTON_TEST +void AppTaskCommon::TestOTAButtonEventHandler(void) +{ + AppEvent event; + + event.Type = AppEvent::kEventType_Button; + event.ButtonEvent.Action = kButtonPushEvent; + event.Handler = TestOTAHandler; + GetAppTask().PostEvent(&event); +} + +void AppTaskCommon::TestOTAHandler(AppEvent * aEvent) +{ + LOG_INF("TestOTAHandler"); + + chip::DeviceLayer::OTAImageProcessorImpl imageProcessor; + imageProcessor.Apply(); +} +#endif + #if CHIP_DEVICE_CONFIG_ENABLE_THREAD void AppTaskCommon::StartThreadButtonEventHandler(void) { diff --git a/integrations/cloudbuild/chef.yaml b/integrations/cloudbuild/chef.yaml index fd34dab03f06d6..1eafb85580a072 100644 --- a/integrations/cloudbuild/chef.yaml +++ b/integrations/cloudbuild/chef.yaml @@ -1,5 +1,5 @@ steps: - - name: "ghcr.io/project-chip/chip-build-vscode:81" + - name: "ghcr.io/project-chip/chip-build-vscode:90" entrypoint: "bash" args: - "-c" @@ -7,7 +7,7 @@ steps: git config --global --add safe.directory "*" python scripts/checkout_submodules.py --shallow --recursive --platform esp32 nrfconnect silabs linux android id: Submodules - - name: "ghcr.io/project-chip/chip-build-vscode:81" + - name: "ghcr.io/project-chip/chip-build-vscode:90" # NOTE: silabs boostrap is NOT done with the rest as it requests a conflicting # jinja2 version (asks for 3.1.3 when constraints.txt asks for 3.0.3) env: @@ -23,7 +23,7 @@ steps: - name: pwenv path: /pwenv timeout: 900s - - name: "ghcr.io/project-chip/chip-build-vscode:81" + - name: "ghcr.io/project-chip/chip-build-vscode:90" env: - PW_ENVIRONMENT_ROOT=/pwenv args: @@ -38,7 +38,7 @@ steps: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:81" + - name: "ghcr.io/project-chip/chip-build-vscode:90" env: - PW_ENVIRONMENT_ROOT=/pwenv args: diff --git a/integrations/cloudbuild/smoke-test.yaml b/integrations/cloudbuild/smoke-test.yaml index 02e73512c43928..f1ca12766f0d29 100644 --- a/integrations/cloudbuild/smoke-test.yaml +++ b/integrations/cloudbuild/smoke-test.yaml @@ -1,5 +1,5 @@ steps: - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" entrypoint: "bash" args: - "-c" @@ -7,7 +7,7 @@ steps: git config --global --add safe.directory "*" python scripts/checkout_submodules.py --shallow --recursive --platform esp32 nrfconnect silabs linux android id: Submodules - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" # NOTE: silabs boostrap is NOT done with the rest as it requests a conflicting # jinja2 version (asks for 3.1.3 when constraints.txt asks for 3.0.3) env: @@ -24,7 +24,7 @@ steps: path: /pwenv timeout: 900s - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" id: ESP32 env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -45,7 +45,7 @@ steps: volumes: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" id: NRFConnect env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -66,7 +66,7 @@ steps: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" id: EFR32 env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -88,7 +88,7 @@ steps: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" id: Linux env: - PW_ENVIRONMENT_ROOT=/pwenv @@ -141,7 +141,7 @@ steps: - name: pwenv path: /pwenv - - name: "ghcr.io/project-chip/chip-build-vscode:89" + - name: "ghcr.io/project-chip/chip-build-vscode:90" id: Android env: - PW_ENVIRONMENT_ROOT=/pwenv diff --git a/scripts/build/build/targets.py b/scripts/build/build/targets.py index ff7dd298351688..b36824bc481583 100755 --- a/scripts/build/build/targets.py +++ b/scripts/build/build/targets.py @@ -800,6 +800,7 @@ def BuildTelinkTarget(): target.AppendModifier('4mb', enable_4mb_flash=True) target.AppendModifier('mars', mars_board_config=True) target.AppendModifier('usb', usb_board_config=True) + target.AppendModifier('compress-lzma', compress_lzma_config=True) return target diff --git a/scripts/build/builders/telink.py b/scripts/build/builders/telink.py index 1145b848a289b6..644f4cdc08e23a 100644 --- a/scripts/build/builders/telink.py +++ b/scripts/build/builders/telink.py @@ -154,6 +154,7 @@ def __init__(self, enable_4mb_flash: bool = False, mars_board_config: bool = False, usb_board_config: bool = False, + compress_lzma_config: bool = False, ): super(TelinkBuilder, self).__init__(root, runner) self.app = app @@ -166,6 +167,7 @@ def __init__(self, self.enable_4mb_flash = enable_4mb_flash self.mars_board_config = mars_board_config self.usb_board_config = usb_board_config + self.compress_lzma_config = compress_lzma_config def get_cmd_prefixes(self): if not self._runner.dry_run: @@ -210,6 +212,9 @@ def generate(self): if self.usb_board_config: flags.append("-DTLNK_USB_DONGLE=y") + if self.compress_lzma_config: + flags.append("-DCONFIG_COMPRESS_LZMA=y") + if self.options.pregen_dir: flags.append(f"-DCHIP_CODEGEN_PREGEN_DIR={shlex.quote(self.options.pregen_dir)}") diff --git a/scripts/build/testdata/all_targets_linux_x64.txt b/scripts/build/testdata/all_targets_linux_x64.txt index e58549453af58b..f34f42b55e0584 100644 --- a/scripts/build/testdata/all_targets_linux_x64.txt +++ b/scripts/build/testdata/all_targets_linux_x64.txt @@ -22,5 +22,5 @@ nuttx-x64-light qpg-qpg6105-{lock,light,shell,persistent-storage,light-switch,thermostat}[-updateimage] stm32-stm32wb5mm-dk-light tizen-arm-{all-clusters,chip-tool,light,tests}[-no-ble][-no-thread][-no-wifi][-asan][-ubsan][-coverage][-with-ui] -telink-{tlsr9118bdk40d,tlsr9518adk80d,tlsr9528a,tlsr9528a_retention,tlsr9258a,tlsr9258a_retention}-{air-quality-sensor,all-clusters,all-clusters-minimal,bridge,contact-sensor,light,light-switch,lock,ota-requestor,pump,pump-controller,shell,smoke-co-alarm,temperature-measurement,thermostat,window-covering}[-ota][-dfu][-shell][-rpc][-factory-data][-4mb][-mars][-usb] +telink-{tlsr9118bdk40d,tlsr9518adk80d,tlsr9528a,tlsr9528a_retention,tlsr9258a,tlsr9258a_retention}-{air-quality-sensor,all-clusters,all-clusters-minimal,bridge,contact-sensor,light,light-switch,lock,ota-requestor,pump,pump-controller,shell,smoke-co-alarm,temperature-measurement,thermostat,window-covering}[-ota][-dfu][-shell][-rpc][-factory-data][-4mb][-mars][-usb][-compress-lzma] openiotsdk-{shell,lock}[-mbedtls][-psa] diff --git a/scripts/tools/telink/process_binaries.py b/scripts/tools/telink/process_binaries.py index 0f650e25427521..5144920dd86823 100755 --- a/scripts/tools/telink/process_binaries.py +++ b/scripts/tools/telink/process_binaries.py @@ -16,6 +16,7 @@ # limitations under the License. # +import lzma import os import subprocess import sys @@ -58,6 +59,45 @@ def merge_binaries(input_file1, input_file2, output_file, offset): # Obtain build configuration build_conf = BuildConfiguration(os.path.join(os.getcwd(), os.pardir)) + +def compress_lzma_firmware(input_file, output_file): + # Read the input firmware binary + with open(input_file, 'rb') as f: + firmware_data = f.read() # Read the rest of the file from the offset + + # Define the properties + lc = 1 # Literal context bits + lp = 2 # Literal position bits + pb = 0 # Position bits + dict_size = build_conf['CONFIG_COMPRESS_LZMA_DICTIONARY_SIZE'] # dictionary size + + # Create the LZMA compressor using the specified parameters + compressor = lzma.LZMACompressor( + format=lzma.FORMAT_RAW, # Use raw format to match with `lzma_raw_decoder()` in C + filters=[ + { + "id": lzma.FILTER_LZMA1, # Use LZMA1 filter for compatibility + "dict_size": dict_size, # Set dictionary size + "lc": lc, # Literal context bits + "lp": lp, # Literal position bits + "pb": pb, # Position bits + "mode": lzma.MODE_NORMAL, # Normal compression mode + "mf": lzma.MF_BT4, # Match finder algorithm + "depth": 0 # Default match finder depth + } + ] + ) + + # Compress the firmware data + compressed_data = compressor.compress(firmware_data) + compressor.flush() + + # Write the compressed binary to output file + with open(output_file, 'wb') as f: + f.write(compressed_data) + + print(f"Compressed {input_file} -> {output_file} (size reduced from {len(firmware_data)} to {len(compressed_data)} bytes)") + + # Clean up merged.bin from previous build if os.path.exists('merged.bin'): os.remove('merged.bin') @@ -83,7 +123,7 @@ def merge_binaries(input_file1, input_file2, output_file, offset): '--slot-size', str(build_conf['CONFIG_FLASH_LOAD_SIZE']), '--key', os.path.join(ZEPHYR_BASE, '../', build_conf['CONFIG_MCUBOOT_SIGNATURE_KEY_FILE']), 'merged.bin', - 'zephyr.signed.bin' + build_conf['CONFIG_SIGNED_OTA_IMAGE_FILE_NAME'] ] try: subprocess.run(sign_command, check=True) @@ -94,6 +134,31 @@ def merge_binaries(input_file1, input_file2, output_file, offset): # Merge MCUBoot binary if configured if build_conf.getboolean('CONFIG_BOOTLOADER_MCUBOOT'): merge_binaries('mcuboot.bin', 'zephyr.signed.bin', 'merged.bin', build_conf['CONFIG_FLASH_LOAD_OFFSET']) + if build_conf.getboolean('CONFIG_COMPRESS_LZMA'): + compress_lzma_firmware('zephyr.signed.bin', 'zephyr.signed.lzma.bin') + + sign_command = [ + 'python3', + os.path.join(ZEPHYR_BASE, '../bootloader/mcuboot/scripts/imgtool.py'), + 'sign', + '--version', '0.0.0+0', + '--align', '1', + '--header-size', str(build_conf['CONFIG_ROM_START_OFFSET']), + '--slot-size', str(build_conf['CONFIG_FLASH_LOAD_SIZE']), + '--key', os.path.join(ZEPHYR_BASE, '../', build_conf['CONFIG_MCUBOOT_SIGNATURE_KEY_FILE']), + '--pad-header', + 'zephyr.signed.lzma.bin', + build_conf['CONFIG_SIGNED_OTA_IMAGE_FILE_NAME'] + ] + + try: + subprocess.run(sign_command, check=True) + except subprocess.CalledProcessError as e: + raise RuntimeError(f"Error signing the image: {e}") + + if build_conf.getboolean('CONFIG_TELINK_OTA_BUTTON_TEST'): + merge_binaries('merged.bin', build_conf['CONFIG_SIGNED_OTA_IMAGE_FILE_NAME'], + 'merged.bin', build_conf['CONFIG_TELINK_OTA_PARTITION_ADDR']) # Merge Factory Data binary if configured if build_conf.getboolean('CONFIG_CHIP_FACTORY_DATA_MERGE_WITH_FIRMWARE'): From ba1f9a228b1713a249c45f50507c044131b86f3f Mon Sep 17 00:00:00 2001 From: Jeff Tung <100387939+jtung-apple@users.noreply.github.com> Date: Tue, 5 Nov 2024 04:00:06 -0800 Subject: [PATCH 062/121] [Darwin] MTRDeviceController_XPC logging for compressedFabricID (#36342) * [Darwin] MTRDeviceController_XPC logging for compressedFabricID * Update src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm --------- Co-authored-by: Kiel Oleson --- src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm index 53a04b1e206b98..9b9a87bb97a5cc 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceController_XPC.mm @@ -467,7 +467,7 @@ - (oneway void)controller:(NSUUID *)controller controllerConfigurationUpdated:(N NSArray * deviceInfoList = MTR_SAFE_CAST(configuration[MTRDeviceControllerRegistrationNodeIDsKey], NSArray); - MTR_LOG("Received controllerConfigurationUpdated: controllerNode ID %@ deviceInfoList %@", self.controllerNodeID, deviceInfoList); + MTR_LOG("Received controllerConfigurationUpdated: controllerNodeID %@ compressedFabricID %016lluX deviceInfoList %@", self.controllerNodeID, self.compressedFabricID.unsignedLongLongValue, deviceInfoList); for (NSDictionary * deviceInfo in deviceInfoList) { if (!MTR_SAFE_CAST(deviceInfo, NSDictionary)) { From 22fb834d3514104ae2ae3896a4ebc427acfea053 Mon Sep 17 00:00:00 2001 From: shripad621git <79364691+shripad621git@users.noreply.github.com> Date: Tue, 5 Nov 2024 19:28:54 +0530 Subject: [PATCH 063/121] Update esp-insights component to latest version (#36078) --- config/esp32/components/chip/idf_component.yml | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/config/esp32/components/chip/idf_component.yml b/config/esp32/components/chip/idf_component.yml index 2e7415827ff264..2662ad5eb7ef22 100644 --- a/config/esp32/components/chip/idf_component.yml +++ b/config/esp32/components/chip/idf_component.yml @@ -18,7 +18,7 @@ dependencies: - if: "idf_version >=4.4" espressif/esp_insights: - version: "1.0.1" + version: "1.2.2" require: public # There is an issue with IDF-Component-Manager when ESP Insights is included. # Issue: https://github.com/project-chip/connectedhomeip/issues/29125 @@ -26,14 +26,6 @@ dependencies: - if: "idf_version >=5.0" - if: "target != esp32h2" - # This matches the dependency of esp_insights - espressif/esp_diag_data_store: - version: "1.0.1" - require: public - rules: - - if: "idf_version >=5.0" - - if: "target != esp32h2" - espressif/esp_rcp_update: version: "1.2.0" rules: From 344632cdc45c4151e0dca5e8dba5b186df19255f Mon Sep 17 00:00:00 2001 From: Wang Qixiang <43193572+wqx6@users.noreply.github.com> Date: Tue, 5 Nov 2024 22:11:57 +0800 Subject: [PATCH 064/121] ESP32: Add support for ESP32-P4 (#36312) * ESP32: Add support for ESP32-P4 * Restyled by clang-format * Restyled by prettier-yaml --------- Co-authored-by: Restyled.io --- config/esp32/components/chip/CMakeLists.txt | 13 +++++-- .../esp32/components/chip/idf_component.yml | 5 +++ .../esp32/main/Kconfig.projbuild | 8 +++- .../esp32/sdkconfig.defaults.esp32p4 | 37 +++++++++++++++++++ .../esp32/sdkconfig.defaults.esp32p4 | 37 +++++++++++++++++++ .../platform/esp32/common/Esp32AppServer.cpp | 12 ------ .../ESP32/ConfigurationManagerImpl.cpp | 2 + src/platform/ESP32/nimble/BLEManagerImpl.cpp | 7 ++++ 8 files changed, 104 insertions(+), 17 deletions(-) create mode 100644 examples/all-clusters-app/esp32/sdkconfig.defaults.esp32p4 create mode 100644 examples/lighting-app/esp32/sdkconfig.defaults.esp32p4 diff --git a/config/esp32/components/chip/CMakeLists.txt b/config/esp32/components/chip/CMakeLists.txt index ddf4d72ff8691b..f3e919d3b6b9db 100644 --- a/config/esp32/components/chip/CMakeLists.txt +++ b/config/esp32/components/chip/CMakeLists.txt @@ -428,6 +428,8 @@ if(CONFIG_BT_ENABLED) idf_component_get_property(bt_dir bt COMPONENT_DIR) list(APPEND chip_libraries $) list(APPEND chip_libraries "${bt_dir}/controller/lib_${target_name}/${target_name}-bt-lib/libble_app.a") + elseif(target_name STREQUAL "esp32p4") + list(APPEND chip_libraries $) else() list(APPEND chip_libraries $ -lbtdm_app) endif() @@ -507,10 +509,10 @@ idf_component_get_property(lwip_lib lwip COMPONENT_LIB) list(APPEND chip_libraries $) +idf_component_get_property(esp_wifi_lib esp_wifi COMPONENT_LIB) +list(APPEND chip_libraries $) if (CONFIG_ESP32_WIFI_ENABLED) - idf_component_get_property(esp_wifi_lib esp_wifi COMPONENT_LIB) idf_component_get_property(esp_wifi_dir esp_wifi COMPONENT_DIR) - list(APPEND chip_libraries $) if (CONFIG_IDF_TARGET_ESP32C2) set(blobs core net80211 pp) else() @@ -536,6 +538,7 @@ list(APPEND chip_libraries $) idf_component_get_property(esp_hw_support_lib esp_hw_support COMPONENT_LIB) list(APPEND chip_libraries $) +if (NOT CONFIG_IDF_TARGET_ESP32P4) idf_component_get_property(esp_phy_lib esp_phy COMPONENT_LIB) idf_component_get_property(esp_phy_dir esp_phy COMPONENT_DIR) list(APPEND chip_libraries $) @@ -550,8 +553,12 @@ endif() foreach(phy_blob ${phy_blobs}) list(APPEND chip_libraries "${esp_phy_dir}/lib/${target_name}/lib${phy_blob}.a") endforeach() +endif() -set(components_to_link esp_event hal esp_system soc efuse vfs driver esp_coex freertos esp_timer) +set(components_to_link esp_event hal esp_system soc efuse vfs driver freertos esp_timer) +if (NOT CONFIG_IDF_TARGET_ESP32P4) +list(APPEND components_to_link esp_coex) +endif() idf_build_get_property(build_components BUILD_COMPONENTS) foreach(component ${components_to_link}) # Some of the components are not present in IDF v4.x diff --git a/config/esp32/components/chip/idf_component.yml b/config/esp32/components/chip/idf_component.yml index 2662ad5eb7ef22..78d21af787c631 100644 --- a/config/esp32/components/chip/idf_component.yml +++ b/config/esp32/components/chip/idf_component.yml @@ -36,3 +36,8 @@ dependencies: require: public rules: - if: "idf_version >=4.3" + + espressif/esp_wifi_remote: + version: ">=0.1.12" + rules: + - if: "target in [esp32p4]" diff --git a/examples/all-clusters-app/esp32/main/Kconfig.projbuild b/examples/all-clusters-app/esp32/main/Kconfig.projbuild index 2cec0c32093734..72807a1618632a 100644 --- a/examples/all-clusters-app/esp32/main/Kconfig.projbuild +++ b/examples/all-clusters-app/esp32/main/Kconfig.projbuild @@ -26,6 +26,7 @@ menu "Demo" default DEVICE_TYPE_ESP32_C3_DEVKITM if IDF_TARGET_ESP32C3 default DEVICE_TYPE_ESP32_C2_DEVKITM if IDF_TARGET_ESP32C2 default DEVICE_TYPE_ESP32_C6_DEVKITC if IDF_TARGET_ESP32C6 + default DEVICE_TYPE_ESP32_P4_FUNCTION_EV_BOARD if IDF_TARGET_ESP32P4 help Specifies the type of ESP32 device. @@ -57,6 +58,9 @@ menu "Demo" config DEVICE_TYPE_ESP32_H2_DEVKITM bool "ESP32H2-DevKitM" depends on IDF_TARGET_ESP32H2 + config DEVICE_TYPE_ESP32_P4_FUNCTION_EV_BOARD + bool "ESP32P4 Function EV Board" + depends on IDF_TARGET_ESP32P4 endchoice choice @@ -87,7 +91,7 @@ menu "Demo" config TFT_PREDEFINED_DISPLAY_TYPE int range 0 5 - default 0 if DEVICE_TYPE_ESP32_DEVKITC || DEVICE_TYPE_ESP32_H2_DEVKITM + default 0 if DEVICE_TYPE_ESP32_DEVKITC || DEVICE_TYPE_ESP32_H2_DEVKITM || DEVICE_TYPE_ESP32_P4_FUNCTION_EV_BOARD default 0 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32_C2_DEVKITM || DEVICE_TYPE_ESP32_C6_DEVKITC default 3 if DEVICE_TYPE_M5STACK default 4 if DEVICE_TYPE_ESP32_WROVER_KIT @@ -118,7 +122,7 @@ menu "Demo" range 0 40 default 2 if DEVICE_TYPE_ESP32_DEVKITC #Use LED1 (blue LED) as status LED on DevKitC default 2 if DEVICE_TYPE_ESP32_ETHERNET_KIT - default 8 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32_C2_DEVKITM || DEVICE_TYPE_ESP32_C6_DEVKITC || DEVICE_TYPE_ESP32_H2_DEVKITM + default 8 if DEVICE_TYPE_ESP32_C3_DEVKITM || DEVICE_TYPE_ESP32_C2_DEVKITM || DEVICE_TYPE_ESP32_C6_DEVKITC || DEVICE_TYPE_ESP32_H2_DEVKITM || DEVICE_TYPE_ESP32_P4_FUNCTION_EV_BOARD default 26 if DEVICE_TYPE_ESP32_WROVER_KIT default 40 if DEVICE_TYPE_M5STACK help diff --git a/examples/all-clusters-app/esp32/sdkconfig.defaults.esp32p4 b/examples/all-clusters-app/esp32/sdkconfig.defaults.esp32p4 new file mode 100644 index 00000000000000..3211b306b2be99 --- /dev/null +++ b/examples/all-clusters-app/esp32/sdkconfig.defaults.esp32p4 @@ -0,0 +1,37 @@ +CONFIG_IDF_TARGET="esp32p4" + +# Flash size and partition +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" + +# Enable BLE Host but use remote controller +CONFIG_BT_ENABLED=y +CONFIG_BT_NIMBLE_ENABLED=y +CONFIG_BT_NIMBLE_TRANSPORT_UART=n +CONFIG_ESP_ENABLE_BT=y + +# Increase main task stack size +CONFIG_ESP_MAIN_TASK_STACK_SIZE=4096 + +# Disable Wi-Fi Soft AP +CONFIG_ESP_WIFI_SOFTAP_SUPPORT=n + +# LwIP +CONFIG_LWIP_IPV6_AUTOCONFIG=y +CONFIG_LWIP_IPV6_NUM_ADDRESSES=6 + +# mbedtls +CONFIG_MBEDTLS_HKDF_C=y + +# Matter shell +CONFIG_ENABLE_CHIP_SHELL=y + +# OTA requestor +CONFIG_ENABLE_OTA_REQUESTOR=y + +# Do not deinit BLE after commissioning +CONFIG_USE_BLE_ONLY_FOR_COMMISSIONING=n + +# ESP32-P4 Function EV Board use ESP32C6 as slave device +CONFIG_SLAVE_IDF_TARGET_ESP32C6=y diff --git a/examples/lighting-app/esp32/sdkconfig.defaults.esp32p4 b/examples/lighting-app/esp32/sdkconfig.defaults.esp32p4 new file mode 100644 index 00000000000000..3211b306b2be99 --- /dev/null +++ b/examples/lighting-app/esp32/sdkconfig.defaults.esp32p4 @@ -0,0 +1,37 @@ +CONFIG_IDF_TARGET="esp32p4" + +# Flash size and partition +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" + +# Enable BLE Host but use remote controller +CONFIG_BT_ENABLED=y +CONFIG_BT_NIMBLE_ENABLED=y +CONFIG_BT_NIMBLE_TRANSPORT_UART=n +CONFIG_ESP_ENABLE_BT=y + +# Increase main task stack size +CONFIG_ESP_MAIN_TASK_STACK_SIZE=4096 + +# Disable Wi-Fi Soft AP +CONFIG_ESP_WIFI_SOFTAP_SUPPORT=n + +# LwIP +CONFIG_LWIP_IPV6_AUTOCONFIG=y +CONFIG_LWIP_IPV6_NUM_ADDRESSES=6 + +# mbedtls +CONFIG_MBEDTLS_HKDF_C=y + +# Matter shell +CONFIG_ENABLE_CHIP_SHELL=y + +# OTA requestor +CONFIG_ENABLE_OTA_REQUESTOR=y + +# Do not deinit BLE after commissioning +CONFIG_USE_BLE_ONLY_FOR_COMMISSIONING=n + +# ESP32-P4 Function EV Board use ESP32C6 as slave device +CONFIG_SLAVE_IDF_TARGET_ESP32C6=y diff --git a/examples/platform/esp32/common/Esp32AppServer.cpp b/examples/platform/esp32/common/Esp32AppServer.cpp index 37dd7f4fe4adcf..8740f39cdbc080 100644 --- a/examples/platform/esp32/common/Esp32AppServer.cpp +++ b/examples/platform/esp32/common/Esp32AppServer.cpp @@ -40,18 +40,6 @@ #include #endif -#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#if CONFIG_BT_ENABLED -#include "esp_bt.h" -#if CONFIG_BT_NIMBLE_ENABLED -#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) -#include "esp_nimble_hci.h" -#endif // ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) -#include "nimble/nimble_port.h" -#endif // CONFIG_BT_NIMBLE_ENABLED -#endif // CONFIG_BT_ENABLED -#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE - #ifdef CONFIG_ENABLE_CHIP_SHELL #include #endif diff --git a/src/platform/ESP32/ConfigurationManagerImpl.cpp b/src/platform/ESP32/ConfigurationManagerImpl.cpp index a12750c6a45e57..653d523970369a 100644 --- a/src/platform/ESP32/ConfigurationManagerImpl.cpp +++ b/src/platform/ESP32/ConfigurationManagerImpl.cpp @@ -36,7 +36,9 @@ #include "esp_mac.h" #endif #include "esp_ota_ops.h" +#ifndef CONFIG_IDF_TARGET_ESP32P4 #include "esp_phy_init.h" +#endif #include "esp_wifi.h" #include "nvs.h" #include "nvs_flash.h" diff --git a/src/platform/ESP32/nimble/BLEManagerImpl.cpp b/src/platform/ESP32/nimble/BLEManagerImpl.cpp index ff48f5d9d6aa78..176fd81ee9f2c9 100644 --- a/src/platform/ESP32/nimble/BLEManagerImpl.cpp +++ b/src/platform/ESP32/nimble/BLEManagerImpl.cpp @@ -48,7 +48,9 @@ #include #include +#ifndef CONFIG_IDF_TARGET_ESP32P4 #include "esp_bt.h" +#endif #include "esp_log.h" #if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) @@ -1021,6 +1023,11 @@ CHIP_ERROR BLEManagerImpl::DeinitBLE() return MapBLEError(err); } +#ifdef CONFIG_IDF_TARGET_ESP32P4 +// Stub function to avoid link error +extern "C" void ble_transport_ll_deinit(void) {} +#endif + CHIP_ERROR BLEManagerImpl::ConfigureAdvertisingData(void) { CHIP_ERROR err; From 2b10abe40ec935aea15d6fc15e7089c99a618e57 Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Tue, 5 Nov 2024 17:05:05 +0100 Subject: [PATCH 065/121] Remove not-implemented methods from BufferWriter (#36368) --- src/lib/support/BufferWriter.h | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/src/lib/support/BufferWriter.h b/src/lib/support/BufferWriter.h index 64c22af21b43cf..ad474251516421 100644 --- a/src/lib/support/BufferWriter.h +++ b/src/lib/support/BufferWriter.h @@ -87,28 +87,8 @@ class BufferWriter uint8_t * Buffer() { return mBuf; } const uint8_t * Buffer() const { return mBuf; } - BufferWriter & Format(const char * format, ...) ENFORCE_FORMAT(2, 3) - { - va_list args; - va_start(args, format); - VFormat(format, args); - va_end(args); - return *this; - } - void Reset() { mNeeded = 0; } - /// Since this uses vsnprintf internally, on overflow - /// this will write one less byte that strictly can be - /// written (since null terminator will be in the binary data) - BufferWriter & VFormat(const char * format, va_list args) ENFORCE_FORMAT(2, 0); - - /// Assume a specific size for the buffer instead of mSize - /// - /// This is to allow avoiding off-by-one overflow truncation - /// when we know the underlying buffer size is larger. - BufferWriter & VFormatWithSize(size_t size, const char * format, va_list args) ENFORCE_FORMAT(3, 0); - protected: uint8_t * mBuf; size_t mSize; From 5158c55a9f4f1160f009c9dc876bcd6053e02f94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ludovic=20BOU=C3=89?= Date: Tue, 5 Nov 2024 17:19:12 +0100 Subject: [PATCH 066/121] energy-management-app: Add Water Heater in Readme index (#36344) * energy-management-app: Add Water Heater in Readme index energy-management-app: Add Water Heater in Readme index * Restyle --- examples/energy-management-app/linux/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/energy-management-app/linux/README.md b/examples/energy-management-app/linux/README.md index d28121f0a6d33b..57df50bba575cf 100644 --- a/examples/energy-management-app/linux/README.md +++ b/examples/energy-management-app/linux/README.md @@ -24,6 +24,7 @@ details. - [Activating python virtual env](#activating-python-virtual-env) - [Interacting with CHIP-REPL and the example app](#interacting-with-chip-repl-and-the-example-app) - [Using chip-repl to Fake a charging session](#using-chip-repl-to-fake-a-charging-session) + - [Water Heater App: Interaction using the chip-tool and TestEventTriggers](#water-heater-app-interaction-using-the-chip-tool-and-testeventtriggers)
From 2a7106fa158c2ab4056fa23379e898c68c1f258e Mon Sep 17 00:00:00 2001 From: Wang Qixiang <43193572+wqx6@users.noreply.github.com> Date: Wed, 6 Nov 2024 02:34:01 +0800 Subject: [PATCH 067/121] ESP32: Add functions to delete OpenThread task and deinit OpenThread stack (#36168) --- src/platform/ESP32/OpenthreadLauncher.cpp | 49 +++++++++++++++++++---- src/platform/ESP32/OpenthreadLauncher.h | 2 + 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/src/platform/ESP32/OpenthreadLauncher.cpp b/src/platform/ESP32/OpenthreadLauncher.cpp index 63f1bac825214f..0ab3dadf6862cb 100644 --- a/src/platform/ESP32/OpenthreadLauncher.cpp +++ b/src/platform/ESP32/OpenthreadLauncher.cpp @@ -40,12 +40,14 @@ #include #endif -static esp_netif_t * openthread_netif = NULL; -static esp_openthread_platform_config_t * s_platform_config = NULL; -static TaskHandle_t cli_transmit_task = NULL; -static QueueHandle_t cli_transmit_task_queue = NULL; +static esp_netif_t * openthread_netif = nullptr; +static esp_openthread_platform_config_t * s_platform_config = nullptr; +static TaskHandle_t cli_transmit_task = nullptr; +static QueueHandle_t cli_transmit_task_queue = nullptr; +static TaskHandle_t openthread_task = nullptr; static constexpr uint16_t OTCLI_TRANSMIT_TASK_STACK_SIZE = 1024; static constexpr UBaseType_t OTCLI_TRANSMIT_TASK_PRIORITY = 5; +static const char * TAG = "OpenThread"; CHIP_ERROR cli_transmit_task_post(std::unique_ptr && cli_str) { @@ -116,6 +118,14 @@ static esp_err_t cli_command_transmit_task(void) return ESP_OK; } +static void cli_command_transmit_task_delete(void) +{ + if (cli_transmit_task) + { + vTaskDelete(cli_transmit_task); + } +} + static esp_netif_t * init_openthread_netif(const esp_openthread_platform_config_t * config) { esp_netif_config_t cfg = ESP_NETIF_DEFAULT_OPENTHREAD(); @@ -141,7 +151,6 @@ static void ot_task_worker(void * context) #if defined(CONFIG_OPENTHREAD_BORDER_ROUTER) && defined(CONFIG_AUTO_UPDATE_RCP) static constexpr size_t kRcpVersionMaxSize = 100; -static const char * TAG = "RCP_UPDATE"; static void update_rcp(void) { @@ -230,7 +239,15 @@ esp_err_t openthread_init_stack(void) }; ESP_ERROR_CHECK(esp_netif_init()); - ESP_ERROR_CHECK(esp_vfs_eventfd_register(&eventfd_config)); + esp_err_t err = esp_vfs_eventfd_register(&eventfd_config); + if (err == ESP_ERR_INVALID_STATE) + { + ESP_LOGW(TAG, "eventfd is already registered"); + } + else if (err != ESP_OK) + { + return err; + } assert(s_platform_config); // Initialize the OpenThread stack ESP_ERROR_CHECK(esp_openthread_init(s_platform_config)); @@ -248,6 +265,24 @@ esp_err_t openthread_init_stack(void) esp_err_t openthread_launch_task(void) { - xTaskCreate(ot_task_worker, "ot_task", CONFIG_THREAD_TASK_STACK_SIZE, xTaskGetCurrentTaskHandle(), 5, NULL); + xTaskCreate(ot_task_worker, "ot_task", CONFIG_THREAD_TASK_STACK_SIZE, xTaskGetCurrentTaskHandle(), 5, &openthread_task); return ESP_OK; } + +esp_err_t openthread_deinit_stack(void) +{ + esp_openthread_netif_glue_deinit(); + esp_netif_destroy(openthread_netif); +#ifdef CONFIG_OPENTHREAD_CLI + cli_command_transmit_task_delete(); +#endif + return esp_openthread_deinit(); +} + +void openthread_delete_task(void) +{ + if (openthread_task) + { + vTaskDelete(openthread_task); + } +} diff --git a/src/platform/ESP32/OpenthreadLauncher.h b/src/platform/ESP32/OpenthreadLauncher.h index a15125f948d1dc..daeebd153c6698 100644 --- a/src/platform/ESP32/OpenthreadLauncher.h +++ b/src/platform/ESP32/OpenthreadLauncher.h @@ -29,4 +29,6 @@ esp_err_t openthread_init_br_rcp(const esp_rcp_update_config_t * update_config); esp_err_t set_openthread_platform_config(esp_openthread_platform_config_t * config); esp_err_t openthread_init_stack(void); esp_err_t openthread_launch_task(void); +esp_err_t openthread_deinit_stack(void); +void openthread_delete_task(void); CHIP_ERROR cli_transmit_task_post(std::unique_ptr && cli_str); From 1c655f913662603199c0c96e186d3ddc09951a16 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Wed, 6 Nov 2024 00:46:47 -0800 Subject: [PATCH 068/121] [Fabric-Admin] Fix failing cleanup bridge after bridge is removed (#36375) --- .../commands/fabric-sync/FabricSyncCommand.cpp | 14 +++++++------- .../commands/fabric-sync/FabricSyncCommand.h | 6 +++--- .../fabric-admin/device_manager/DeviceManager.cpp | 6 +++++- .../fabric-admin/device_manager/PairingManager.cpp | 7 ++++++- examples/fabric-admin/rpc/RpcClient.cpp | 2 +- 5 files changed, 22 insertions(+), 13 deletions(-) diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp index 6d42b04722fec6..e21f02f2ecb6b4 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp @@ -83,7 +83,7 @@ CHIP_ERROR FabricSyncAddBridgeCommand::RunCommand(NodeId remoteId) if (DeviceMgr().IsFabricSyncReady()) { // print to console - fprintf(stderr, "Remote Fabric Bridge has already been configured."); + fprintf(stderr, "Remote Fabric Bridge has already been configured.\n"); return CHIP_NO_ERROR; } @@ -126,7 +126,7 @@ CHIP_ERROR FabricSyncRemoveBridgeCommand::RunCommand() if (bridgeNodeId == kUndefinedNodeId) { // print to console - fprintf(stderr, "Remote Fabric Bridge is not configured yet, nothing to remove."); + fprintf(stderr, "Remote Fabric Bridge is not configured yet, nothing to remove.\n"); return CHIP_NO_ERROR; } @@ -176,7 +176,7 @@ CHIP_ERROR FabricSyncAddLocalBridgeCommand::RunCommand(NodeId deviceId) if (DeviceMgr().IsLocalBridgeReady()) { // print to console - fprintf(stderr, "Local Fabric Bridge has already been configured."); + fprintf(stderr, "Local Fabric Bridge has already been configured.\n"); return CHIP_NO_ERROR; } @@ -227,7 +227,7 @@ CHIP_ERROR FabricSyncRemoveLocalBridgeCommand::RunCommand() if (bridgeNodeId == kUndefinedNodeId) { // print to console - fprintf(stderr, "Local Fabric Bridge is not configured yet, nothing to remove."); + fprintf(stderr, "Local Fabric Bridge is not configured yet, nothing to remove.\n"); return CHIP_NO_ERROR; } @@ -292,18 +292,18 @@ void FabricSyncDeviceCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERRO } } -CHIP_ERROR FabricSyncDeviceCommand::RunCommand(EndpointId remoteId) +CHIP_ERROR FabricSyncDeviceCommand::RunCommand(EndpointId remoteEndpointId) { if (!DeviceMgr().IsFabricSyncReady()) { // print to console - fprintf(stderr, "Remote Fabric Bridge is not configured yet."); + fprintf(stderr, "Remote Fabric Bridge is not configured yet.\n"); return CHIP_NO_ERROR; } PairingManager::Instance().SetOpenCommissioningWindowDelegate(this); - DeviceMgr().OpenRemoteDeviceCommissioningWindow(remoteId); + DeviceMgr().OpenRemoteDeviceCommissioningWindow(remoteEndpointId); return CHIP_NO_ERROR; } diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h index 809cc7d322b364..82442acafa6af5 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h @@ -124,8 +124,8 @@ class FabricSyncDeviceCommand : public CHIPCommand, public CommissioningWindowDe AddArgument("endpointid", 0, UINT16_MAX, &mRemoteEndpointId); } - void OnCommissioningWindowOpened(NodeId deviceId, CHIP_ERROR status, chip::SetupPayload payload) override; - void OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) override; + void OnCommissioningWindowOpened(chip::NodeId deviceId, CHIP_ERROR status, chip::SetupPayload payload) override; + void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) override; /////////// CHIPCommand Interface ///////// CHIP_ERROR RunCommand() override { return RunCommand(mRemoteEndpointId); } @@ -136,7 +136,7 @@ class FabricSyncDeviceCommand : public CHIPCommand, public CommissioningWindowDe chip::EndpointId mRemoteEndpointId = chip::kInvalidEndpointId; chip::NodeId mAssignedNodeId = chip::kUndefinedNodeId; - CHIP_ERROR RunCommand(chip::EndpointId remoteId); + CHIP_ERROR RunCommand(chip::EndpointId remoteEndpointId); }; } // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index fafae0eb00115d..7546f503b55274 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -71,7 +71,11 @@ void DeviceManager::UpdateLastUsedNodeId(NodeId nodeId) void DeviceManager::SetRemoteBridgeNodeId(chip::NodeId nodeId) { mRemoteBridgeNodeId = nodeId; - mCommissionerControl.Init(PairingManager::Instance().CurrentCommissioner(), mRemoteBridgeNodeId, kAggregatorEndpointId); + + if (mRemoteBridgeNodeId != kUndefinedNodeId) + { + mCommissionerControl.Init(PairingManager::Instance().CurrentCommissioner(), mRemoteBridgeNodeId, kAggregatorEndpointId); + } } void DeviceManager::AddSyncedDevice(const Device & device) diff --git a/examples/fabric-admin/device_manager/PairingManager.cpp b/examples/fabric-admin/device_manager/PairingManager.cpp index 64e4fb4b56c64b..b13af2dbe46541 100644 --- a/examples/fabric-admin/device_manager/PairingManager.cpp +++ b/examples/fabric-admin/device_manager/PairingManager.cpp @@ -550,7 +550,12 @@ void PairingManager::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E if (err == CHIP_NO_ERROR) { // print to console - fprintf(stderr, "Device with Node ID: " ChipLogFormatX64 "has been successfully removed.\n", ChipLogValueX64(nodeId)); + fprintf(stderr, "Device with Node ID: " ChipLogFormatX64 " has been successfully removed.\n", ChipLogValueX64(nodeId)); + + if (self->mPairingDelegate) + { + self->mPairingDelegate->OnDeviceRemoved(nodeId, err); + } #if defined(PW_RPC_ENABLED) FabricIndex fabricIndex = self->CurrentCommissioner().GetFabricIndex(); diff --git a/examples/fabric-admin/rpc/RpcClient.cpp b/examples/fabric-admin/rpc/RpcClient.cpp index a3bc459235a0cb..f99d925d9d3da3 100644 --- a/examples/fabric-admin/rpc/RpcClient.cpp +++ b/examples/fabric-admin/rpc/RpcClient.cpp @@ -59,7 +59,7 @@ CHIP_ERROR WaitForResponse(CallType & call) } else { - fprintf(stderr, "RPC Response timed out!"); + fprintf(stderr, "RPC Response timed out!\n"); return CHIP_ERROR_TIMEOUT; } } From 4fce9b9e24452f99b634da74265ffe174c9cab83 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Wed, 6 Nov 2024 01:13:26 -0800 Subject: [PATCH 069/121] [Fabric-Sync] use namespace to isolate admin and bridge (#36374) --- examples/fabric-sync/admin/DeviceManager.cpp | 3 +++ examples/fabric-sync/admin/DeviceManager.h | 4 ++++ examples/fabric-sync/admin/PairingManager.cpp | 6 +++++- examples/fabric-sync/admin/PairingManager.h | 4 ++++ .../include/BridgedAdministratorCommissioning.h | 4 ++++ .../fabric-sync/bridge/include/BridgedDevice.h | 4 ++++ .../include/BridgedDeviceBasicInformationImpl.h | 4 ++++ .../bridge/include/BridgedDeviceManager.h | 12 ++++++++---- .../src/BridgedAdministratorCommissioning.cpp | 4 ++++ .../fabric-sync/bridge/src/BridgedDevice.cpp | 4 ++++ .../src/BridgedDeviceBasicInformationImpl.cpp | 4 ++++ .../bridge/src/BridgedDeviceManager.cpp | 15 ++++++++++----- examples/fabric-sync/main.cpp | 2 +- examples/fabric-sync/shell/AddBridgeCommand.cpp | 13 +++++++------ examples/fabric-sync/shell/AddBridgeCommand.h | 2 +- .../fabric-sync/shell/RemoveBridgeCommand.cpp | 16 ++++++++-------- examples/fabric-sync/shell/RemoveBridgeCommand.h | 2 +- 17 files changed, 76 insertions(+), 27 deletions(-) diff --git a/examples/fabric-sync/admin/DeviceManager.cpp b/examples/fabric-sync/admin/DeviceManager.cpp index 79f41d5dc11c17..3d2055444f92a8 100644 --- a/examples/fabric-sync/admin/DeviceManager.cpp +++ b/examples/fabric-sync/admin/DeviceManager.cpp @@ -26,6 +26,7 @@ using namespace chip; +namespace admin { // Define the static member DeviceManager DeviceManager::sInstance; @@ -109,3 +110,5 @@ void DeviceManager::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) ChipLogProgress(NotSpecified, "Synced device with NodeId:" ChipLogFormatX64 " has been removed.", ChipLogValueX64(deviceId)); } + +} // namespace admin diff --git a/examples/fabric-sync/admin/DeviceManager.h b/examples/fabric-sync/admin/DeviceManager.h index 5615df54a9cf32..866e0c20f6c333 100644 --- a/examples/fabric-sync/admin/DeviceManager.h +++ b/examples/fabric-sync/admin/DeviceManager.h @@ -23,6 +23,8 @@ #include #include +namespace admin { + class DeviceManager : public PairingDelegate { public: @@ -97,3 +99,5 @@ inline DeviceManager & DeviceMgr() } return DeviceManager::sInstance; } + +} // namespace admin diff --git a/examples/fabric-sync/admin/PairingManager.cpp b/examples/fabric-sync/admin/PairingManager.cpp index 06c1f2b99b7336..32317b4fa30e3a 100644 --- a/examples/fabric-sync/admin/PairingManager.cpp +++ b/examples/fabric-sync/admin/PairingManager.cpp @@ -29,6 +29,8 @@ using namespace ::chip; using namespace ::chip::Controller; +namespace admin { + namespace { CHIP_ERROR GetPayload(const char * setUpCode, SetupPayload & payload) @@ -451,7 +453,7 @@ void PairingManager::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E if (err == CHIP_NO_ERROR) { // print to console - fprintf(stderr, "Device with Node ID: " ChipLogFormatX64 "has been successfully removed.\n", ChipLogValueX64(nodeId)); + fprintf(stderr, "Device with Node ID: " ChipLogFormatX64 " has been successfully removed.\n", ChipLogValueX64(nodeId)); } else { @@ -548,3 +550,5 @@ CHIP_ERROR PairingManager::UnpairDevice(NodeId nodeId) } }); } + +} // namespace admin diff --git a/examples/fabric-sync/admin/PairingManager.h b/examples/fabric-sync/admin/PairingManager.h index 07cba7488154f8..5ef8a0761f7f28 100644 --- a/examples/fabric-sync/admin/PairingManager.h +++ b/examples/fabric-sync/admin/PairingManager.h @@ -24,6 +24,8 @@ #include #include +namespace admin { + // Constants constexpr uint16_t kMaxManualCodeLength = 22; @@ -201,3 +203,5 @@ class PairingManager : public chip::Controller::DevicePairingDelegate, chip::Platform::UniquePtr mCurrentFabricRemover; chip::Callback::Callback mCurrentFabricRemoveCallback; }; + +} // namespace admin diff --git a/examples/fabric-sync/bridge/include/BridgedAdministratorCommissioning.h b/examples/fabric-sync/bridge/include/BridgedAdministratorCommissioning.h index 06fd9026d44225..7b5711d39557e9 100644 --- a/examples/fabric-sync/bridge/include/BridgedAdministratorCommissioning.h +++ b/examples/fabric-sync/bridge/include/BridgedAdministratorCommissioning.h @@ -20,6 +20,8 @@ #include #include +namespace bridge { + /** * @brief CADMIN cluster implementation for handling attribute interactions of bridged device endpoints. * @@ -56,3 +58,5 @@ class BridgedAdministratorCommissioning : public chip::app::AttributeAccessInter // to reflect this change. chip::app::AttributeAccessInterface * mOriginalAttributeInterface = nullptr; }; + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/include/BridgedDevice.h b/examples/fabric-sync/bridge/include/BridgedDevice.h index d2c5a64b9ef4b7..ed5c9710624225 100644 --- a/examples/fabric-sync/bridge/include/BridgedDevice.h +++ b/examples/fabric-sync/bridge/include/BridgedDevice.h @@ -23,6 +23,8 @@ #include +namespace bridge { + class BridgedDevice { public: @@ -90,3 +92,5 @@ class BridgedDevice BridgedAttributes mAttributes; AdminCommissioningAttributes mAdminCommissioningAttributes; }; + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/include/BridgedDeviceBasicInformationImpl.h b/examples/fabric-sync/bridge/include/BridgedDeviceBasicInformationImpl.h index 23403438ab2be8..f57f7d0362ae73 100644 --- a/examples/fabric-sync/bridge/include/BridgedDeviceBasicInformationImpl.h +++ b/examples/fabric-sync/bridge/include/BridgedDeviceBasicInformationImpl.h @@ -18,6 +18,8 @@ #include #include +namespace bridge { + class BridgedDeviceBasicInformationImpl : public chip::app::AttributeAccessInterface { public: @@ -30,3 +32,5 @@ class BridgedDeviceBasicInformationImpl : public chip::app::AttributeAccessInter CHIP_ERROR Read(const chip::app::ConcreteReadAttributePath & path, chip::app::AttributeValueEncoder & encoder) override; CHIP_ERROR Write(const chip::app::ConcreteDataAttributePath & path, chip::app::AttributeValueDecoder & decoder) override; }; + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/include/BridgedDeviceManager.h b/examples/fabric-sync/bridge/include/BridgedDeviceManager.h index 127898fc5b2fab..6d172767662a69 100644 --- a/examples/fabric-sync/bridge/include/BridgedDeviceManager.h +++ b/examples/fabric-sync/bridge/include/BridgedDeviceManager.h @@ -24,6 +24,8 @@ #include +namespace bridge { + class BridgedDeviceManager { public: @@ -52,9 +54,9 @@ class BridgedDeviceManager * * @param dev A pointer to the device to be added. * @param parentEndpointId The parent endpoint ID. Defaults to an invalid endpoint ID. - * @return int The index of the dynamic endpoint if successful, nullopt otherwise + * @return uint16_t The index of the dynamic endpoint if successful, nullopt otherwise */ - std::optional AddDeviceEndpoint(std::unique_ptr dev, + std::optional AddDeviceEndpoint(std::unique_ptr dev, chip::EndpointId parentEndpointId = chip::kInvalidEndpointId); /** @@ -100,9 +102,9 @@ class BridgedDeviceManager * found, it removes the dynamic endpoint. * * @param scopedNodeId The ScopedNodeId of the device to be removed. - * @return unsigned of the index of the removed dynamic endpoint if successful, nullopt otherwise. + * @return uint16_t of the index of the removed dynamic endpoint if successful, nullopt otherwise. */ - std::optional RemoveDeviceByScopedNodeId(chip::ScopedNodeId scopedNodeId); + std::optional RemoveDeviceByScopedNodeId(chip::ScopedNodeId scopedNodeId); /** * Finds the device with the given unique id (if any) @@ -134,3 +136,5 @@ inline BridgedDeviceManager & BridgeDeviceMgr() { return BridgedDeviceManager::sInstance; } + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/src/BridgedAdministratorCommissioning.cpp b/examples/fabric-sync/bridge/src/BridgedAdministratorCommissioning.cpp index a0d87cbb3b81ef..3299df75a9039e 100644 --- a/examples/fabric-sync/bridge/src/BridgedAdministratorCommissioning.cpp +++ b/examples/fabric-sync/bridge/src/BridgedAdministratorCommissioning.cpp @@ -26,6 +26,8 @@ using namespace chip::app; using namespace chip::app::Clusters; using namespace chip::app::Clusters::AdministratorCommissioning; +namespace bridge { + CHIP_ERROR BridgedAdministratorCommissioning::Init() { // We expect initialization after emberAfInit(). This allows us to unregister the existing @@ -79,3 +81,5 @@ CHIP_ERROR BridgedAdministratorCommissioning::Read(const ConcreteReadAttributePa return CHIP_NO_ERROR; } + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/src/BridgedDevice.cpp b/examples/fabric-sync/bridge/src/BridgedDevice.cpp index f462d1cce6efd5..bd88c89145930e 100644 --- a/examples/fabric-sync/bridge/src/BridgedDevice.cpp +++ b/examples/fabric-sync/bridge/src/BridgedDevice.cpp @@ -27,6 +27,8 @@ using namespace chip; using namespace chip::app::Clusters::Actions; +namespace bridge { + BridgedDevice::BridgedDevice(ScopedNodeId scopedNodeId) { mReachable = false; @@ -116,3 +118,5 @@ void BridgedDevice::SetAdminCommissioningAttributes(const AdminCommissioningAttr } }); } + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/src/BridgedDeviceBasicInformationImpl.cpp b/examples/fabric-sync/bridge/src/BridgedDeviceBasicInformationImpl.cpp index 7fa48a4a158ddd..d021671c8bf1bd 100644 --- a/examples/fabric-sync/bridge/src/BridgedDeviceBasicInformationImpl.cpp +++ b/examples/fabric-sync/bridge/src/BridgedDeviceBasicInformationImpl.cpp @@ -29,6 +29,8 @@ using namespace ::chip; using namespace ::chip::app; using namespace ::chip::app::Clusters; +namespace bridge { + CHIP_ERROR BridgedDeviceBasicInformationImpl::Read(const ConcreteReadAttributePath & path, AttributeValueEncoder & encoder) { // Registration is done for the bridged device basic information only @@ -105,3 +107,5 @@ CHIP_ERROR BridgedDeviceBasicInformationImpl::Write(const ConcreteDataAttributeP return CHIP_ERROR_INVALID_ARGUMENT; } + +} // namespace bridge diff --git a/examples/fabric-sync/bridge/src/BridgedDeviceManager.cpp b/examples/fabric-sync/bridge/src/BridgedDeviceManager.cpp index 0265f912027ca0..09c1b643c00efb 100644 --- a/examples/fabric-sync/bridge/src/BridgedDeviceManager.cpp +++ b/examples/fabric-sync/bridge/src/BridgedDeviceManager.cpp @@ -45,6 +45,8 @@ using namespace chip::Transport; using namespace chip::DeviceLayer; using namespace chip::app::Clusters; +namespace bridge { + namespace { constexpr uint8_t kMaxRetries = 10; @@ -184,7 +186,7 @@ void BridgedDeviceManager::Init() mCurrentEndpointId = mFirstDynamicEndpointId; } -std::optional BridgedDeviceManager::AddDeviceEndpoint(std::unique_ptr dev, +std::optional BridgedDeviceManager::AddDeviceEndpoint(std::unique_ptr dev, chip::EndpointId parentEndpointId) { EmberAfEndpointType * ep = dev->IsIcd() ? &sIcdBridgedNodeEndpoint : &sBridgedNodeEndpoint; @@ -194,6 +196,8 @@ std::optional BridgedDeviceManager::AddDeviceEndpoint(std::unique_ptr< // TODO: this shares data version among different clusters, which seems incorrect const chip::Span & dataVersionStorage = Span(sBridgedNodeDataVersions); + assertChipStackLockedByCurrentThread(); + if (dev->GetBridgedAttributes().uniqueId.empty()) { dev->SetUniqueId(GenerateUniqueId()); @@ -204,7 +208,7 @@ std::optional BridgedDeviceManager::AddDeviceEndpoint(std::unique_ptr< return std::nullopt; } - for (unsigned index = 0; index < CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; index++) + for (uint16_t index = 0; index < CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; index++) { if (mDevices[index]) { @@ -213,7 +217,6 @@ std::optional BridgedDeviceManager::AddDeviceEndpoint(std::unique_ptr< for (int retryCount = 0; retryCount < kMaxRetries; retryCount++) { - DeviceLayer::StackLock lock; dev->SetEndpointId(mCurrentEndpointId); dev->SetParentEndpointId(parentEndpointId); CHIP_ERROR err = @@ -327,9 +330,9 @@ BridgedDevice * BridgedDeviceManager::GetDeviceByScopedNodeId(chip::ScopedNodeId return nullptr; } -std::optional BridgedDeviceManager::RemoveDeviceByScopedNodeId(chip::ScopedNodeId scopedNodeId) +std::optional BridgedDeviceManager::RemoveDeviceByScopedNodeId(chip::ScopedNodeId scopedNodeId) { - for (unsigned index = 0; index < CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; ++index) + for (uint16_t index = 0; index < CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT; ++index) { if (mDevices[index] && mDevices[index]->GetScopedNodeId() == scopedNodeId) { @@ -343,3 +346,5 @@ std::optional BridgedDeviceManager::RemoveDeviceByScopedNodeId(chip::S } return std::nullopt; } + +} // namespace bridge diff --git a/examples/fabric-sync/main.cpp b/examples/fabric-sync/main.cpp index 45e0ce388ef0ff..3cd5ab8c20f1c9 100644 --- a/examples/fabric-sync/main.cpp +++ b/examples/fabric-sync/main.cpp @@ -99,7 +99,7 @@ int main(int argc, char * argv[]) Shell::RegisterCommands(); #endif - CHIP_ERROR err = PairingManager::Instance().Init(GetDeviceCommissioner()); + CHIP_ERROR err = admin::PairingManager::Instance().Init(GetDeviceCommissioner()); if (err != CHIP_NO_ERROR) { ChipLogProgress(NotSpecified, "Failed to init PairingManager: %s ", ErrorStr(err)); diff --git a/examples/fabric-sync/shell/AddBridgeCommand.cpp b/examples/fabric-sync/shell/AddBridgeCommand.cpp index d02ad9f58dba11..09246c11528e7e 100644 --- a/examples/fabric-sync/shell/AddBridgeCommand.cpp +++ b/examples/fabric-sync/shell/AddBridgeCommand.cpp @@ -48,11 +48,12 @@ void AddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) if (err == CHIP_NO_ERROR) { - DeviceMgr().SetRemoteBridgeNodeId(mBridgeNodeId); + admin::DeviceMgr().SetRemoteBridgeNodeId(mBridgeNodeId); + ChipLogProgress(NotSpecified, "Successfully paired bridge device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mBridgeNodeId)); - DeviceMgr().UpdateLastUsedNodeId(mBridgeNodeId); + admin::DeviceMgr().UpdateLastUsedNodeId(mBridgeNodeId); } else { @@ -65,16 +66,16 @@ void AddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) CHIP_ERROR AddBridgeCommand::RunCommand() { - if (DeviceMgr().IsFabricSyncReady()) + if (admin::DeviceMgr().IsFabricSyncReady()) { // print to console fprintf(stderr, "Remote Fabric Bridge has already been configured.\n"); - return CHIP_ERROR_BUSY; + return CHIP_NO_ERROR; } - PairingManager::Instance().SetCommissioningDelegate(this); + admin::PairingManager::Instance().SetCommissioningDelegate(this); - return DeviceMgr().PairRemoteFabricBridge(mBridgeNodeId, mSetupPINCode, mRemoteAddr, mRemotePort); + return admin::DeviceMgr().PairRemoteFabricBridge(mBridgeNodeId, mSetupPINCode, mRemoteAddr, mRemotePort); } } // namespace commands diff --git a/examples/fabric-sync/shell/AddBridgeCommand.h b/examples/fabric-sync/shell/AddBridgeCommand.h index d4b2c16f1e21d9..48c1830260421e 100644 --- a/examples/fabric-sync/shell/AddBridgeCommand.h +++ b/examples/fabric-sync/shell/AddBridgeCommand.h @@ -23,7 +23,7 @@ namespace commands { -class AddBridgeCommand : public Command, public CommissioningDelegate +class AddBridgeCommand : public Command, public admin::CommissioningDelegate { public: AddBridgeCommand(chip::NodeId nodeId, uint32_t setupPINCode, const char * remoteAddr, uint16_t remotePort); diff --git a/examples/fabric-sync/shell/RemoveBridgeCommand.cpp b/examples/fabric-sync/shell/RemoveBridgeCommand.cpp index 9e8f1ed5fa8cd5..2eaaf6fc34476f 100644 --- a/examples/fabric-sync/shell/RemoveBridgeCommand.cpp +++ b/examples/fabric-sync/shell/RemoveBridgeCommand.cpp @@ -35,9 +35,10 @@ void RemoveBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) if (err == CHIP_NO_ERROR) { - DeviceMgr().SetRemoteBridgeNodeId(kUndefinedNodeId); - ChipLogProgress(NotSpecified, "Successfully removed bridge device: NodeId: " ChipLogFormatX64, - ChipLogValueX64(mBridgeNodeId)); + admin::DeviceMgr().SetRemoteBridgeNodeId(kUndefinedNodeId); + + // print to console + fprintf(stderr, "Successfully removed bridge device: NodeId: " ChipLogFormatX64 "\n", ChipLogValueX64(mBridgeNodeId)); } else { @@ -50,21 +51,20 @@ void RemoveBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) CHIP_ERROR RemoveBridgeCommand::RunCommand() { - NodeId bridgeNodeId = DeviceMgr().GetRemoteBridgeNodeId(); + NodeId bridgeNodeId = admin::DeviceMgr().GetRemoteBridgeNodeId(); if (bridgeNodeId == kUndefinedNodeId) { // print to console fprintf(stderr, "Remote Fabric Bridge is not configured yet, nothing to remove.\n"); - return CHIP_ERROR_BUSY; + return CHIP_NO_ERROR; } mBridgeNodeId = bridgeNodeId; - PairingManager::Instance().SetPairingDelegate(this); - DeviceMgr().UnpairRemoteFabricBridge(); + admin::PairingManager::Instance().SetPairingDelegate(this); - return CHIP_NO_ERROR; + return admin::DeviceMgr().UnpairRemoteFabricBridge(); } } // namespace commands diff --git a/examples/fabric-sync/shell/RemoveBridgeCommand.h b/examples/fabric-sync/shell/RemoveBridgeCommand.h index 401a5390be8fd9..b0e4b33d52ce8b 100644 --- a/examples/fabric-sync/shell/RemoveBridgeCommand.h +++ b/examples/fabric-sync/shell/RemoveBridgeCommand.h @@ -23,7 +23,7 @@ namespace commands { -class RemoveBridgeCommand : public Command, public PairingDelegate +class RemoveBridgeCommand : public Command, public admin::PairingDelegate { public: void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; From 380ddd685b3cd5c88baccb1ae04ccd0a6690b3e0 Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Wed, 6 Nov 2024 13:28:43 +0100 Subject: [PATCH 070/121] [darwin-framework-tool] Some macosx variants does not use the right output dir (#36384) --- examples/darwin-framework-tool/BUILD.gn | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/examples/darwin-framework-tool/BUILD.gn b/examples/darwin-framework-tool/BUILD.gn index f5333c9f42c4e1..fbe1c4d6f82954 100644 --- a/examples/darwin-framework-tool/BUILD.gn +++ b/examples/darwin-framework-tool/BUILD.gn @@ -53,7 +53,9 @@ sdk_build_dir_suffix = "" if (getenv("SDKROOT") != "") { sdk = getenv("SDKROOT") sdk_root_parts = string_split(getenv("SDKROOT"), ".") - sdk_build_dir_suffix = "-${sdk_root_parts[0]}" + if (sdk_root_parts[0] != "macosx") { + sdk_build_dir_suffix = "-${sdk_root_parts[0]}" + } } output_sdk_type = "Debug${sdk_build_dir_suffix}" @@ -134,7 +136,7 @@ action("build-darwin-framework") { "${root_out_dir}/macos_framework_output/Build", ] - if (sdk == "macosx") { + if (sdk == "macosx" || sdk_root_parts[0] == "macosx") { outputs += [ "${root_out_dir}/macos_framework_output/Build/Intermediates.noindex/Matter.build/${output_sdk_type}/Matter.build/out/lib/libCHIP.a" ] } } @@ -285,11 +287,12 @@ executable("darwin-framework-tool") { "Foundation.framework", "CoreBluetooth.framework", "Network.framework", + "IOKit.framework", ] # Other SDKs are linked statically to Matter.framework but the macosx SDK is linked dynamically but needs some symbols that are # not exposed by the dylib. - if (sdk == "macosx") { + if (sdk == "macosx" || sdk_root_parts[0] == "macosx") { libs = [ "${root_out_dir}/macos_framework_output/Build/Intermediates.noindex/Matter.build/${output_sdk_type}/Matter.build/out/lib/libCHIP.a" ] } From 84efd4963bfdbcc95a8e6c14299c1f0bd2e408eb Mon Sep 17 00:00:00 2001 From: Rohan Sahay <103027015+rosahay-silabs@users.noreply.github.com> Date: Wed, 6 Nov 2024 18:05:57 +0530 Subject: [PATCH 071/121] [Silabs] Adds fix for BTN low power mode for SiWx917 SoC and power manager (#35808) * Decouple UART power requirement handler * Adds refactored BTN handler based on power manager * Fixed incorrect API * Adds changes for interrupt * Replace use of RSI_xx APIs with sl_si91x_xx APIs * Refactor button event handling and UART power requirement handler * Adds comments based on the coding standards Reduce into inline functions * Renaming sl_btn0 -> btn0 * Adds changes to optimize code * Adds CPP define in header * Update function comments * Replace with more readable condition * Updates document to add BTN0 screen cycle action (#323) * Restyled by prettier-markdown * Adds compilation fix for EFR32 boards * Addressing comments --------- Co-authored-by: Restyled.io --- .../air-quality-sensor-app/silabs/README.md | 1 + examples/dishwasher-app/silabs/README.md | 2 + .../energy-management-app/silabs/README.md | 1 + examples/light-switch-app/silabs/README.md | 1 + examples/lighting-app/silabs/README.md | 1 + examples/lit-icd-app/silabs/README.md | 1 + examples/lock-app/silabs/README.md | 1 + examples/platform/silabs/MatterConfig.cpp | 4 +- .../silabs/SiWx917/SiWxPlatformInterface.h | 73 +++++++++++++++++++ .../silabs/SiWx917/SiWxWifiInterface.cpp | 31 +++++--- .../silabs/wifi/WifiInterfaceAbstraction.h | 3 - examples/pump-app/silabs/README.md | 1 + examples/smoke-co-alarm-app/silabs/README.md | 1 + examples/thermostat/silabs/README.md | 1 + .../platformAbstraction/WiseMcuSpam.cpp | 14 ++-- third_party/silabs/SiWx917_sdk.gni | 5 +- 16 files changed, 117 insertions(+), 24 deletions(-) create mode 100644 examples/platform/silabs/SiWx917/SiWxPlatformInterface.h diff --git a/examples/air-quality-sensor-app/silabs/README.md b/examples/air-quality-sensor-app/silabs/README.md index 7279e23457ef01..b2687c6cadb8b0 100644 --- a/examples/air-quality-sensor-app/silabs/README.md +++ b/examples/air-quality-sensor-app/silabs/README.md @@ -257,6 +257,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/dishwasher-app/silabs/README.md b/examples/dishwasher-app/silabs/README.md index 9a8a102cbd147d..ffc56f3580697b 100644 --- a/examples/dishwasher-app/silabs/README.md +++ b/examples/dishwasher-app/silabs/README.md @@ -10,6 +10,7 @@ An example showing the use of Matter on the Silicon Labs EFR32 MG24 boards. - [Flashing the Application](#flashing-the-application) - [Viewing Logging Output](#viewing-logging-output) - [Running the Complete Example](#running-the-complete-example) + - [Commissioning](#commissioning)
@@ -211,6 +212,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/energy-management-app/silabs/README.md b/examples/energy-management-app/silabs/README.md index 5c1955a5071f3c..09253afa55524c 100644 --- a/examples/energy-management-app/silabs/README.md +++ b/examples/energy-management-app/silabs/README.md @@ -257,6 +257,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/light-switch-app/silabs/README.md b/examples/light-switch-app/silabs/README.md index 898f8e8f299112..75411dd3055e72 100644 --- a/examples/light-switch-app/silabs/README.md +++ b/examples/light-switch-app/silabs/README.md @@ -263,6 +263,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/lighting-app/silabs/README.md b/examples/lighting-app/silabs/README.md index 7052d4f71221c3..b783a6c328fac1 100644 --- a/examples/lighting-app/silabs/README.md +++ b/examples/lighting-app/silabs/README.md @@ -245,6 +245,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/lit-icd-app/silabs/README.md b/examples/lit-icd-app/silabs/README.md index 4d1dee045c2e40..1b94dc5b902b73 100644 --- a/examples/lit-icd-app/silabs/README.md +++ b/examples/lit-icd-app/silabs/README.md @@ -250,6 +250,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/lock-app/silabs/README.md b/examples/lock-app/silabs/README.md index 7b4f7fdbdfaddf..0688f1ce70e93c 100644 --- a/examples/lock-app/silabs/README.md +++ b/examples/lock-app/silabs/README.md @@ -277,6 +277,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/platform/silabs/MatterConfig.cpp b/examples/platform/silabs/MatterConfig.cpp index 43bd2c181fd044..c7d4487cfc4f5d 100644 --- a/examples/platform/silabs/MatterConfig.cpp +++ b/examples/platform/silabs/MatterConfig.cpp @@ -41,6 +41,7 @@ #endif #if defined(SLI_SI91X_MCU_INTERFACE) && SLI_SI91X_MCU_INTERFACE == 1 +#include "SiWxPlatformInterface.h" #include "WifiInterfaceAbstraction.h" #endif // SLI_SI91X_MCU_INTERFACE @@ -328,6 +329,7 @@ CHIP_ERROR SilabsMatterConfig::InitWiFi(void) extern "C" void vApplicationIdleHook(void) { #if (SLI_SI91X_MCU_INTERFACE && CHIP_CONFIG_ENABLE_ICD_SERVER) - sl_si91x_invoke_btn_press_event(); + SiWxPlatformInterface::sl_si91x_btn_event_handler(); + SiWxPlatformInterface::sl_si91x_uart_power_requirement_handler(); #endif } diff --git a/examples/platform/silabs/SiWx917/SiWxPlatformInterface.h b/examples/platform/silabs/SiWx917/SiWxPlatformInterface.h new file mode 100644 index 00000000000000..879ca3013c7b41 --- /dev/null +++ b/examples/platform/silabs/SiWx917/SiWxPlatformInterface.h @@ -0,0 +1,73 @@ +/* + * + * Copyright (c) 2024 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. + */ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif +#if CHIP_CONFIG_ENABLE_ICD_SERVER +#if SLI_SI91X_MCU_INTERFACE +#include "sl_si91x_button.h" +#include "sl_si91x_button_pin_config.h" +#include "sl_si91x_driver_gpio.h" +/** + * @brief invoked when button press event is received when in sleep + * @param[in] pin_intr GPIO pin interrupt number. + * @return none. + * @note this is a callback from the Wiseconnect SDK + */ +void gpio_uulp_pin_interrupt_callback(uint32_t pin_intr); +#endif // SLI_SI91X_MCU_INTERFACE +#endif // CHIP_CONFIG_ENABLE_ICD_SERVER +#ifdef __cplusplus +} +#endif + +namespace chip { +namespace DeviceLayer { +namespace Silabs { +namespace SiWxPlatformInterface { + +#if CHIP_CONFIG_ENABLE_ICD_SERVER +#if SLI_SI91X_MCU_INTERFACE +/** + * @brief Required to invoke button press event during sleep as falling edge is not detected + * @param[in] none. + * @note flow is GPIO wakeup due to BTN0 press -> check button state in idle task required as the GPIO interrupt is not + * detected during sleep for BUTTON RELEASED + */ +inline void sl_si91x_btn_event_handler() +{ + sl_button_on_change(SL_BUTTON_BTN0_NUMBER, + (sl_si91x_gpio_get_uulp_npss_pin(SL_BUTTON_BTN0_PIN) == LOW) ? BUTTON_PRESSED : BUTTON_RELEASED); +} + +/** + * @brief Required to enable MATTER shell UART with ICD feature flag + * @param[in] none. + * @note this requires hardware jumping of the GPIO PINs to work with the baseboard. + */ +void sl_si91x_uart_power_requirement_handler(); +#endif // SLI_SI91X_MCU_INTERFACE +#endif // CHIP_CONFIG_ENABLE_ICD_SERVER +} // namespace SiWxPlatformInterface +} // namespace Silabs +} // namespace DeviceLayer +} // namespace chip diff --git a/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp b/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp index 26a16f9aa87f8f..2390365384481d 100644 --- a/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp +++ b/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp @@ -74,8 +74,11 @@ extern "C" { #endif #if CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE +#include "SiWxPlatformInterface.h" + #include "rsi_rom_power_save.h" -#include "sl_si91x_button_pin_config.h" +#include "sl_gpio_board.h" +#include "sl_si91x_driver_gpio.h" #include "sl_si91x_power_manager.h" #endif // CHIP_CONFIG_ENABLE_ICD_SERVER && SLI_SI91X_MCU_INTERFACE @@ -522,23 +525,27 @@ int32_t sl_wifi_platform_disconnect(void) #if CHIP_CONFIG_ENABLE_ICD_SERVER #if SLI_SI91X_MCU_INTERFACE -// Required to invoke button press event during sleep as falling edge is not detected -void sl_si91x_invoke_btn_press_event(void) +void gpio_uulp_pin_interrupt_callback(uint32_t pin_intr) { - // TODO: should be removed once we are getting the press interrupt for button 0 with sleep - if (!RSI_NPSSGPIO_GetPin(SL_BUTTON_BTN0_PIN) && !btn0_pressed) - { - sl_button_on_change(SL_BUTTON_BTN0_NUMBER, 1 /* Button Pressed */); - btn0_pressed = true; - } - if (RSI_NPSSGPIO_GetPin(SL_BUTTON_BTN0_PIN)) + // UULP_GPIO_2 is used to detect the button 0 press + VerifyOrReturn(pin_intr == RTE_UULP_GPIO_2_PIN, ChipLogError(DeviceLayer, "invalid pin interrupt: %ld", pin_intr)); + sl_status_t status = SL_STATUS_OK; + uint8_t pin_intr_status = sl_si91x_gpio_get_uulp_npss_pin(pin_intr); + if (pin_intr_status == LOW) { - btn0_pressed = false; + // BTN_0 is pressed + // NOTE: the GPIO is masked since the interrupt is invoked before scheduler is started, thus this is required to hand over + // control to scheduler, the PIN is unmasked in the power manager flow before going to sleep + status = sl_si91x_gpio_driver_mask_uulp_npss_interrupt(BIT(pin_intr)); + VerifyOrReturn(status == SL_STATUS_OK, ChipLogError(DeviceLayer, "failed to mask interrupt: %ld", status)); } +} +void chip::DeviceLayer::Silabs::SiWxPlatformInterface::sl_si91x_uart_power_requirement_handler(void) +{ #ifdef ENABLE_CHIP_SHELL // Checking the UULP PIN 1 status to reinit the UART and not allow the device to go to sleep - if (RSI_NPSSGPIO_GetPin(RTE_UULP_GPIO_1_PIN)) + if (sl_si91x_gpio_get_uulp_npss_pin(RTE_UULP_GPIO_1_PIN)) { if (!ps_requirement_added) { diff --git a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h index a26ead2579b16a..f0383b20e25f85 100644 --- a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h +++ b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h @@ -105,9 +105,6 @@ extern "C" { sl_status_t sl_matter_wifi_platform_init(void); #if CHIP_CONFIG_ENABLE_ICD_SERVER -#if SLI_SI91X_MCU_INTERFACE -void sl_si91x_invoke_btn_press_event(); -#endif // SLI_SI91X_MCU_INTERFACE #if SLI_SI917 int32_t wfx_rsi_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_si91x_performance_profile_t sl_si91x_wifi_state); #else diff --git a/examples/pump-app/silabs/README.md b/examples/pump-app/silabs/README.md index 70d83e4de5f70c..0ca0f43a7a5784 100644 --- a/examples/pump-app/silabs/README.md +++ b/examples/pump-app/silabs/README.md @@ -242,6 +242,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/smoke-co-alarm-app/silabs/README.md b/examples/smoke-co-alarm-app/silabs/README.md index 7928107b35de47..520056661d8b3d 100644 --- a/examples/smoke-co-alarm-app/silabs/README.md +++ b/examples/smoke-co-alarm-app/silabs/README.md @@ -260,6 +260,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/examples/thermostat/silabs/README.md b/examples/thermostat/silabs/README.md index 3205352bf07f1c..681618545b7a1a 100644 --- a/examples/thermostat/silabs/README.md +++ b/examples/thermostat/silabs/README.md @@ -251,6 +251,7 @@ combination with JLinkRTTClient as follows: - _Press and Release_ : Start, or restart, BLE advertisement in fast mode. It will advertise in this mode for 30 seconds. The device will then switch to a slower interval advertisement. After 15 minutes, the advertisement stops. + Additionally, it will cycle through the QR code, application status screen and device status screen, respectively. - _Pressed and hold for 6 s_ : Initiates the factory reset of the device. Releasing the button within the 6-second window cancels the factory reset diff --git a/src/platform/silabs/platformAbstraction/WiseMcuSpam.cpp b/src/platform/silabs/platformAbstraction/WiseMcuSpam.cpp index cf60cf5c5892fe..317d59074af323 100644 --- a/src/platform/silabs/platformAbstraction/WiseMcuSpam.cpp +++ b/src/platform/silabs/platformAbstraction/WiseMcuSpam.cpp @@ -159,21 +159,21 @@ void sl_button_on_change(uint8_t btn, uint8_t btnAction) // Currently the btn0 is pull-up resistor due to which is sends a release event on every wakeup if (btn == SL_BUTTON_BTN0_NUMBER) { - if (btnAction == BUTTON_PRESSED) + // if the btn was not pressed and only a release event came, ignore it + // if the btn was already pressed and another press event came, ignore it + // essentially, if both of them are in the same state then ignore it. + VerifyOrReturn(btnAction != btn0_pressed); + + if ((btnAction == BUTTON_PRESSED) && (btn0_pressed == false)) { btn0_pressed = true; } - else if ((btnAction == BUTTON_RELEASED) && (btn0_pressed == false)) - { - // if the btn was not pressed and only a release event came, ignore it - return; - } else if ((btnAction == BUTTON_RELEASED) && (btn0_pressed == true)) { btn0_pressed = false; } } -#endif /* SL_ICD_ENABLED */ +#endif // SL_ICD_ENABLED if (Silabs::GetPlatform().mButtonCallback == nullptr) { return; diff --git a/third_party/silabs/SiWx917_sdk.gni b/third_party/silabs/SiWx917_sdk.gni index ab94c6372d18e0..94763d8311dce6 100644 --- a/third_party/silabs/SiWx917_sdk.gni +++ b/third_party/silabs/SiWx917_sdk.gni @@ -321,9 +321,12 @@ template("siwx917_sdk") { "SL_ACTIVE_MODE_DURATION_MS=${sl_active_mode_duration_ms}", "SL_IDLE_MODE_DURATION_S=${sl_idle_mode_duration_s}", "SL_ICD_SUPPORTED_CLIENTS_PER_FABRIC=${sl_icd_supported_clients_per_fabric}", - "SL_SI91X_NPSS_GPIO_BTN_HANDLER=1", "SL_SI91X_POWER_MANAGER_UC_AVAILABLE=1", "SL_SI91X_TICKLESS_MODE=1", + + # Enable Wakeup source for ICD + "SL_ENABLE_GPIO_WAKEUP_SOURCE=1", + "ENABLE_NPSS_GPIO_2=1", ] } From da2b7670547d4c371a3cac07a4148e210f4a5aa0 Mon Sep 17 00:00:00 2001 From: pankore <86098180+pankore@users.noreply.github.com> Date: Wed, 6 Nov 2024 21:10:45 +0800 Subject: [PATCH 072/121] [Ameba] Update Docker image (#36383) --- integrations/docker/images/base/chip-build/version | 2 +- integrations/docker/images/stage-2/chip-build-ameba/Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/integrations/docker/images/base/chip-build/version b/integrations/docker/images/base/chip-build/version index 3c23aaad931620..2546ff1921d2dc 100644 --- a/integrations/docker/images/base/chip-build/version +++ b/integrations/docker/images/base/chip-build/version @@ -1 +1 @@ -90 : [Telink] Update Docker image (Zephyr update) +91 : [Ameba] Update matter timers and add more examples diff --git a/integrations/docker/images/stage-2/chip-build-ameba/Dockerfile b/integrations/docker/images/stage-2/chip-build-ameba/Dockerfile index 93217c332ef671..d3f8dadcb5332a 100644 --- a/integrations/docker/images/stage-2/chip-build-ameba/Dockerfile +++ b/integrations/docker/images/stage-2/chip-build-ameba/Dockerfile @@ -11,7 +11,7 @@ RUN set -x \ # Setup Ameba ARG AMEBA_DIR=/opt/ameba -ARG TAG_NAME=ameba_update_2024_03_22 +ARG TAG_NAME=ameba_update_2024_11_05 RUN set -x \ && apt-get update \ && mkdir ${AMEBA_DIR} \ From 6cf10d7baee0429b1ec12a8ace1152cbf2956257 Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Wed, 6 Nov 2024 10:57:35 -0500 Subject: [PATCH 073/121] Set coupleColorTempToLevelMinMireds at the same value than ColorTempPhysicalMinMireds (#36372) --- .../lighting-app/silabs/data_model/lighting-thread-app.matter | 2 +- examples/lighting-app/silabs/data_model/lighting-thread-app.zap | 2 +- .../lighting-app/silabs/data_model/lighting-wifi-app.matter | 2 +- examples/lighting-app/silabs/data_model/lighting-wifi-app.zap | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/lighting-app/silabs/data_model/lighting-thread-app.matter b/examples/lighting-app/silabs/data_model/lighting-thread-app.matter index 49684770a3bcaa..9fb02976f031d5 100644 --- a/examples/lighting-app/silabs/data_model/lighting-thread-app.matter +++ b/examples/lighting-app/silabs/data_model/lighting-thread-app.matter @@ -2672,7 +2672,7 @@ endpoint 1 { ram attribute colorCapabilities default = 0x1F; ram attribute colorTempPhysicalMinMireds default = 0x009A; ram attribute colorTempPhysicalMaxMireds default = 0x01C6; - ram attribute coupleColorTempToLevelMinMireds; + ram attribute coupleColorTempToLevelMinMireds default = 0x009A; persist attribute startUpColorTemperatureMireds default = 0x00FA; callback attribute generatedCommandList; callback attribute acceptedCommandList; diff --git a/examples/lighting-app/silabs/data_model/lighting-thread-app.zap b/examples/lighting-app/silabs/data_model/lighting-thread-app.zap index 62cc5c49eb9ac3..6e7931fbcf0f68 100644 --- a/examples/lighting-app/silabs/data_model/lighting-thread-app.zap +++ b/examples/lighting-app/silabs/data_model/lighting-thread-app.zap @@ -5022,7 +5022,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "0x009A", "reportable": 1, "minInterval": 0, "maxInterval": 65344, diff --git a/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter b/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter index 003a38e52c0214..1619fc9622caf4 100644 --- a/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter +++ b/examples/lighting-app/silabs/data_model/lighting-wifi-app.matter @@ -2964,7 +2964,7 @@ endpoint 1 { ram attribute colorCapabilities default = 0x1F; ram attribute colorTempPhysicalMinMireds default = 0x009A; ram attribute colorTempPhysicalMaxMireds default = 0x01C6; - ram attribute coupleColorTempToLevelMinMireds; + ram attribute coupleColorTempToLevelMinMireds default = 0x009A; persist attribute startUpColorTemperatureMireds default = 0x00FA; ram attribute featureMap default = 0x1F; ram attribute clusterRevision default = 7; diff --git a/examples/lighting-app/silabs/data_model/lighting-wifi-app.zap b/examples/lighting-app/silabs/data_model/lighting-wifi-app.zap index 94397579a0a7d6..a0b64b71934eea 100644 --- a/examples/lighting-app/silabs/data_model/lighting-wifi-app.zap +++ b/examples/lighting-app/silabs/data_model/lighting-wifi-app.zap @@ -4797,7 +4797,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "", + "defaultValue": "0x009A", "reportable": 1, "minInterval": 0, "maxInterval": 65344, From 2af51b0120b88959f896bbac26b21ea8f2c64bd2 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Wed, 6 Nov 2024 14:50:35 -0500 Subject: [PATCH 074/121] Switch string for cirque lookup. (#36407) This is after https://github.com/openthread/ot-br-posix/pull/2574 removed the log line we were looking for. Co-authored-by: Andrei Litvin --- src/test_driver/linux-cirque/helper/CHIPTestBase.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test_driver/linux-cirque/helper/CHIPTestBase.py b/src/test_driver/linux-cirque/helper/CHIPTestBase.py index ea45a62221e7e5..a6756b4800ee24 100644 --- a/src/test_driver/linux-cirque/helper/CHIPTestBase.py +++ b/src/test_driver/linux-cirque/helper/CHIPTestBase.py @@ -143,7 +143,7 @@ def reset_thread_devices(self, devices: Union[List[str], str]): for device_id in devices: # Wait for otbr-agent and CHIP server start self.assertTrue(self.wait_for_device_output( - device_id, "Thread Border Router started on AIL", 10)) + device_id, "Thread interface: wpan0", 10)) self.assertTrue(self.wait_for_device_output( device_id, "[SVR] Server Listening...", 15)) # Clear default Thread network commissioning data From 775cb4d0cd3f0d83dc0d6fa44b6b45902bbebd52 Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Wed, 6 Nov 2024 18:03:35 -0500 Subject: [PATCH 075/121] Create CHIP-specific backends for pigweed assert and logs (#36297) * Add a matter backend for assertions, to not depend on basic assertions in pigweed itself * No nullptr pass * Add a log backend, update copyrights * Restyle * Switch all backends for log and assert to the new chip backends instead of previous built-in/basic ones. Remove old log backend * Update public to fix linter for gn references * Fix dependencies (this should fix boufalolab compile at least * Remove pw_log_basic as we do not use it anymore * Restyle * Remove one more log_basic usage * Fix typo in log type - application is not defined * Avoid infinite recursion on logging now that PW-logging is not used * Remove echo_pb2 from the console as this is already imported by the pw_system.console it seems * Make PWConsole work again * make linter happy * Clean up all usages of CHIP_USE_PW_LOGGING * Mass rename backends to pw_backends * One more rename * Remove some more includes * Allow to keep going and report failed tetsts in local.py * Do not force fabric admin on BLE ... that seems odd * Switch to no wifi on fabric admin/bridge too * More cleanup for sizes for subprocess * More updates, generally switching to textio did not seem to work well, so just set bufsize to 0 * Update logic: apparently readlines is NOT lazy * Remove unused import * Fix unit tests * Even better display and avoid crashes in pw rpc. Sill need to fix mcore test * Fix flag logic * Make MCOREFS_1_5 less racy: window status is updated several times it seems, so wait for the right status (it starts as not open, then switches to open) * Restyled by autopep8 * Ensure elapsed and time remaining is always updated * Make local.py have a less noisy argument since on failures we generally want to read the files not have them in stdout (except for CI where we only see stdout right now) --------- Co-authored-by: Andrei Litvin Co-authored-by: Restyled.io --- .github/workflows/tests.yaml | 4 +- .gn | 4 +- .../bouffalolab/common/lib/pw_rpc/pw_rpc.gni | 4 +- config/efr32/lib/pw_rpc/pw_rpc.gni | 4 +- config/mbed/chip-gn/lib/pw_rpc/pw_rpc.gni | 4 +- config/nxp/lib/pw_rpc/pw_rpc.gni | 4 +- config/qpg/lib/pw_rpc/pw_rpc.gni | 4 +- .../all-clusters-app/linux/with_pw_rpc.gni | 5 +- examples/android/CHIPTest/args.gni | 4 +- examples/chef/linux/with_pw_rpc.gni | 5 +- examples/common/pigweed/RpcService.cpp | 15 --- .../rpc_console/py/chip_rpc/console.py | 18 +--- examples/common/pigweed/system_rpc_server.cc | 8 +- examples/fabric-admin/args.gni | 1 - .../fabric-admin/scripts/fabric-sync-app.py | 1 + examples/fabric-admin/with_pw_rpc.gni | 5 +- .../fabric-bridge-app/linux/with_pw_rpc.gni | 5 +- examples/light-switch-app/genio/args.gni | 4 +- .../genio/build_for_wifi_args.gni | 4 +- examples/light-switch-app/qpg/args.gni | 4 +- .../linux/with_pw_rpc.gni | 5 +- .../lighting-app/bouffalolab/bl602/args.gni | 4 +- .../lighting-app/bouffalolab/bl702/args.gni | 4 +- .../lighting-app/bouffalolab/bl702l/args.gni | 4 +- examples/lighting-app/genio/args.gni | 4 +- .../genio/build_for_wifi_args.gni | 4 +- examples/lighting-app/linux/with_pw_rpc.gni | 5 +- examples/lighting-app/qpg/args.gni | 4 +- examples/lock-app/genio/args.gni | 4 +- .../lock-app/genio/build_for_wifi_args.gni | 4 +- examples/lock-app/qpg/args.gni | 4 +- examples/ota-requestor-app/genio/args.gni | 4 +- .../genio/build_for_wifi_args.gni | 4 +- examples/platform/linux/system_rpc_server.cc | 18 ++-- examples/shell/genio/args.gni | 4 +- examples/shell/qpg/args.gni | 4 +- examples/thermostat/genio/args.gni | 4 +- .../thermostat/genio/build_for_wifi_args.gni | 4 +- examples/thermostat/qpg/args.gni | 4 +- scripts/build/builders/host.py | 1 + ...ux-arm64-ota-requestor-nodeps-ipv6only.txt | 2 +- scripts/tests/local.py | 92 +++++++++++++++---- scripts/tests/requirements.txt | 1 + src/app/tests/BUILD.gn | 2 - src/lib/core/BUILD.gn | 1 - src/lib/core/core.gni | 3 - src/lib/support/pw_log_chip/BUILD.gn | 35 ------- .../pw_log_chip/public/pw_log_chip/log_chip.h | 50 ---------- src/platform/Linux/BUILD.gn | 12 --- src/platform/Linux/Logging.cpp | 29 ------ src/platform/NuttX/BUILD.gn | 8 -- src/platform/NuttX/Logging.cpp | 29 ------ src/platform/logging/BUILD.gn | 4 - src/pw_backends/assert/BUILD.gn | 69 ++++++++++++++ src/pw_backends/assert/handler.cpp | 42 +++++++++ .../assert/public/pw_assert_matter/handler.h | 35 +++++++ .../pw_assert_backend/check_backend.h | 66 +++++++++++++ src/pw_backends/log/BUILD.gn | 75 +++++++++++++++ .../log/public/pw_log_matter/log_matter.h | 52 +++++++++++ .../pw_log_backend/log_backend.h | 11 +-- src/python_testing/TC_MCORE_FS_1_5.py | 16 ++-- .../chip/testing/tasks.py | 18 ++-- src/test_driver/efr32/args.gni | 4 +- 63 files changed, 525 insertions(+), 331 deletions(-) delete mode 100644 src/lib/support/pw_log_chip/BUILD.gn delete mode 100644 src/lib/support/pw_log_chip/public/pw_log_chip/log_chip.h create mode 100644 src/pw_backends/assert/BUILD.gn create mode 100644 src/pw_backends/assert/handler.cpp create mode 100644 src/pw_backends/assert/public/pw_assert_matter/handler.h create mode 100644 src/pw_backends/assert/public_overrides/pw_assert_backend/check_backend.h create mode 100644 src/pw_backends/log/BUILD.gn create mode 100644 src/pw_backends/log/public/pw_log_matter/log_matter.h rename src/{lib/support/pw_log_chip => pw_backends/log}/public_overrides/pw_log_backend/log_backend.h (74%) diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 3b2fcb093a9158..9a31e56ca8ef54 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -494,7 +494,7 @@ jobs: --target linux-x64-microwave-oven-ipv6only-no-ble-no-wifi-tsan-clang-test \ --target linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test \ --target linux-x64-network-manager-ipv6only-no-ble-no-wifi-tsan-clang-test \ - --target linux-x64-fabric-admin-rpc-ipv6only-clang \ + --target linux-x64-fabric-admin-rpc-ipv6only-no-ble-no-wifi-clang \ --target linux-x64-fabric-bridge-rpc-ipv6only-no-ble-no-wifi-clang \ --target linux-x64-light-data-model-no-unique-id-ipv6only-no-ble-no-wifi-clang \ --target linux-x64-python-bindings \ @@ -511,7 +511,7 @@ jobs: echo "CHIP_MICROWAVE_OVEN_APP: out/linux-x64-microwave-oven-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-microwave-oven-app" >> /tmp/test_env.yaml echo "CHIP_RVC_APP: out/linux-x64-rvc-ipv6only-no-ble-no-wifi-tsan-clang-test/chip-rvc-app" >> /tmp/test_env.yaml echo "NETWORK_MANAGEMENT_APP: out/linux-x64-network-manager-ipv6only-no-ble-no-wifi-tsan-clang-test/matter-network-manager-app" >> /tmp/test_env.yaml - echo "FABRIC_ADMIN_APP: out/linux-x64-fabric-admin-rpc-ipv6only-clang/fabric-admin" >> /tmp/test_env.yaml + echo "FABRIC_ADMIN_APP: out/linux-x64-fabric-admin-rpc-ipv6only-no-ble-no-wifi-clang/fabric-admin" >> /tmp/test_env.yaml echo "FABRIC_BRIDGE_APP: out/linux-x64-fabric-bridge-rpc-ipv6only-no-ble-no-wifi-clang/fabric-bridge-app" >> /tmp/test_env.yaml echo "LIGHTING_APP_NO_UNIQUE_ID: out/linux-x64-light-data-model-no-unique-id-ipv6only-no-ble-no-wifi-clang/chip-lighting-app" >> /tmp/test_env.yaml echo "TRACE_APP: out/trace_data/app-{SCRIPT_BASE_NAME}" >> /tmp/test_env.yaml diff --git a/.gn b/.gn index f844fd20e9b87d..ebd301ee7cf8cd 100644 --- a/.gn +++ b/.gn @@ -35,8 +35,8 @@ default_args = { # Required for pw_unit_test pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" - pw_assert_BACKEND = "$dir_pw_assert_log" - pw_log_BACKEND = "$dir_pw_log_basic" + pw_assert_BACKEND = "//src/pw_backends/assert" + pw_log_BACKEND = "//src/pw_backends/log" # TODO: Make sure only unit tests link against this pw_build_LINK_DEPS = [ diff --git a/config/bouffalolab/common/lib/pw_rpc/pw_rpc.gni b/config/bouffalolab/common/lib/pw_rpc/pw_rpc.gni index 2cfbc034e875eb..86c20ccc72cdc8 100644 --- a/config/bouffalolab/common/lib/pw_rpc/pw_rpc.gni +++ b/config/bouffalolab/common/lib/pw_rpc/pw_rpc.gni @@ -15,8 +15,8 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "${chip_root}/examples/platform/bouffalolab/common/rpc/pw_sys_io:pw_sys_io" diff --git a/config/efr32/lib/pw_rpc/pw_rpc.gni b/config/efr32/lib/pw_rpc/pw_rpc.gni index 101112c12dadc9..ac5e3831da388d 100644 --- a/config/efr32/lib/pw_rpc/pw_rpc.gni +++ b/config/efr32/lib/pw_rpc/pw_rpc.gni @@ -15,8 +15,8 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" pw_sys_io_BACKEND = "${chip_root}/examples/platform/silabs/pw_sys_io:pw_sys_io_silabs" diff --git a/config/mbed/chip-gn/lib/pw_rpc/pw_rpc.gni b/config/mbed/chip-gn/lib/pw_rpc/pw_rpc.gni index 2b03f6b4c9958c..50ef9977fa54db 100644 --- a/config/mbed/chip-gn/lib/pw_rpc/pw_rpc.gni +++ b/config/mbed/chip-gn/lib/pw_rpc/pw_rpc.gni @@ -15,8 +15,8 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "${chip_root}/examples/platform/mbed/pw_sys_io:pw_sys_io_mbed" pw_rpc_system_server_BACKEND = diff --git a/config/nxp/lib/pw_rpc/pw_rpc.gni b/config/nxp/lib/pw_rpc/pw_rpc.gni index 68255db8bb96da..f91c53cf354da3 100644 --- a/config/nxp/lib/pw_rpc/pw_rpc.gni +++ b/config/nxp/lib/pw_rpc/pw_rpc.gni @@ -15,8 +15,8 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" pw_sys_io_BACKEND = "${chip_root}/examples/platform/nxp/pw_sys_io:pw_sys_io_nxp" diff --git a/config/qpg/lib/pw_rpc/pw_rpc.gni b/config/qpg/lib/pw_rpc/pw_rpc.gni index 60fb93e6b8fc44..8e282c3bf053f2 100644 --- a/config/qpg/lib/pw_rpc/pw_rpc.gni +++ b/config/qpg/lib/pw_rpc/pw_rpc.gni @@ -15,8 +15,8 @@ import("//build_overrides/chip.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "${chip_root}/examples/platform/qpg/pw_sys_io:pw_sys_io_qpg" pw_build_LINK_DEPS = [ diff --git a/examples/all-clusters-app/linux/with_pw_rpc.gni b/examples/all-clusters-app/linux/with_pw_rpc.gni index 0f1ab1ea89c121..a67251431a018c 100644 --- a/examples/all-clusters-app/linux/with_pw_rpc.gni +++ b/examples/all-clusters-app/linux/with_pw_rpc.gni @@ -21,8 +21,8 @@ import("${chip_root}/config/standalone/args.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" pw_trace_BACKEND = "$dir_pw_trace_tokenized" pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" @@ -39,4 +39,3 @@ pw_build_LINK_DEPS = [ ] chip_enable_pw_rpc = true -chip_use_pw_logging = true diff --git a/examples/android/CHIPTest/args.gni b/examples/android/CHIPTest/args.gni index df7c34af9c20ae..04ba876aeb7ac9 100644 --- a/examples/android/CHIPTest/args.gni +++ b/examples/android/CHIPTest/args.gni @@ -28,8 +28,8 @@ chip_monolithic_tests = false pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" -pw_assert_BACKEND = "$dir_pw_assert_log" -pw_log_BACKEND = "$dir_pw_log_basic" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" pw_unit_test_BACKEND = "$dir_pw_unit_test:light" diff --git a/examples/chef/linux/with_pw_rpc.gni b/examples/chef/linux/with_pw_rpc.gni index 0f1ab1ea89c121..a67251431a018c 100644 --- a/examples/chef/linux/with_pw_rpc.gni +++ b/examples/chef/linux/with_pw_rpc.gni @@ -21,8 +21,8 @@ import("${chip_root}/config/standalone/args.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" pw_trace_BACKEND = "$dir_pw_trace_tokenized" pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" @@ -39,4 +39,3 @@ pw_build_LINK_DEPS = [ ] chip_enable_pw_rpc = true -chip_use_pw_logging = true diff --git a/examples/common/pigweed/RpcService.cpp b/examples/common/pigweed/RpcService.cpp index 74d0b891e9b00d..ee999c4b172fc9 100644 --- a/examples/common/pigweed/RpcService.cpp +++ b/examples/common/pigweed/RpcService.cpp @@ -25,7 +25,6 @@ #include "pw_hdlc/decoder.h" #include "pw_hdlc/default_addresses.h" #include "pw_hdlc/rpc_channel.h" -#include "pw_log/log.h" #include "pw_rpc/channel.h" #include "pw_status/status.h" #include "pw_stream/sys_io_stream.h" @@ -96,20 +95,6 @@ void Start(void (*RegisterServices)(pw::rpc::Server &), ::chip::rpc::Mutex * uar PW_DASSERT(RegisterServices != nullptr); uart_mutex = uart_mutex_; - // Send log messages to HDLC address 1. This prevents logs from interfering - // with pw_rpc communications. - pw::log_basic::SetOutput([](std::string_view log) { - if (uart_mutex) - { - uart_mutex->Lock(); - } - pw::hdlc::WriteUIFrame(1, pw::as_bytes(pw::span(log)), sysIoWriter); - if (uart_mutex) - { - uart_mutex->Unlock(); - } - }); - // Set up the server and start processing data. RegisterServices(server); diff --git a/examples/common/pigweed/rpc_console/py/chip_rpc/console.py b/examples/common/pigweed/rpc_console/py/chip_rpc/console.py index 50f0b030f51725..31ecd9df03e0f0 100644 --- a/examples/common/pigweed/rpc_console/py/chip_rpc/console.py +++ b/examples/common/pigweed/rpc_console/py/chip_rpc/console.py @@ -39,7 +39,7 @@ import argparse import sys from pathlib import Path -from typing import Any, Collection +from typing import Collection import pw_system.console from pw_hdlc import rpc @@ -52,7 +52,6 @@ from button_service import button_service_pb2 from descriptor_service import descriptor_service_pb2 from device_service import device_service_pb2 -from echo_service import echo_pb2 from fabric_admin_service import fabric_admin_service_pb2 from fabric_bridge_service import fabric_bridge_service_pb2 from lighting_service import lighting_service_pb2 @@ -72,13 +71,6 @@ def _parse_args(): type=int, default=115200, help='the baud rate to use') - parser.add_argument( - '-o', - '--output', - type=argparse.FileType('wb'), - default=sys.stdout.buffer, - help=('The file to which to write device output (HDLC channel 1); ' - 'provide - or omit for stdout.')) parser.add_argument( '-r', '--raw_serial', @@ -99,7 +91,7 @@ def _parse_args(): def show_console(device: str, baudrate: int, token_databases: Collection[Path], - socket_addr: str, output: Any, raw_serial: bool) -> int: + socket_addr: str, raw_serial: bool) -> int: # TODO: this shows a default console with little customization # Ideally we should at least customize the default messages @@ -114,7 +106,6 @@ def show_console(device: str, baudrate: int, device=device, baudrate=baudrate, socket_addr=socket_addr, - output=output, hdlc_encoding=not raw_serial, token_databases=token_databases, logfile="", @@ -122,14 +113,10 @@ def show_console(device: str, baudrate: int, channel_id=rpc.DEFAULT_CHANNEL_ID, # Defaults beyond the original console - proto_globs=[], ticks_per_second=None, host_logfile="", json_logfile="", rpc_logging=False, - # the pt-python based console seems to break on python 3.1 with - # "set_wakeup_fd only works in main thread of the main interpreter" - use_ipython=True, compiled_protos=[ actions_service_pb2, attributes_service_pb2, @@ -137,7 +124,6 @@ def show_console(device: str, baudrate: int, button_service_pb2, descriptor_service_pb2, device_service_pb2, - echo_pb2, fabric_admin_service_pb2, fabric_bridge_service_pb2, lighting_service_pb2, diff --git a/examples/common/pigweed/system_rpc_server.cc b/examples/common/pigweed/system_rpc_server.cc index 098aa3b1711058..360bdef947e631 100644 --- a/examples/common/pigweed/system_rpc_server.cc +++ b/examples/common/pigweed/system_rpc_server.cc @@ -20,7 +20,6 @@ #include "pw_hdlc/decoder.h" #include "pw_hdlc/default_addresses.h" #include "pw_hdlc/rpc_channel.h" -#include "pw_log/log.h" #include "pw_rpc_system_server/rpc_server.h" #include "pw_stream/sys_io_stream.h" @@ -40,12 +39,7 @@ rpc::Server server(channels); } // namespace -void Init() -{ - // Send log messages to HDLC address 1. This prevents logs from interfering - // with pw_rpc communications. - pw::log_basic::SetOutput([](std::string_view log) { pw::hdlc::WriteUIFrame(1, pw::as_bytes(pw::span(log)), writer); }); -} +void Init() {} rpc::Server & Server() { diff --git a/examples/fabric-admin/args.gni b/examples/fabric-admin/args.gni index 63c91c70c209cd..83300d797ed08a 100644 --- a/examples/fabric-admin/args.gni +++ b/examples/fabric-admin/args.gni @@ -32,4 +32,3 @@ matter_log_json_payload_decode_full = true # make fabric-admin very strict by default chip_tlv_validate_char_string_on_read = true chip_tlv_validate_char_string_on_write = true -chip_enable_ble = true diff --git a/examples/fabric-admin/scripts/fabric-sync-app.py b/examples/fabric-admin/scripts/fabric-sync-app.py index bc26c655be9024..3de85b9f672887 100755 --- a/examples/fabric-admin/scripts/fabric-sync-app.py +++ b/examples/fabric-admin/scripts/fabric-sync-app.py @@ -32,6 +32,7 @@ async def forward_f(prefix: bytes, f_in: asyncio.StreamReader, This function can optionally feed received lines to a callback function. """ + while line := await f_in.readline(): if cb is not None: cb(line) diff --git a/examples/fabric-admin/with_pw_rpc.gni b/examples/fabric-admin/with_pw_rpc.gni index abb9ac65f27e78..d5e1aae432216d 100644 --- a/examples/fabric-admin/with_pw_rpc.gni +++ b/examples/fabric-admin/with_pw_rpc.gni @@ -21,8 +21,8 @@ import("${chip_root}/config/standalone/args.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" pw_trace_BACKEND = "$dir_pw_trace_tokenized" pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" @@ -39,4 +39,3 @@ pw_build_LINK_DEPS = [ ] chip_enable_pw_rpc = true -chip_use_pw_logging = true diff --git a/examples/fabric-bridge-app/linux/with_pw_rpc.gni b/examples/fabric-bridge-app/linux/with_pw_rpc.gni index e1bd567cf22db2..335a1f309666b0 100644 --- a/examples/fabric-bridge-app/linux/with_pw_rpc.gni +++ b/examples/fabric-bridge-app/linux/with_pw_rpc.gni @@ -21,8 +21,8 @@ import("${chip_root}/config/standalone/args.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" pw_trace_BACKEND = "$dir_pw_trace_tokenized" pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" @@ -38,5 +38,4 @@ pw_build_LINK_DEPS = [ "$dir_pw_log:impl", ] -chip_use_pw_logging = true bridge_enable_pw_rpc = true diff --git a/examples/light-switch-app/genio/args.gni b/examples/light-switch-app/genio/args.gni index ddbfb9fa47f20d..b684adc4a6b792 100644 --- a/examples/light-switch-app/genio/args.gni +++ b/examples/light-switch-app/genio/args.gni @@ -18,8 +18,8 @@ import("${chip_root}/src/platform/mt793x/args.gni") mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_enable_ble = true diff --git a/examples/light-switch-app/genio/build_for_wifi_args.gni b/examples/light-switch-app/genio/build_for_wifi_args.gni index cb0ea7600a2dd5..3001e6648f4aa8 100644 --- a/examples/light-switch-app/genio/build_for_wifi_args.gni +++ b/examples/light-switch-app/genio/build_for_wifi_args.gni @@ -18,5 +18,5 @@ mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false import("${chip_root}/src/platform/MT793X/wifi_args.gni") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/light-switch-app/qpg/args.gni b/examples/light-switch-app/qpg/args.gni index 9a69cd16959f6d..a6b8b77b72902c 100644 --- a/examples/light-switch-app/qpg/args.gni +++ b/examples/light-switch-app/qpg/args.gni @@ -32,5 +32,5 @@ chip_stack_lock_tracking = "none" matter_device_vid = "0xFFF1" matter_device_pid = "0x8004" -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/lighting-app-data-mode-no-unique-id/linux/with_pw_rpc.gni b/examples/lighting-app-data-mode-no-unique-id/linux/with_pw_rpc.gni index 0f1ab1ea89c121..a67251431a018c 100644 --- a/examples/lighting-app-data-mode-no-unique-id/linux/with_pw_rpc.gni +++ b/examples/lighting-app-data-mode-no-unique-id/linux/with_pw_rpc.gni @@ -21,8 +21,8 @@ import("${chip_root}/config/standalone/args.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" pw_trace_BACKEND = "$dir_pw_trace_tokenized" pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" @@ -39,4 +39,3 @@ pw_build_LINK_DEPS = [ ] chip_enable_pw_rpc = true -chip_use_pw_logging = true diff --git a/examples/lighting-app/bouffalolab/bl602/args.gni b/examples/lighting-app/bouffalolab/bl602/args.gni index 0fcb5aac2edc9b..491e87ab3fb419 100644 --- a/examples/lighting-app/bouffalolab/bl602/args.gni +++ b/examples/lighting-app/bouffalolab/bl602/args.gni @@ -19,8 +19,8 @@ import("${chip_root}/src/platform/bouffalolab/BL602/args.gni") bl_iot_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" chip_detail_logging = false diff --git a/examples/lighting-app/bouffalolab/bl702/args.gni b/examples/lighting-app/bouffalolab/bl702/args.gni index e06c706903b935..4e999b386d0d41 100644 --- a/examples/lighting-app/bouffalolab/bl702/args.gni +++ b/examples/lighting-app/bouffalolab/bl702/args.gni @@ -19,8 +19,8 @@ import("${chip_root}/src/platform/bouffalolab/BL702/args.gni") bl_iot_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" chip_detail_logging = false diff --git a/examples/lighting-app/bouffalolab/bl702l/args.gni b/examples/lighting-app/bouffalolab/bl702l/args.gni index 3120af1cce60f6..44589ed15f5d5f 100644 --- a/examples/lighting-app/bouffalolab/bl702l/args.gni +++ b/examples/lighting-app/bouffalolab/bl702l/args.gni @@ -19,8 +19,8 @@ import("${chip_root}/src/platform/bouffalolab/BL702L/args.gni") bl_iot_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" chip_detail_logging = false diff --git a/examples/lighting-app/genio/args.gni b/examples/lighting-app/genio/args.gni index e22869653722a7..cbdadf266953f2 100644 --- a/examples/lighting-app/genio/args.gni +++ b/examples/lighting-app/genio/args.gni @@ -19,8 +19,8 @@ import("${chip_root}/src/platform/mt793x/args.gni") mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_enable_ble = true diff --git a/examples/lighting-app/genio/build_for_wifi_args.gni b/examples/lighting-app/genio/build_for_wifi_args.gni index cb0ea7600a2dd5..3001e6648f4aa8 100644 --- a/examples/lighting-app/genio/build_for_wifi_args.gni +++ b/examples/lighting-app/genio/build_for_wifi_args.gni @@ -18,5 +18,5 @@ mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false import("${chip_root}/src/platform/MT793X/wifi_args.gni") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/lighting-app/linux/with_pw_rpc.gni b/examples/lighting-app/linux/with_pw_rpc.gni index 0f1ab1ea89c121..a67251431a018c 100644 --- a/examples/lighting-app/linux/with_pw_rpc.gni +++ b/examples/lighting-app/linux/with_pw_rpc.gni @@ -21,8 +21,8 @@ import("${chip_root}/config/standalone/args.gni") import("//build_overrides/pigweed.gni") -pw_log_BACKEND = "$dir_pw_log_basic" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" pw_sys_io_BACKEND = "$dir_pw_sys_io_stdio" pw_trace_BACKEND = "$dir_pw_trace_tokenized" pw_unit_test_MAIN = "$dir_pw_unit_test:logging_main" @@ -39,4 +39,3 @@ pw_build_LINK_DEPS = [ ] chip_enable_pw_rpc = true -chip_use_pw_logging = true diff --git a/examples/lighting-app/qpg/args.gni b/examples/lighting-app/qpg/args.gni index ea22dfd187fbb2..37ca029954781a 100644 --- a/examples/lighting-app/qpg/args.gni +++ b/examples/lighting-app/qpg/args.gni @@ -30,5 +30,5 @@ chip_stack_lock_tracking = "none" matter_device_vid = "0xFFF1" matter_device_pid = "0x8005" -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/lock-app/genio/args.gni b/examples/lock-app/genio/args.gni index ddbfb9fa47f20d..b684adc4a6b792 100644 --- a/examples/lock-app/genio/args.gni +++ b/examples/lock-app/genio/args.gni @@ -18,8 +18,8 @@ import("${chip_root}/src/platform/mt793x/args.gni") mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_enable_ble = true diff --git a/examples/lock-app/genio/build_for_wifi_args.gni b/examples/lock-app/genio/build_for_wifi_args.gni index cb0ea7600a2dd5..3001e6648f4aa8 100644 --- a/examples/lock-app/genio/build_for_wifi_args.gni +++ b/examples/lock-app/genio/build_for_wifi_args.gni @@ -18,5 +18,5 @@ mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false import("${chip_root}/src/platform/MT793X/wifi_args.gni") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/lock-app/qpg/args.gni b/examples/lock-app/qpg/args.gni index d5dcdfe217c635..562005806d5059 100644 --- a/examples/lock-app/qpg/args.gni +++ b/examples/lock-app/qpg/args.gni @@ -31,5 +31,5 @@ chip_stack_lock_tracking = "none" matter_device_vid = "0xFFF1" matter_device_pid = "0x8006" -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/ota-requestor-app/genio/args.gni b/examples/ota-requestor-app/genio/args.gni index 7a6cc1c74c6394..89889de70bd9ea 100644 --- a/examples/ota-requestor-app/genio/args.gni +++ b/examples/ota-requestor-app/genio/args.gni @@ -18,8 +18,8 @@ import("${chip_root}/src/platform/mt793x/args.gni") mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_enable_ble = true diff --git a/examples/ota-requestor-app/genio/build_for_wifi_args.gni b/examples/ota-requestor-app/genio/build_for_wifi_args.gni index cb0ea7600a2dd5..3001e6648f4aa8 100644 --- a/examples/ota-requestor-app/genio/build_for_wifi_args.gni +++ b/examples/ota-requestor-app/genio/build_for_wifi_args.gni @@ -18,5 +18,5 @@ mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false import("${chip_root}/src/platform/MT793X/wifi_args.gni") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/platform/linux/system_rpc_server.cc b/examples/platform/linux/system_rpc_server.cc index 6323ad597d0cfe..b87a1c5d50bcc0 100644 --- a/examples/platform/linux/system_rpc_server.cc +++ b/examples/platform/linux/system_rpc_server.cc @@ -56,11 +56,6 @@ void set_socket_port(uint16_t new_socket_port) void Init() { - log_basic::SetOutput([](std::string_view log) { - std::fprintf(stderr, "%.*s\n", static_cast(log.size()), log.data()); - hdlc::WriteUIFrame(1, as_bytes(span(log)), socket_stream).IgnoreError(); // TODO(pwbug/387): Handle Status properly - }); - PW_LOG_INFO("Starting pw_rpc server on port %d", socket_port); PW_CHECK_OK(server_socket.Listen(socket_port)); auto accept_result = server_socket.Accept(); @@ -92,9 +87,18 @@ Status Start() // remote to connect. socket_stream.Close(); server_socket.Close(); - PW_CHECK_OK(server_socket.Listen(socket_port)); + Status status = server_socket.Listen(socket_port); + if (!status.ok()) + { + PW_LOG_ERROR("Listen failed. Exiting RPC Server loop"); + return status; + } auto accept_result = server_socket.Accept(); - PW_CHECK_OK(accept_result.status()); + if (!accept_result.status().ok()) + { + PW_LOG_ERROR("Accept failed. Exiting RPC Server loop"); + return accept_result.status(); + } socket_stream = *std::move(accept_result); } continue; diff --git a/examples/shell/genio/args.gni b/examples/shell/genio/args.gni index 8d2c11daa5b180..eda29ff0e68df2 100644 --- a/examples/shell/genio/args.gni +++ b/examples/shell/genio/args.gni @@ -19,8 +19,8 @@ import("${chip_root}/src/platform/mt793x/args.gni") mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_enable_ble = false chip_config_network_layer_ble = false diff --git a/examples/shell/qpg/args.gni b/examples/shell/qpg/args.gni index 478e91d9cb05a6..c6c98b3fce747a 100644 --- a/examples/shell/qpg/args.gni +++ b/examples/shell/qpg/args.gni @@ -19,8 +19,8 @@ import("${chip_root}/examples/platform/qpg/args.gni") qpg_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_build_libshell = true # Disable lock tracking, since our FreeRTOS configuration does not set diff --git a/examples/thermostat/genio/args.gni b/examples/thermostat/genio/args.gni index ddbfb9fa47f20d..b684adc4a6b792 100644 --- a/examples/thermostat/genio/args.gni +++ b/examples/thermostat/genio/args.gni @@ -18,8 +18,8 @@ import("${chip_root}/src/platform/mt793x/args.gni") mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" chip_enable_ble = true diff --git a/examples/thermostat/genio/build_for_wifi_args.gni b/examples/thermostat/genio/build_for_wifi_args.gni index cb0ea7600a2dd5..3001e6648f4aa8 100644 --- a/examples/thermostat/genio/build_for_wifi_args.gni +++ b/examples/thermostat/genio/build_for_wifi_args.gni @@ -18,5 +18,5 @@ mt793x_sdk_target = get_label_info(":sdk", "label_no_toolchain") chip_enable_openthread = false import("${chip_root}/src/platform/MT793X/wifi_args.gni") -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/examples/thermostat/qpg/args.gni b/examples/thermostat/qpg/args.gni index 693375e4388593..64d8c32d43a0ec 100644 --- a/examples/thermostat/qpg/args.gni +++ b/examples/thermostat/qpg/args.gni @@ -31,5 +31,5 @@ chip_stack_lock_tracking = "none" matter_device_vid = "0xFFF1" matter_device_pid = "0x8003" -pw_log_BACKEND = "${chip_root}/src/lib/support/pw_log_chip" -pw_assert_BACKEND = "$dir_pw_assert_log:check_backend" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" diff --git a/scripts/build/builders/host.py b/scripts/build/builders/host.py index 0ced1270fb583e..43b95b763278b8 100644 --- a/scripts/build/builders/host.py +++ b/scripts/build/builders/host.py @@ -354,6 +354,7 @@ def __init__(self, root, runner, app: HostApp, board=HostBoard.NATIVE, if not enable_ble: self.extra_gn_options.append('chip_config_network_layer_ble=false') + self.extra_gn_options.append('chip_enable_ble=false') if not enable_wifi: self.extra_gn_options.append('chip_enable_wifi=false') diff --git a/scripts/build/testdata/dry_run_linux-arm64-ota-requestor-nodeps-ipv6only.txt b/scripts/build/testdata/dry_run_linux-arm64-ota-requestor-nodeps-ipv6only.txt index cc8ec0110ec923..a1f9beb5eb6f60 100644 --- a/scripts/build/testdata/dry_run_linux-arm64-ota-requestor-nodeps-ipv6only.txt +++ b/scripts/build/testdata/dry_run_linux-arm64-ota-requestor-nodeps-ipv6only.txt @@ -4,7 +4,7 @@ cd "{root}" # Generating linux-arm64-ota-requestor-nodeps-ipv6only bash -c ' PKG_CONFIG_PATH="SYSROOT_AARCH64/lib/aarch64-linux-gnu/pkgconfig" \ - gn gen --check --fail-on-unused-args --export-compile-commands --root={root}/examples/ota-requestor-app/linux '"'"'--args=chip_inet_config_enable_ipv4=false chip_config_network_layer_ble=false chip_enable_wifi=false chip_enable_openthread=false is_clang=true chip_crypto="mbedtls" target_cpu="arm64" sysroot="SYSROOT_AARCH64"'"'"' {out}/linux-arm64-ota-requestor-nodeps-ipv6only' + gn gen --check --fail-on-unused-args --export-compile-commands --root={root}/examples/ota-requestor-app/linux '"'"'--args=chip_inet_config_enable_ipv4=false chip_config_network_layer_ble=false chip_enable_ble=false chip_enable_wifi=false chip_enable_openthread=false is_clang=true chip_crypto="mbedtls" target_cpu="arm64" sysroot="SYSROOT_AARCH64"'"'"' {out}/linux-arm64-ota-requestor-nodeps-ipv6only' # Setting up Java deps third_party/java_deps/set_up_java_deps.sh diff --git a/scripts/tests/local.py b/scripts/tests/local.py index 97a2d1daf83c28..05cf2f129a05fb 100755 --- a/scripts/tests/local.py +++ b/scripts/tests/local.py @@ -31,6 +31,7 @@ import alive_progress import click +import colorama import coloredlogs import tabulate import yaml @@ -95,6 +96,7 @@ class ExecutionTimeInfo: script: str duration_sec: float + status: str # Top level command, groups all other commands for the purpose of having @@ -166,8 +168,8 @@ def _do_build_apps(): f"{target_prefix}-all-clusters-no-ble-clang-boringssl", f"{target_prefix}-bridge-no-ble-clang-boringssl", f"{target_prefix}-energy-management-no-ble-clang-boringssl", - f"{target_prefix}-fabric-admin-rpc-ipv6only-clang-boringssl", - f"{target_prefix}-fabric-bridge-rpc-ipv6only-clang-boringssl", + f"{target_prefix}-fabric-admin-no-ble-no-wifi-rpc-ipv6only-clang-boringssl", + f"{target_prefix}-fabric-bridge-no-ble-no-wifi-rpc-ipv6only-clang-boringssl", f"{target_prefix}-light-data-model-no-unique-id-ipv6only-no-ble-no-wifi-clang", f"{target_prefix}-lit-icd-no-ble-clang-boringssl", f"{target_prefix}-lock-no-ble-clang-boringssl", @@ -316,12 +318,24 @@ def _add_target_to_cmd(cmd, flag, path, runner): help="Don't actually execute the tests, just print out the command that would be run.", ) @click.option( - "--show_timings", + "--no-show-timings", default=False, is_flag=True, - show_default=True, help="At the end of the execution, show how many seconds each test took.", ) +@click.option( + "--keep-going", + default=False, + is_flag=True, + show_default=True, + help="Keep going on errors. Will report all failed tests at the end.", +) +@click.option( + "--fail-log-dir", + default=None, + help="Save failure logs into the specified directory instead of logging (as logging can be noisy/slow)", + type=click.Path(exists=True, file_okay=False, dir_okay=True), +) @click.option( "--runner", default="none", @@ -329,7 +343,14 @@ def _add_target_to_cmd(cmd, flag, path, runner): help="Determines the verbosity of script output", ) def python_tests( - test_filter, from_filter, from_skip_filter, dry_run, show_timings, runner + test_filter, + from_filter, + from_skip_filter, + dry_run, + no_show_timings, + runner, + keep_going, + fail_log_dir, ): """ Run python tests via `run_python_test.py` @@ -359,9 +380,9 @@ def as_runner(path): NETWORK_MANAGEMENT_APP: { as_runner(f'out/{target_prefix}-network-manager-ipv6only-no-ble-clang-boringssl/matter-network-manager-app')} FABRIC_ADMIN_APP: { - as_runner(f'out/{target_prefix}-fabric-admin-rpc-ipv6only-clang-boringssl/fabric-admin')} + as_runner(f'out/{target_prefix}-fabric-admin-no-ble-no-wifi-rpc-ipv6only-clang-boringssl/fabric-admin')} FABRIC_BRIDGE_APP: { - as_runner(f'out/{target_prefix}-fabric-bridge-rpc-ipv6only-clang-boringssl/fabric-bridge-app')} + as_runner(f'out/{target_prefix}-fabric-bridge-no-ble-no-wifi-rpc-ipv6only-clang-boringssl/fabric-bridge-app')} LIGHTING_APP_NO_UNIQUE_ID: {as_runner(f'out/{target_prefix}-light-data-model-no-unique-id-ipv6only-no-ble-no-wifi-clang/chip-lighting-app')} TRACE_APP: out/trace_data/app-{{SCRIPT_BASE_NAME}} TRACE_TEST_JSON: out/trace_data/test-{{SCRIPT_BASE_NAME}} @@ -395,7 +416,9 @@ def as_runner(path): excluded_patterns = set([item["name"] for item in metadata["not_automated"]]) # NOTE: for slow tests. we add logs to not get impatient - slow_test_duration = dict([(item["name"], item["duration"]) for item in metadata["slow_tests"]]) + slow_test_duration = dict( + [(item["name"], item["duration"]) for item in metadata["slow_tests"]] + ) if not os.path.isdir("src/python_testing"): raise Exception( @@ -411,6 +434,7 @@ def as_runner(path): test_scripts.sort() # order consistent execution_times = [] + failed_tests = [] try: to_run = [] for script in fnmatch.filter(test_scripts, test_filter or "*.*"): @@ -461,12 +485,33 @@ def as_runner(path): if result.returncode != 0: logging.error("Test failed: %s", script) - logging.info("STDOUT:\n%s", result.stdout.decode("utf8")) - logging.warning("STDERR:\n%s", result.stderr.decode("utf8")) - sys.exit(1) + if fail_log_dir: + out_name = os.path.join(fail_log_dir, f"{base_name}.out.log") + err_name = os.path.join(fail_log_dir, f"{base_name}.err.log") + + logging.error("STDOUT IN %s", out_name) + logging.error("STDERR IN %s", err_name) + + with open(out_name, "wb") as f: + f.write(result.stdout) + with open(err_name, "wb") as f: + f.write(result.stdout) + + else: + logging.info("STDOUT:\n%s", result.stdout.decode("utf8")) + logging.warning("STDERR:\n%s", result.stderr.decode("utf8")) + if not keep_going: + sys.exit(1) + failed_tests.append(script) time_info = ExecutionTimeInfo( - script=base_name, duration_sec=(tend - tstart) + script=base_name, + duration_sec=(tend - tstart), + status=( + "PASS" + if result.returncode == 0 + else colorama.Fore.RED + "FAILURE" + colorama.Fore.RESET + ), ) execution_times.append(time_info) @@ -478,12 +523,25 @@ def as_runner(path): ) bar() finally: - if execution_times and show_timings: - execution_times.sort(key=lambda v: v.duration_sec) + if failed_tests and keep_going: + logging.error("FAILED TESTS:") + for name in failed_tests: + logging.error(" %s", name) + + if execution_times and not no_show_timings: + execution_times.sort( + key=lambda v: (0 if v.status == "PASS" else 1, v.duration_sec), + ) print( - tabulate.tabulate(execution_times, headers=["Script", "Duration(sec)"]) + tabulate.tabulate( + execution_times, headers=["Script", "Duration(sec)", "Status"] + ) ) + if failed_tests: + # Propagate the final failure + sys.exit(1) + def _do_build_fabric_sync_apps(): """ @@ -491,8 +549,8 @@ def _do_build_fabric_sync_apps(): """ target_prefix = _get_native_machine_target() targets = [ - f"{target_prefix}-fabric-bridge-boringssl-rpc-no-ble", - f"{target_prefix}-fabric-admin-boringssl-rpc", + f"{target_prefix}-fabric-admin-no-ble-no-wifi-rpc-ipv6only-clang-boringssl", + f"{target_prefix}-fabric-bridge-no-ble-no-wifi-rpc-ipv6only-clang-boringssl", f"{target_prefix}-all-clusters-boringssl-no-ble", ] diff --git a/scripts/tests/requirements.txt b/scripts/tests/requirements.txt index 9e2d8570359155..1fab1f84c7c77e 100644 --- a/scripts/tests/requirements.txt +++ b/scripts/tests/requirements.txt @@ -5,5 +5,6 @@ colorama coloredlogs diskcache mypy==1.10.1 +pyyaml tabulate websockets diff --git a/src/app/tests/BUILD.gn b/src/app/tests/BUILD.gn index 03dadc061740a6..6f55c7bb6fafd1 100644 --- a/src/app/tests/BUILD.gn +++ b/src/app/tests/BUILD.gn @@ -181,8 +181,6 @@ source_set("app-test-stubs") { "test-interaction-model-api.h", ] - public_configs = [ "${chip_root}/src/lib/support/pw_log_chip:config" ] - public_deps = [ "${chip_root}/src/app/util/mock:mock_codegen_data_model", "${chip_root}/src/app/util/mock:mock_ember", diff --git a/src/lib/core/BUILD.gn b/src/lib/core/BUILD.gn index 5a6e6e114e4aae..265f5fea7fc5b8 100644 --- a/src/lib/core/BUILD.gn +++ b/src/lib/core/BUILD.gn @@ -48,7 +48,6 @@ buildconfig_header("chip_buildconfig") { "CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE=${chip_log_message_max_size}", "CHIP_AUTOMATION_LOGGING=${chip_automation_logging}", "CHIP_PW_TOKENIZER_LOGGING=${chip_pw_tokenizer_logging}", - "CHIP_USE_PW_LOGGING=${chip_use_pw_logging}", "CHIP_EXCHANGE_NODE_ID_LOGGING=${chip_exchange_node_id_logging}", "CHIP_CONFIG_SHORT_ERROR_STR=${chip_config_short_error_str}", "CHIP_CONFIG_ENABLE_ARG_PARSER=${chip_config_enable_arg_parser}", diff --git a/src/lib/core/core.gni b/src/lib/core/core.gni index eea73a5c56f7b3..6dd71cf64f5a57 100644 --- a/src/lib/core/core.gni +++ b/src/lib/core/core.gni @@ -50,9 +50,6 @@ declare_args() { # Enable pigweed tokenizer logging. chip_pw_tokenizer_logging = false - # Configure chip logging to output through pigweed logging. - chip_use_pw_logging = false - # Enable logging of node Id in exchange context log messages. # Will cause increase in code size and is therefore disabled by default. chip_exchange_node_id_logging = false diff --git a/src/lib/support/pw_log_chip/BUILD.gn b/src/lib/support/pw_log_chip/BUILD.gn deleted file mode 100644 index 23695fa505add0..00000000000000 --- a/src/lib/support/pw_log_chip/BUILD.gn +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright 2020 The Pigweed 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 -# -# https://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("//build_overrides/chip.gni") -import("//build_overrides/pigweed.gni") - -import("$dir_pw_build/target_types.gni") - -config("config") { - include_dirs = [ - "public", - "public_overrides", - ] -} - -pw_source_set("pw_log_chip") { - public_configs = [ ":config" ] - public_deps = [ ":pw_log_chip.impl" ] - public = [ "public_overrides/pw_log_backend/log_backend.h" ] - sources = [ "public/pw_log_chip/log_chip.h" ] -} - -pw_source_set("pw_log_chip.impl") { - public_deps = [ "${chip_root}/src/lib/support" ] -} diff --git a/src/lib/support/pw_log_chip/public/pw_log_chip/log_chip.h b/src/lib/support/pw_log_chip/public/pw_log_chip/log_chip.h deleted file mode 100644 index 6550ec707057da..00000000000000 --- a/src/lib/support/pw_log_chip/public/pw_log_chip/log_chip.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2020 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. - */ - -/** - * @file - * This header redirects Pigweed logging prints to chip. - */ -#pragma once - -#include - -#include "pw_preprocessor/arguments.h" - -/** - * Redirect pigweed log prints to chip logging. - * Currently does not use a log module, but this could be added when needed. - * pigweed debug and info level logs are mapped to chip's kLogCategory_Detail. - * All other log levels are mapped to chip's kLogCategory_Error. - * - * Note: This function should not be called directly, instead call the functions - * in pw_log/log.h. - * - * @param[in] level Pigweed log level. - * @param[in] flags Pigweed logging flags, currently these are ignored. - * @param[in] message The printf style log string. - */ -#define PW_LOG(level, flags, message, ...) \ - do \ - { \ - if (level >= PW_LOG_LEVEL_INFO) \ - { \ - ::chip::Logging::Log(::chip::Logging::kLogModule_NotSpecified, \ - (level <= PW_LOG_LEVEL_INFO) ? ::chip::Logging::kLogCategory_Detail \ - : ::chip::Logging::kLogCategory_Error, \ - message PW_COMMA_ARGS(__VA_ARGS__)); \ - } \ - } while (0) diff --git a/src/platform/Linux/BUILD.gn b/src/platform/Linux/BUILD.gn index 35b5047c9f4c00..7961b3d648da8f 100644 --- a/src/platform/Linux/BUILD.gn +++ b/src/platform/Linux/BUILD.gn @@ -22,10 +22,6 @@ import("${chip_root}/src/platform/device.gni") assert(chip_device_platform == "linux") -if (chip_use_pw_logging) { - import("//build_overrides/pigweed.gni") -} - if (chip_enable_openthread) { import("//build_overrides/openthread.gni") import("//build_overrides/ot_br_posix.gni") @@ -141,10 +137,6 @@ static_library("Linux") { public_deps += [ "dbus/openthread" ] } - if (chip_use_pw_logging) { - deps += [ "$dir_pw_log" ] - } - if (chip_enable_wifi) { sources += [ "NetworkCommissioningWiFiDriver.cpp" ] @@ -162,9 +154,5 @@ source_set("logging") { "${chip_root}/src/platform/logging:headers", ] - if (chip_use_pw_logging) { - deps += [ "$dir_pw_log" ] - } - sources = [ "Logging.cpp" ] } diff --git a/src/platform/Linux/Logging.cpp b/src/platform/Linux/Logging.cpp index 25e132e1a12b76..8a247f5e848495 100644 --- a/src/platform/Linux/Logging.cpp +++ b/src/platform/Linux/Logging.cpp @@ -12,10 +12,6 @@ #include #include -#if CHIP_USE_PW_LOGGING -#include -#endif // CHIP_USE_PW_LOGGING - namespace chip { namespace DeviceLayer { @@ -43,7 +39,6 @@ void LogV(const char * module, uint8_t category, const char * msg, va_list v) // indicate the error occurred during getting time. gettimeofday(&tv, nullptr); -#if !CHIP_USE_PW_LOGGING // Lock standard output, so a single log line will not be corrupted in case // where multiple threads are using logging subsystem at the same time. flockfile(stdout); @@ -55,30 +50,6 @@ void LogV(const char * module, uint8_t category, const char * msg, va_list v) fflush(stdout); funlockfile(stdout); -#else // !CHIP_USE_PW_LOGGING - char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; - snprintf(formattedMsg, sizeof(formattedMsg), - "[%" PRIu64 ".%06" PRIu64 "][%lld:%lld] CHIP:%s: ", static_cast(tv.tv_sec), - static_cast(tv.tv_usec), static_cast(syscall(SYS_getpid)), - static_cast(syscall(SYS_gettid)), module); - size_t len = strnlen(formattedMsg, sizeof(formattedMsg)); - vsnprintf(formattedMsg + len, sizeof(formattedMsg) - len, msg, v); - - switch (static_cast(category)) - { - case kLogCategory_Error: - PW_LOG_ERROR("%s", formattedMsg); - break; - case kLogCategory_Progress: - PW_LOG_INFO("%s", formattedMsg); - break; - case kLogCategory_Detail: - case kLogCategory_None: - case kLogCategory_Automation: - PW_LOG_DEBUG("%s", formattedMsg); - break; - } -#endif // !CHIP_USE_PW_LOGGING // Let the application know that a log message has been emitted. DeviceLayer::OnLogOutput(); diff --git a/src/platform/NuttX/BUILD.gn b/src/platform/NuttX/BUILD.gn index 346c7d60ed0bdf..65113454ee06fb 100644 --- a/src/platform/NuttX/BUILD.gn +++ b/src/platform/NuttX/BUILD.gn @@ -22,10 +22,6 @@ import("${chip_root}/src/platform/device.gni") assert(chip_device_platform == "linux" || chip_device_platform == "nuttx") -if (chip_use_pw_logging) { - import("//build_overrides/pigweed.gni") -} - if (chip_enable_openthread) { import("//build_overrides/openthread.gni") import("//build_overrides/ot_br_posix.gni") @@ -156,9 +152,5 @@ source_set("logging") { "${chip_root}/src/platform/logging:headers", ] - if (chip_use_pw_logging) { - deps += [ "$dir_pw_log" ] - } - sources = [ "Logging.cpp" ] } diff --git a/src/platform/NuttX/Logging.cpp b/src/platform/NuttX/Logging.cpp index ea95fdc4fbc7ef..6d92a2ba54eb5a 100644 --- a/src/platform/NuttX/Logging.cpp +++ b/src/platform/NuttX/Logging.cpp @@ -12,10 +12,6 @@ #include #include -#if CHIP_USE_PW_LOGGING -#include -#endif // CHIP_USE_PW_LOGGING - namespace chip { namespace DeviceLayer { @@ -43,7 +39,6 @@ void LogV(const char * module, uint8_t category, const char * msg, va_list v) // indicate the error occurred during getting time. gettimeofday(&tv, nullptr); -#if !CHIP_USE_PW_LOGGING // Lock standard output, so a single log line will not be corrupted in case // where multiple threads are using logging subsystem at the same time. flockfile(stdout); @@ -55,30 +50,6 @@ void LogV(const char * module, uint8_t category, const char * msg, va_list v) fflush(stdout); funlockfile(stdout); -#else // !CHIP_USE_PW_LOGGING - char formattedMsg[CHIP_CONFIG_LOG_MESSAGE_MAX_SIZE]; - snprintf(formattedMsg, sizeof(formattedMsg), - "[%" PRIu64 ".%06" PRIu64 "][%lld:%lld] CHIP:%s: ", static_cast(tv.tv_sec), - static_cast(tv.tv_usec), static_cast(syscall(SYS_getpid)), - static_cast(syscall(SYS_gettid)), module); - size_t len = strnlen(formattedMsg, sizeof(formattedMsg)); - vsnprintf(formattedMsg + len, sizeof(formattedMsg) - len, msg, v); - - switch (static_cast(category)) - { - case kLogCategory_Error: - PW_LOG_ERROR("%s", formattedMsg); - break; - case kLogCategory_Progress: - PW_LOG_INFO("%s", formattedMsg); - break; - case kLogCategory_Detail: - case kLogCategory_None: - case kLogCategory_Automation: - PW_LOG_DEBUG("%s", formattedMsg); - break; - } -#endif // !CHIP_USE_PW_LOGGING // Let the application know that a log message has been emitted. DeviceLayer::OnLogOutput(); diff --git a/src/platform/logging/BUILD.gn b/src/platform/logging/BUILD.gn index eb3c62154ce436..e415448a7f12d1 100644 --- a/src/platform/logging/BUILD.gn +++ b/src/platform/logging/BUILD.gn @@ -12,10 +12,6 @@ group("default") { if (chip_logging_backend == "platform") { deps = [] - if (chip_use_pw_logging) { - deps += [ "$dir_pw_log" ] - } - if (chip_device_platform == "cyw30739") { deps += [ "${chip_root}/src/platform/Infineon/CYW30739:logging" ] } else if (chip_device_platform == "psoc6") { diff --git a/src/pw_backends/assert/BUILD.gn b/src/pw_backends/assert/BUILD.gn new file mode 100644 index 00000000000000..5da1b7836b23a8 --- /dev/null +++ b/src/pw_backends/assert/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2024 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("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") + +import("$dir_pw_build/facade.gni") + +config("public_include_path") { + include_dirs = [ "public" ] + visibility = [ ":*" ] +} + +config("backend_config") { + include_dirs = [ "public_overrides" ] + visibility = [ ":*" ] +} + +pw_facade("handler") { + backend = "${chip_root}/src/pw_backends/assert:assert.impl" + public_configs = [ ":public_include_path" ] + public_deps = [ "$dir_pw_preprocessor" ] + public = [ "public/pw_assert_matter/handler.h" ] +} + +pw_source_set("assert") { + public_configs = [ + ":backend_config", + ":public_include_path", + ] + public = [ + "public/pw_assert_matter/handler.h", + "public_overrides/pw_assert_backend/check_backend.h", + ] + public_deps = [ ":handler.facade" ] +} + +# A basic handler backend using pw_sys_io. +pw_source_set("assert.impl") { + # Turn off GN check since this target intentionally leaves out deps to avoid + # circular dependencies. + check_includes = false + + configs = [ + "$dir_pw_string:public_include_path", + "$dir_pw_result:public_include_path", + ] + + deps = [ + ":handler.facade", + "$dir_pw_assert:config", + "$dir_pw_preprocessor", + "$dir_pw_string:builder", + "${chip_root}/src/lib/support", + ] + sources = [ "handler.cpp" ] +} diff --git a/src/pw_backends/assert/handler.cpp b/src/pw_backends/assert/handler.cpp new file mode 100644 index 00000000000000..b776cb892d1e64 --- /dev/null +++ b/src/pw_backends/assert/handler.cpp @@ -0,0 +1,42 @@ +/* + * 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 + +#include +#include +#include + +void pw_assert_matter_HandleFailure(const char * file_name, int line_number, const char * function_name, const char * format, ...) +{ + + pw::StringBuffer<64> builder; + + builder.Format("Assertion failed: %s:%d (in %s):", file_name, line_number, function_name); + + va_list args; + va_start(args, format); + builder.FormatVaList(format, args); + va_end(args); + + ChipLogError(Support, "%s", builder.c_str()); + chipDie(); +} + +extern "C" void pw_assert_HandleFailure(void) +{ + pw_assert_matter_HandleFailure("", -1, "", "Crash: PW_ASSERT() or PW_DASSERT() failure"); +} diff --git a/src/pw_backends/assert/public/pw_assert_matter/handler.h b/src/pw_backends/assert/public/pw_assert_matter/handler.h new file mode 100644 index 00000000000000..efeac9a1c71d4b --- /dev/null +++ b/src/pw_backends/assert/public/pw_assert_matter/handler.h @@ -0,0 +1,35 @@ +/* + * 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. + */ +#pragma once + +#include "pw_preprocessor/compiler.h" +#include "pw_preprocessor/util.h" + +PW_EXTERN_C_START + +// Application-defined assert failure handler for pw_assert_basic. +// file_name - may be nullptr if not available +// line_number - may be -1 if not available +// function_name - may be nullptr if not available +// format & varags - The assert reason can be built using the format string and +// the varargs. +// +// Applications must define this function; it is not defined by pw_assert_basic. +void pw_assert_matter_HandleFailure(const char * file_name, int line_number, const char * function_name, const char * format, ...) + PW_PRINTF_FORMAT(4, 5) PW_NO_RETURN; + +PW_EXTERN_C_END diff --git a/src/pw_backends/assert/public_overrides/pw_assert_backend/check_backend.h b/src/pw_backends/assert/public_overrides/pw_assert_backend/check_backend.h new file mode 100644 index 00000000000000..af6c76aa0db302 --- /dev/null +++ b/src/pw_backends/assert/public_overrides/pw_assert_backend/check_backend.h @@ -0,0 +1,66 @@ +/* + * 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. + */ +#pragma once + +#include "pw_assert_matter/handler.h" + +// Use __PRETTY_FUNCTION__, a GNU extension, in place of the __func__ macro when +// supported. __PRETTY_FUNCTION__ expands to the full C++ function name. +#ifdef __GNUC__ +#define _PW_ASSERT_MATTER_FUNCTION_NAME __PRETTY_FUNCTION__ +#else +#define _PW_ASSERT_MATTER_FUNCTION_NAME __func__ +#endif // __GNUC__ + +// Die with a message with many attributes included. This is the crash macro +// frontend that funnels everything into the C handler provided by the user, +// pw_assert_MATTER_HandleFailure(). +#define PW_HANDLE_CRASH(...) \ + pw_assert_matter_HandleFailure(__FILE__, __LINE__, _PW_ASSERT_MATTER_FUNCTION_NAME PW_COMMA_ARGS(__VA_ARGS__)) + +// Die with a message with many attributes included. This is the crash macro +// frontend that funnels everything into the C handler provided by the user, +// pw_assert_matter_HandleFailure(). +#define PW_HANDLE_ASSERT_FAILURE(condition_string, message, ...) \ + pw_assert_matter_HandleFailure(__FILE__, __LINE__, _PW_ASSERT_MATTER_FUNCTION_NAME, \ + "Check failed: " condition_string ". " message PW_COMMA_ARGS(__VA_ARGS__)) + +// Sample assert failure message produced by the below implementation: +// +// Check failed: current_sensor (=610) < new_sensor (=50). More details! +// +// Putting the value next to the operand makes the string easier to read. + +// clang-format off +// This is too hairy for clang format to handle and retain readability. +#define PW_HANDLE_ASSERT_BINARY_COMPARE_FAILURE(arg_a_str, \ + arg_a_val, \ + comparison_op_str, \ + arg_b_str, \ + arg_b_val, \ + type_fmt, \ + message, ...) \ + pw_assert_matter_HandleFailure( \ + __FILE__, \ + __LINE__, \ + _PW_ASSERT_MATTER_FUNCTION_NAME, \ + "Check failed: " \ + arg_a_str " (=" type_fmt ") " \ + comparison_op_str " " \ + arg_b_str " (=" type_fmt ")" \ + ". " message, \ + arg_a_val, arg_b_val PW_COMMA_ARGS(__VA_ARGS__)) diff --git a/src/pw_backends/log/BUILD.gn b/src/pw_backends/log/BUILD.gn new file mode 100644 index 00000000000000..b935a686506fcf --- /dev/null +++ b/src/pw_backends/log/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2024 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("//build_overrides/build.gni") +import("//build_overrides/chip.gni") +import("//build_overrides/pigweed.gni") + +import("$dir_pw_build/facade.gni") + +config("public_include_path") { + include_dirs = [ "public" ] + visibility = [ ":*" ] +} + +config("backend_config") { + include_dirs = [ "public_overrides" ] + visibility = [ ":*" ] +} + +pw_facade("handler") { + backend = "${chip_root}/src/pw_backends/log:log.impl" + public_configs = [ ":public_include_path" ] + public_deps = [ + "$dir_pw_preprocessor", + "${chip_root}/src/lib/support:text_only_logging", + ] + public = [ + "public/pw_log_matter/log_matter.h", + "public_overrides/pw_log_backend/log_backend.h", + ] +} + +pw_source_set("log") { + public_configs = [ + ":backend_config", + ":public_include_path", + ] + public = [ "public/pw_log_matter/log_matter.h" ] + public_deps = [ + ":handler.facade", + "${chip_root}/src/lib/support:text_only_logging", + ] +} + +# A basic handler backend using pw_sys_io. +pw_source_set("log.impl") { + # Turn off GN check since this target intentionally leaves out deps to avoid + # circular dependencies. + check_includes = false + + configs = [ + "$dir_pw_string:public_include_path", + "$dir_pw_result:public_include_path", + ] + + deps = [ + ":handler.facade", + "$dir_pw_log:config", + "$dir_pw_preprocessor", + "$dir_pw_string:builder", + "${chip_root}/src/lib/support", + ] + sources = [] +} diff --git a/src/pw_backends/log/public/pw_log_matter/log_matter.h b/src/pw_backends/log/public/pw_log_matter/log_matter.h new file mode 100644 index 00000000000000..c956bcadb7aa68 --- /dev/null +++ b/src/pw_backends/log/public/pw_log_matter/log_matter.h @@ -0,0 +1,52 @@ +/* + * 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. + */ +#pragma once + +#include "lib/support/logging/Constants.h" +#include +#include + +// Pigweed defines more granular logging than CHIP. +// we match the following: +// - Detail == DEBUG +// - Progress == INFO +// - ERROR = WARN, ERROR, CRITICAL + +constexpr chip::Logging::LogCategory PwLogLevelToChipLogCategory(int level) +{ + switch (level) + { + case PW_LOG_LEVEL_DEBUG: + return chip::Logging::kLogCategory_Detail; + case PW_LOG_LEVEL_INFO: + return chip::Logging::kLogCategory_Progress; + default: + return chip::Logging::kLogCategory_Error; + } +} + +#define PW_LOG_DEBUG(...) ChipLogDetail(NotSpecified, __VA_ARGS__) +#define PW_LOG_INFO(...) ChipLogProgress(NotSpecified, __VA_ARGS__) +#define PW_LOG_WARN(...) ChipLogError(NotSpecified, __VA_ARGS__) +#define PW_LOG_ERROR(...) ChipLogError(NotSpecified, __VA_ARGS__) +#define PW_LOG_CRITICAL(...) ChipLogError(NotSpecified, __VA_ARGS__) + +// Log a message with many attributes included. +// +// This is the main macro that functions not included above will use +#define PW_HANDLE_LOG(level, module, flags, message, ...) \ + ChipInternalLogImpl(NotSpecified, PwLogLevelToChipLogCategory(level), message, __VA_ARGS__) diff --git a/src/lib/support/pw_log_chip/public_overrides/pw_log_backend/log_backend.h b/src/pw_backends/log/public_overrides/pw_log_backend/log_backend.h similarity index 74% rename from src/lib/support/pw_log_chip/public_overrides/pw_log_backend/log_backend.h rename to src/pw_backends/log/public_overrides/pw_log_backend/log_backend.h index aee9d4abff0403..8e9e15947ab0d9 100644 --- a/src/lib/support/pw_log_chip/public_overrides/pw_log_backend/log_backend.h +++ b/src/pw_backends/log/public_overrides/pw_log_backend/log_backend.h @@ -1,5 +1,6 @@ /* - * Copyright (c) 2020 Project CHIP Authors. + * 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. @@ -13,12 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -/** - * @file - * This header interfaces with the Pigweed logging facade by overriding - * the backend header. - */ #pragma once -#include "pw_log_chip/log_chip.h" +#include "pw_log_matter/log_matter.h" diff --git a/src/python_testing/TC_MCORE_FS_1_5.py b/src/python_testing/TC_MCORE_FS_1_5.py index 59549fd0bcdc9b..e8d6b3e6784a90 100755 --- a/src/python_testing/TC_MCORE_FS_1_5.py +++ b/src/python_testing/TC_MCORE_FS_1_5.py @@ -212,7 +212,7 @@ async def test_TC_MCORE_FS_1_5(self): time_remaining = report_waiting_timeout_delay_sec parts_list_endpoint_count_from_step_1 = len(step_1_dut_parts_list) - step_3_dut_parts_list = None + step_3_dut_parts_list = [] while time_remaining > 0: try: item = parts_list_queue.get(block=True, timeout=time_remaining) @@ -304,16 +304,20 @@ async def test_TC_MCORE_FS_1_5(self): endpoint, attribute, value = item['endpoint'], item['attribute'], item['value'] # Record arrival of an expected subscription change when seen - if endpoint == newly_added_endpoint and attribute == Clusters.AdministratorCommissioning.Attributes.WindowStatus: + if endpoint == newly_added_endpoint and attribute == cadmin_attr.WindowStatus: + if value != th_server_direct_cadmin[cadmin_attr.WindowStatus]: + logging.info("Window status is %r, waiting for %r", value, + th_server_direct_cadmin[cadmin_attr.WindowStatus]) + continue cadmin_sub_new_data = True break - except queue.Empty: # No error, we update timeouts and keep going pass - - elapsed = time.time() - start_time - time_remaining = report_waiting_timeout_delay_sec - elapsed + finally: + # each iteration will alter timing + elapsed = time.time() - start_time + time_remaining = report_waiting_timeout_delay_sec - elapsed asserts.assert_true(cadmin_sub_new_data, "Timed out waiting for DUT to reflect AdministratorCommissioning attributes for bridged device") diff --git a/src/python_testing/matter_testing_infrastructure/chip/testing/tasks.py b/src/python_testing/matter_testing_infrastructure/chip/testing/tasks.py index 9b3a0b111fadbd..01351cb987dcc9 100644 --- a/src/python_testing/matter_testing_infrastructure/chip/testing/tasks.py +++ b/src/python_testing/matter_testing_infrastructure/chip/testing/tasks.py @@ -14,10 +14,11 @@ import logging import re +import shlex import subprocess import sys import threading -from typing import BinaryIO, Callable, List, Optional, Union +from typing import BinaryIO, Callable, Optional, Union def forward_f(f_in: BinaryIO, @@ -29,6 +30,8 @@ def forward_f(f_in: BinaryIO, This function can optionally post-process received lines using a callback function. """ + + # NOTE: readlines would block here, so read line by line instead while line := f_in.readline(): if cb is not None: line = cb(line, is_stderr) @@ -39,7 +42,7 @@ def forward_f(f_in: BinaryIO, class Subprocess(threading.Thread): """Run a subprocess in a thread.""" - def __init__(self, program: str, *args: List[str], + def __init__(self, program: str, *args, output_cb: Optional[Callable[[bytes, bool], bytes]] = None, f_stdout: BinaryIO = sys.stdout.buffer, f_stderr: BinaryIO = sys.stderr.buffer): @@ -62,7 +65,7 @@ def __init__(self, program: str, *args: List[str], self.output_cb = output_cb self.f_stdout = f_stdout self.f_stderr = f_stderr - self.output_match = None + self.output_match: Optional[re.Pattern] = None self.returncode = None def _set_output_match(self, pattern: Union[str, re.Pattern]): @@ -81,11 +84,14 @@ def _check_output(self, line: bytes, is_stderr: bool): def run(self): """Thread entry point.""" - logging.info("RUN: %s %s", self.program, " ".join(self.args)) - self.p = subprocess.Popen([self.program] + list(self.args), + command = [self.program] + list(self.args) + + logging.info("RUN: %s", shlex.join(command)) + self.p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=subprocess.PIPE) + stderr=subprocess.PIPE, + bufsize=0) self.event_started.set() # Forward stdout and stderr with a tag attached. diff --git a/src/test_driver/efr32/args.gni b/src/test_driver/efr32/args.gni index c4bc72c2a3cd97..0cdcbbf8df1050 100644 --- a/src/test_driver/efr32/args.gni +++ b/src/test_driver/efr32/args.gni @@ -30,8 +30,8 @@ openthread_external_platform = pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex" -pw_assert_BACKEND = "$dir_pw_assert_log" -pw_log_BACKEND = "$dir_pw_log_basic" +pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert" +pw_log_BACKEND = "${chip_root}/src/pw_backends/log" pw_unit_test_BACKEND = "$dir_pw_unit_test:light" From ffaeda4e16d2109353d1763035bbe82e1eaaae5f Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Wed, 6 Nov 2024 16:32:48 -0800 Subject: [PATCH 076/121] [Fabric-Admin] Merge CommissioningDelegate and PairingDelegate (#36388) --- .../commands/fabric-sync/FabricSyncCommand.cpp | 6 +++--- .../commands/fabric-sync/FabricSyncCommand.h | 6 +++--- .../fabric-admin/device_manager/PairingManager.cpp | 7 ++++--- .../fabric-admin/device_manager/PairingManager.h | 14 +++----------- 4 files changed, 13 insertions(+), 20 deletions(-) diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp index e21f02f2ecb6b4..355b704c2ee654 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp @@ -87,7 +87,7 @@ CHIP_ERROR FabricSyncAddBridgeCommand::RunCommand(NodeId remoteId) return CHIP_NO_ERROR; } - PairingManager::Instance().SetCommissioningDelegate(this); + PairingManager::Instance().SetPairingDelegate(this); mBridgeNodeId = remoteId; @@ -180,7 +180,7 @@ CHIP_ERROR FabricSyncAddLocalBridgeCommand::RunCommand(NodeId deviceId) return CHIP_NO_ERROR; } - PairingManager::Instance().SetCommissioningDelegate(this); + PairingManager::Instance().SetPairingDelegate(this); mLocalBridgeNodeId = deviceId; if (mSetupPINCode.HasValue()) @@ -252,7 +252,7 @@ void FabricSyncDeviceCommand::OnCommissioningWindowOpened(NodeId deviceId, CHIP_ { NodeId nodeId = DeviceMgr().GetNextAvailableNodeId(); - PairingManager::Instance().SetCommissioningDelegate(this); + PairingManager::Instance().SetPairingDelegate(this); mAssignedNodeId = nodeId; usleep(kCommissionPrepareTimeMs * 1000); diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h index 82442acafa6af5..444fb96a9ad402 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.h @@ -26,7 +26,7 @@ namespace admin { // Constants constexpr uint32_t kCommissionPrepareTimeMs = 500; -class FabricSyncAddBridgeCommand : public CHIPCommand, public CommissioningDelegate +class FabricSyncAddBridgeCommand : public CHIPCommand, public PairingDelegate { public: FabricSyncAddBridgeCommand(CredentialIssuerCommands * credIssuerCommands) : CHIPCommand("add-bridge", credIssuerCommands) @@ -71,7 +71,7 @@ class FabricSyncRemoveBridgeCommand : public CHIPCommand, public PairingDelegate chip::NodeId mBridgeNodeId; }; -class FabricSyncAddLocalBridgeCommand : public CHIPCommand, public CommissioningDelegate +class FabricSyncAddLocalBridgeCommand : public CHIPCommand, public PairingDelegate { public: FabricSyncAddLocalBridgeCommand(CredentialIssuerCommands * credIssuerCommands) : @@ -116,7 +116,7 @@ class FabricSyncRemoveLocalBridgeCommand : public CHIPCommand, public PairingDel chip::NodeId mLocalBridgeNodeId; }; -class FabricSyncDeviceCommand : public CHIPCommand, public CommissioningWindowDelegate, public CommissioningDelegate +class FabricSyncDeviceCommand : public CHIPCommand, public CommissioningWindowDelegate, public PairingDelegate { public: FabricSyncDeviceCommand(CredentialIssuerCommands * credIssuerCommands) : CHIPCommand("sync-device", credIssuerCommands) diff --git a/examples/fabric-admin/device_manager/PairingManager.cpp b/examples/fabric-admin/device_manager/PairingManager.cpp index b13af2dbe46541..40194f9a686056 100644 --- a/examples/fabric-admin/device_manager/PairingManager.cpp +++ b/examples/fabric-admin/device_manager/PairingManager.cpp @@ -312,10 +312,10 @@ void PairingManager::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err) ChipLogProgress(NotSpecified, "Device commissioning Failure: %s", ErrorStr(err)); } - if (mCommissioningDelegate) + if (mPairingDelegate) { - mCommissioningDelegate->OnCommissioningComplete(nodeId, err); - SetCommissioningDelegate(nullptr); + mPairingDelegate->OnCommissioningComplete(nodeId, err); + SetPairingDelegate(nullptr); } } @@ -555,6 +555,7 @@ void PairingManager::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E if (self->mPairingDelegate) { self->mPairingDelegate->OnDeviceRemoved(nodeId, err); + self->SetPairingDelegate(nullptr); } #if defined(PW_RPC_ENABLED) diff --git a/examples/fabric-admin/device_manager/PairingManager.h b/examples/fabric-admin/device_manager/PairingManager.h index 2318acd5f97297..77cec24876e9f2 100644 --- a/examples/fabric-admin/device_manager/PairingManager.h +++ b/examples/fabric-admin/device_manager/PairingManager.h @@ -37,18 +37,12 @@ class CommissioningWindowDelegate virtual ~CommissioningWindowDelegate() = default; }; -class CommissioningDelegate -{ -public: - virtual void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) = 0; - virtual ~CommissioningDelegate() = default; -}; - class PairingDelegate { public: - virtual void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) = 0; - virtual ~PairingDelegate() = default; + virtual void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) {} + virtual void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) {} + virtual ~PairingDelegate() = default; }; /** @@ -85,7 +79,6 @@ class PairingManager : public chip::Controller::DevicePairingDelegate, CHIP_ERROR Init(chip::Controller::DeviceCommissioner * commissioner, CredentialIssuerCommands * credIssuerCmds); void SetOpenCommissioningWindowDelegate(CommissioningWindowDelegate * delegate) { mCommissioningWindowDelegate = delegate; } - void SetCommissioningDelegate(CommissioningDelegate * delegate) { mCommissioningDelegate = delegate; } void SetPairingDelegate(PairingDelegate * delegate) { mPairingDelegate = delegate; } PairingDelegate * GetPairingDelegate() { return mPairingDelegate; } @@ -181,7 +174,6 @@ class PairingManager : public chip::Controller::DevicePairingDelegate, CredentialIssuerCommands * mCredIssuerCmds = nullptr; CommissioningWindowDelegate * mCommissioningWindowDelegate = nullptr; - CommissioningDelegate * mCommissioningDelegate = nullptr; PairingDelegate * mPairingDelegate = nullptr; chip::NodeId mNodeId = chip::kUndefinedNodeId; From e3c6522d0c2390f7a7e14ac96b4bba3562b1b6f5 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Wed, 6 Nov 2024 19:57:51 -0500 Subject: [PATCH 077/121] Add an API on MTRDevice to wait for attributes to reach certain values. (#36205) * Add an API on MTRDevice to wait for attributes to reach certain values. * Address review comments. * Address review comments. * Implement cancellation of attribute waiters. * Addressing more review comments. * Address review comments. * Fix build failure --- .../Framework/CHIP/MTRAttributeValueWaiter.h | 38 +++++ .../Framework/CHIP/MTRAttributeValueWaiter.mm | 137 ++++++++++++++++ .../CHIP/MTRAttributeValueWaiter_Internal.h | 51 ++++++ src/darwin/Framework/CHIP/MTRDevice.h | 21 +++ src/darwin/Framework/CHIP/MTRDevice.mm | 152 +++++++++++++++++- .../Framework/CHIP/MTRDevice_Concrete.mm | 2 + .../Framework/CHIP/MTRDevice_Internal.h | 10 ++ src/darwin/Framework/CHIP/MTRDevice_XPC.mm | 27 ++++ src/darwin/Framework/CHIP/Matter.h | 1 + .../Framework/CHIPTests/MTRDeviceTests.m | 135 +++++++++++++++- .../Matter.xcodeproj/project.pbxproj | 12 ++ 11 files changed, 577 insertions(+), 9 deletions(-) create mode 100644 src/darwin/Framework/CHIP/MTRAttributeValueWaiter.h create mode 100644 src/darwin/Framework/CHIP/MTRAttributeValueWaiter.mm create mode 100644 src/darwin/Framework/CHIP/MTRAttributeValueWaiter_Internal.h diff --git a/src/darwin/Framework/CHIP/MTRAttributeValueWaiter.h b/src/darwin/Framework/CHIP/MTRAttributeValueWaiter.h new file mode 100644 index 00000000000000..98ee86a800da09 --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRAttributeValueWaiter.h @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2024 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 +#import + +NS_ASSUME_NONNULL_BEGIN + +MTR_NEWLY_AVAILABLE +@interface MTRAttributeValueWaiter : NSObject +- (instancetype)init NS_UNAVAILABLE; ++ (instancetype)new NS_UNAVAILABLE; + +/** + * Cancel the wait for the set of attribute path/value pairs represented by this + * MTRAttributeValueWaiter. If the completion has not been called yet, it will + * becalled with MTRErrorCodeCancelled. + */ +- (void)cancel; + +@property (readonly, nonatomic) NSUUID * UUID; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRAttributeValueWaiter.mm b/src/darwin/Framework/CHIP/MTRAttributeValueWaiter.mm new file mode 100644 index 00000000000000..10d0b9f8e1393d --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRAttributeValueWaiter.mm @@ -0,0 +1,137 @@ +/** + * Copyright (c) 2024 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 + +#import + +#import "MTRAttributeValueWaiter_Internal.h" +#import "MTRDevice_Internal.h" +#import "MTRLogging_Internal.h" + +@implementation MTRAwaitedAttributeState +- (instancetype)initWithValue:(MTRDeviceDataValueDictionary)value +{ + if (self = [super init]) { + _valueSatisfied = NO; + _value = value; + } + + return self; +} +@end + +MTR_DIRECT_MEMBERS +@interface MTRAttributeValueWaiter () +@property (nonatomic, retain) NSDictionary * valueExpectations; +// Protected by the MTRDevice's lock. +@property (nonatomic, readwrite, retain) dispatch_queue_t queue; +@property (nonatomic, readwrite, copy, nullable) MTRStatusCompletion completion; +@property (nonatomic, readonly, retain) MTRDevice * device; +@end + +@implementation MTRAttributeValueWaiter + +- (instancetype)initWithDevice:(MTRDevice *)device values:(NSDictionary *)values queue:(dispatch_queue_t)queue completion:(MTRStatusCompletion)completion +{ + if (self = [super init]) { + auto * valueExpectations = [NSMutableDictionary dictionaryWithCapacity:values.count]; + for (MTRAttributePath * path in values) { + auto * valueExpectation = [[MTRAwaitedAttributeState alloc] initWithValue:values[path]]; + valueExpectations[path] = valueExpectation; + } + _valueExpectations = valueExpectations; + _queue = queue; + _completion = completion; + _device = device; + _UUID = [NSUUID UUID]; + } + + return self; +} + +- (void)dealloc +{ + [self cancel]; +} + +- (void)cancel +{ + [self.device _attributeWaitCanceled:self]; +} + +- (BOOL)_attributeValue:(MTRDeviceDataValueDictionary)value reportedForPath:(MTRAttributePath *)path byDevice:(MTRDevice *)device +{ + MTRAwaitedAttributeState * valueExpectation = self.valueExpectations[path]; + if (!valueExpectation) { + // We don't care about this one. + return NO; + } + + MTRDeviceDataValueDictionary expectedValue = valueExpectation.value; + valueExpectation.valueSatisfied = [device _attributeDataValue:value satisfiesValueExpectation:expectedValue]; + return valueExpectation.valueSatisfied; +} + +- (BOOL)allValuesSatisfied +{ + for (MTRAwaitedAttributeState * valueExpectation in [self.valueExpectations allValues]) { + if (!valueExpectation.valueSatisfied) { + return NO; + } + } + + return YES; +} + +- (void)_notifyWithError:(NSError * _Nullable)error +{ + // This is always called with the device lock held, so checking and mutating + // self.completion here is atomic. + if (!self.completion) { + return; + } + + if (self.expirationTimer != nil) { + dispatch_source_cancel(self.expirationTimer); + self.expirationTimer = nil; + } + + if (!error) { + MTR_LOG("%@ %p wait for attribute values completed", self, self); + } else if (error.domain == MTRErrorDomain && error.code == MTRErrorCodeTimeout) { + MTR_LOG("%@ %p wait for attribute values timed out", self, self); + } else if (error.domain == MTRErrorDomain && error.code == MTRErrorCodeCancelled) { + MTR_LOG("%@ %p wait for attribute values canceled", self, self); + } else { + MTR_LOG("%@ %p wait for attribute values unknown error: %@", self, self, error); + } + + auto completion = self.completion; + auto queue = self.queue; + self.completion = nil; + self.queue = nil; + dispatch_async(queue, ^{ + completion(error); + }); +} + +- (NSString *)description +{ + return [NSString stringWithFormat:@"<%@: %@>", NSStringFromClass(self.class), self.UUID]; +} + +@end diff --git a/src/darwin/Framework/CHIP/MTRAttributeValueWaiter_Internal.h b/src/darwin/Framework/CHIP/MTRAttributeValueWaiter_Internal.h new file mode 100644 index 00000000000000..8d4a7999691a0d --- /dev/null +++ b/src/darwin/Framework/CHIP/MTRAttributeValueWaiter_Internal.h @@ -0,0 +1,51 @@ +/** + * Copyright (c) 2024 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 +#import // For MTRAttributePath. +#import +#import + +#import "MTRDefines_Internal.h" + +NS_ASSUME_NONNULL_BEGIN + +// Represents the state of a single attribute being waited for: has the path and +// value being waited for in the response-value and whether the value has been +// reached. +MTR_DIRECT_MEMBERS +@interface MTRAwaitedAttributeState : NSObject +@property (nonatomic, assign, readwrite) BOOL valueSatisfied; +@property (nonatomic, retain, readonly) MTRDeviceDataValueDictionary value; + +- (instancetype)initWithValue:(MTRDeviceDataValueDictionary)value; +@end + +@interface MTRAttributeValueWaiter () + +@property (nonatomic, readonly) BOOL allValuesSatisfied; +@property (nonatomic, retain, readwrite, nullable) dispatch_source_t expirationTimer; + +- (instancetype)initWithDevice:(MTRDevice *)device values:(NSDictionary *)values queue:(dispatch_queue_t)queue completion:(MTRStatusCompletion)completion; + +// Returns YES if after this report the waiter might be done waiting, NO otherwise. +- (BOOL)_attributeValue:(MTRDeviceDataValueDictionary)value reportedForPath:(MTRAttributePath *)path byDevice:(MTRDevice *)device; + +- (void)_notifyWithError:(NSError * _Nullable)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/darwin/Framework/CHIP/MTRDevice.h b/src/darwin/Framework/CHIP/MTRDevice.h index 2055bf8a877690..16df47b12d0411 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.h +++ b/src/darwin/Framework/CHIP/MTRDevice.h @@ -16,6 +16,7 @@ */ #import +#import #import #import @@ -337,6 +338,26 @@ MTR_AVAILABLE(ios(16.1), macos(13.0), watchos(9.1), tvos(16.1)) queue:(dispatch_queue_t)queue completion:(void (^)(NSURL * _Nullable url, NSError * _Nullable error))completion MTR_AVAILABLE(ios(17.6), macos(14.6), watchos(10.6), tvos(17.6)); + +/** + * Sets up the provided completion to be called when any of the following + * happens: + * + * 1) A set of attributes reaches certain values: completion called with nil. + * 2) The provided timeout expires: completion called with MTRErrorCodeTimeout error. + * 3) The wait is canceled: completion called with MTRErrorCodeCancelled error. + * + * If the MTRAttributeValueWaiter is destroyed before the + * completion is called, that is treated the same as canceling the waiter. + * + * The attributes and values to wait for are represented as a dictionary which + * has the attribute paths as keys and the expected data-values as values. + */ +- (MTRAttributeValueWaiter *)waitForAttributeValues:(NSDictionary *> *)values + timeout:(NSTimeInterval)timeout + queue:(dispatch_queue_t)queue + completion:(void (^)(NSError * _Nullable error))completion MTR_NEWLY_AVAILABLE; + @end MTR_EXTERN NSString * const MTRPreviousDataKey MTR_AVAILABLE(ios(17.6), macos(14.6), watchos(10.6), tvos(17.6)); diff --git a/src/darwin/Framework/CHIP/MTRDevice.mm b/src/darwin/Framework/CHIP/MTRDevice.mm index 2337d0eae625f5..7c6414d2a1d9c0 100644 --- a/src/darwin/Framework/CHIP/MTRDevice.mm +++ b/src/darwin/Framework/CHIP/MTRDevice.mm @@ -18,6 +18,7 @@ #import #import +#import "MTRAttributeValueWaiter_Internal.h" #import "MTRBaseClusters.h" #import "MTRBaseDevice_Internal.h" #import "MTRCluster.h" @@ -25,6 +26,7 @@ #import "MTRConversion.h" #import "MTRDefines_Internal.h" #import "MTRDeviceController_Internal.h" +#import "MTRDeviceDataValidation.h" #import "MTRDevice_Internal.h" #import "MTRError_Internal.h" #import "MTRLogging_Internal.h" @@ -96,6 +98,12 @@ - (BOOL)unitTestSuppressTimeBasedReachabilityChanges:(MTRDevice *)device; @end #endif +MTR_DIRECT_MEMBERS +@interface MTRDevice () +// nil until the first time we need it. Access guarded by our lock. +@property (nonatomic, readwrite, nullable) NSHashTable * attributeValueWaiters; +@end + @implementation MTRDevice - (instancetype)initForSubclassesWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller @@ -124,6 +132,10 @@ - (void)dealloc { // TODO: retain cycle and clean up https://github.com/project-chip/connectedhomeip/issues/34267 MTR_LOG("MTRDevice dealloc: %p", self); + + // Locking because _cancelAllAttributeValueWaiters has os_unfair_lock_assert_owner(&_lock) + std::lock_guard lock(_lock); + [self _cancelAllAttributeValueWaiters]; } + (MTRDevice *)deviceWithNodeID:(NSNumber *)nodeID controller:(MTRDeviceController *)controller @@ -228,6 +240,7 @@ - (void)invalidate std::lock_guard lock(_lock); [_delegates removeAllObjects]; + [self _cancelAllAttributeValueWaiters]; } - (BOOL)_delegateExists @@ -631,7 +644,19 @@ - (BOOL)_attributeDataValue:(MTRDeviceDataValueDictionary)observed satisfiesValu return NO; } - if (![self _attributeDataValue:observedEntry[MTRDataKey] satisfiesValueExpectation:expectedEntry[MTRDataKey]]) { + MTRDeviceDataValueDictionary observedDataValue = observedEntry[MTRDataKey]; + if (!MTR_SAFE_CAST(observedDataValue, NSDictionary)) { + MTR_LOG_ERROR("%@ observed data-value is not an NSDictionary: %@", self, observedDataValue); + return NO; + } + + MTRDeviceDataValueDictionary expectedDataValue = expectedEntry[MTRDataKey]; + if (!MTR_SAFE_CAST(expectedDataValue, NSDictionary)) { + MTR_LOG_ERROR("%@ expected data-value is not an NSDictionary: %@", self, expectedDataValue); + return NO; + } + + if (![self _attributeDataValue:observedDataValue satisfiesValueExpectation:expectedDataValue]) { return NO; } } @@ -661,7 +686,7 @@ - (BOOL)_attributeDataValue:(MTRDeviceDataValueDictionary)observed satisfiesValu } for (NSDictionary * expectedField in expectedArray) { - if (![expectedField[MTRContextTagKey] isKindOfClass:NSNumber.class] || ![expectedField[MTRDataKey] isKindOfClass:NSDictionary.class]) { + if (!MTR_SAFE_CAST(expectedField, NSDictionary) || !MTR_SAFE_CAST(expectedField[MTRContextTagKey], NSNumber) || !MTR_SAFE_CAST(expectedField[MTRDataKey], NSDictionary)) { MTR_LOG_ERROR("%@ expected structure-value contains invalid field %@", self, expectedField); return NO; } @@ -672,7 +697,7 @@ - (BOOL)_attributeDataValue:(MTRDeviceDataValueDictionary)observed satisfiesValu // pretty small arrays, so the O(N^2) behavior here is ok. BOOL found = NO; for (NSDictionary * observedField in observedArray) { - if (![observedField[MTRContextTagKey] isKindOfClass:NSNumber.class] || ![observedField[MTRDataKey] isKindOfClass:NSDictionary.class]) { + if (!MTR_SAFE_CAST(observedField, NSDictionary) || !MTR_SAFE_CAST(observedField[MTRContextTagKey], NSNumber) || !MTR_SAFE_CAST(observedField[MTRDataKey], NSDictionary)) { MTR_LOG_ERROR("%@ observed structure-value contains invalid field %@", self, observedField); return NO; } @@ -710,6 +735,127 @@ - (BOOL)_attributeDataValue:(MTRDeviceDataValueDictionary)observed satisfiesValu return YES; } +#pragma mark - Handling of waits for attribute values + +- (MTRAttributeValueWaiter *)waitForAttributeValues:(NSDictionary *)values timeout:(NSTimeInterval)timeout queue:(dispatch_queue_t)queue completion:(void (^)(NSError * _Nullable error))completion +{ + // Check whether the values coming in make sense. + for (MTRAttributePath * path in values) { + MTRVerifyArgumentOrDie(MTRDataValueDictionaryIsWellFormed(values[path]), + ([NSString stringWithFormat:@"waitForAttributeValues handed invalid data-value %@ for path %@", path, values[path]])); + } + + // Check whether we have all these values already. + NSMutableArray * requestPaths = [NSMutableArray arrayWithCapacity:values.count]; + for (MTRAttributePath * path in values) { + [requestPaths addObject:[MTRAttributeRequestPath requestPathWithEndpointID:path.endpoint clusterID:path.cluster attributeID:path.attribute]]; + } + + NSArray * currentValues = [self readAttributePaths:requestPaths]; + + std::lock_guard lock(_lock); + auto * attributeWaiter = [[MTRAttributeValueWaiter alloc] initWithDevice:self values:values queue:queue completion:completion]; + + for (MTRDeviceResponseValueDictionary currentValue in currentValues) { + // Pretend as if this got reported, for purposes of the attribute + // waiter. + [attributeWaiter _attributeValue:currentValue[MTRDataKey] reportedForPath:currentValue[MTRAttributePathKey] byDevice:self]; + } + + if (attributeWaiter.allValuesSatisfied) { + MTR_LOG("%@ waitForAttributeValues no need to wait, values already match: %@", self, values); + [attributeWaiter _notifyWithError:nil]; + return attributeWaiter; + } + + // Otherwise, wait for the values to arrive or our timeout. + if (!self.attributeValueWaiters) { + self.attributeValueWaiters = [NSHashTable weakObjectsHashTable]; + } + [self.attributeValueWaiters addObject:attributeWaiter]; + + MTR_LOG("%@ waitForAttributeValues will wait up to %f seconds for %@", self, timeout, values); + dispatch_source_t timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue); + attributeWaiter.expirationTimer = timerSource; + + // Set a timer to go off after timeout, and not repeat. + dispatch_source_set_timer(timerSource, dispatch_time(DISPATCH_TIME_NOW, static_cast(timeout * static_cast(NSEC_PER_SEC))), DISPATCH_TIME_FOREVER, + // Allow .5 seconds of leeway; should be plenty, in practice. + static_cast(0.5 * static_cast(NSEC_PER_SEC))); + + mtr_weakify(attributeWaiter); + mtr_weakify(self); + dispatch_source_set_event_handler(timerSource, ^{ + dispatch_source_cancel(timerSource); + mtr_strongify(self); + mtr_strongify(attributeWaiter); + if (self != nil && attributeWaiter != nil) { + [self _attributeWaitTimedOut:attributeWaiter]; + } + }); + + dispatch_resume(timerSource); + return attributeWaiter; +} + +- (void)_attributeValue:(MTRDeviceDataValueDictionary)value reportedForPath:(MTRAttributePath *)path +{ + os_unfair_lock_assert_owner(&_lock); + + // Check whether anyone was waiting for this attribute. + NSMutableArray * satisfiedWaiters; + for (MTRAttributeValueWaiter * attributeValueWaiter in self.attributeValueWaiters) { + if ([attributeValueWaiter _attributeValue:value reportedForPath:path byDevice:self] && attributeValueWaiter.allValuesSatisfied) { + if (!satisfiedWaiters) { + satisfiedWaiters = [NSMutableArray array]; + } + [satisfiedWaiters addObject:attributeValueWaiter]; + } + } + + for (MTRAttributeValueWaiter * attributeValueWaiter in satisfiedWaiters) { + [self _notifyAttributeValueWaiter:attributeValueWaiter withError:nil]; + } +} + +- (void)_attributeWaitTimedOut:(MTRAttributeValueWaiter *)attributeValueWaiter +{ + std::lock_guard lock(_lock); + [self _notifyAttributeValueWaiter:attributeValueWaiter withError:[MTRError errorForCHIPErrorCode:CHIP_ERROR_TIMEOUT]]; +} + +- (void)_attributeWaitCanceled:(MTRAttributeValueWaiter *)attributeValueWaiter +{ + std::lock_guard lock(_lock); + [self _doAttributeWaitCanceled:attributeValueWaiter]; +} + +- (void)_doAttributeWaitCanceled:(MTRAttributeValueWaiter *)attributeValueWaiter +{ + os_unfair_lock_assert_owner(&_lock); + + [self _notifyAttributeValueWaiter:attributeValueWaiter withError:[MTRError errorForCHIPErrorCode:CHIP_ERROR_CANCELLED]]; +} + +- (void)_notifyAttributeValueWaiter:(MTRAttributeValueWaiter *)attributeValueWaiter withError:(NSError * _Nullable)error +{ + os_unfair_lock_assert_owner(&_lock); + + [self.attributeValueWaiters removeObject:attributeValueWaiter]; + [attributeValueWaiter _notifyWithError:error]; +} + +- (void)_cancelAllAttributeValueWaiters +{ + os_unfair_lock_assert_owner(&_lock); + + auto * attributeValueWaiters = self.attributeValueWaiters; + self.attributeValueWaiters = nil; + for (MTRAttributeValueWaiter * attributeValueWaiter in attributeValueWaiters) { + [self _doAttributeWaitCanceled:attributeValueWaiter]; + } +} + @end /* BEGIN DRAGONS: Note methods here cannot be renamed, and are used by private callers, do not rename, remove or modify behavior here */ diff --git a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm index 437b1a0676b97b..091d50a5d8fe8c 100644 --- a/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm +++ b/src/darwin/Framework/CHIP/MTRDevice_Concrete.mm @@ -3627,6 +3627,8 @@ - (NSArray *)_getAttributesToReportWithReportedValues:(NSArray delegate) { [delegate device:self receivedAttributeReport:attributeReport]; }]; + + std::lock_guard lock(_lock); + for (NSDictionary * report in attributeReport) { + if (!MTR_SAFE_CAST(report, NSDictionary)) { + MTR_LOG_ERROR("%@ handed a response-value that is not a dictionary: %@", self, report); + continue; + } + + MTRAttributePath * path = MTR_SAFE_CAST(report[MTRAttributePathKey], MTRAttributePath); + if (!path) { + MTR_LOG_ERROR("%@ no valid path for attribute report %@", self, report); + continue; + } + + MTRDeviceDataValueDictionary value = report[MTRDataKey]; + if (!value) { + // This is normal; this could be an error report. + continue; + } + + if (!MTR_SAFE_CAST(value, NSDictionary)) { + MTR_LOG_ERROR("%@ invalid data-value reported: %@", self, report); + continue; + } + + [self _attributeValue:value reportedForPath:path]; + } } - (oneway void)device:(NSNumber *)nodeID receivedEventReport:(NSArray *)eventReport diff --git a/src/darwin/Framework/CHIP/Matter.h b/src/darwin/Framework/CHIP/Matter.h index 9f57e4fb4e4285..85a87c4ba12c0c 100644 --- a/src/darwin/Framework/CHIP/Matter.h +++ b/src/darwin/Framework/CHIP/Matter.h @@ -21,6 +21,7 @@ #import #import +#import #import #import #import diff --git a/src/darwin/Framework/CHIPTests/MTRDeviceTests.m b/src/darwin/Framework/CHIPTests/MTRDeviceTests.m index d5faaec24b63b3..5b6e767fc8e260 100644 --- a/src/darwin/Framework/CHIPTests/MTRDeviceTests.m +++ b/src/darwin/Framework/CHIPTests/MTRDeviceTests.m @@ -1586,6 +1586,37 @@ - (void)test017_TestMTRDeviceBasics XCTAssertEqualObjects([NSSet setWithArray:variousThings], [[NSSet setWithArray:clusterRevisions] setByAddingObjectsFromSet:[NSSet setWithArray:basicInformationAllRootAttributes]]); + // Some quick tests for waitForAttributeValues. First, values that we know + // are already there: + XCTestExpectation * deviceTypesWaitExpectation = [self expectationWithDescription:@"deviceTypes is already the value we expect"]; + __auto_type * deviceTypesToWaitFor = [NSMutableDictionary dictionary]; + for (NSDictionary * deviceTypesValue in deviceTypes) { + deviceTypesToWaitFor[deviceTypesValue[MTRAttributePathKey]] = deviceTypesValue[MTRDataKey]; + } + __auto_type * waiter1 = [device waitForAttributeValues:deviceTypesToWaitFor timeout:200 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNil(error); + [deviceTypesWaitExpectation fulfill]; + }]; + XCTAssertNotNil(waiter1); + [self waitForExpectations:@[ deviceTypesWaitExpectation ] timeout:kTimeoutInSeconds]; + + // Now values that we know will never be there (the type is wrong). + __auto_type * bogusDeviceType = @{ + deviceTypes[0][MTRAttributePathKey] : @ { + MTRTypeKey : MTROctetStringValueType, + MTRValueKey : [@"abc" dataUsingEncoding:NSUTF8StringEncoding], + }, + }; + XCTestExpectation * bogusDeviceTypesWaitExpectation = [self expectationWithDescription:@"bogusDeviceTypes wait should time out"]; + __auto_type * waiter2 = [device waitForAttributeValues:bogusDeviceType timeout:0.5 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNotNil(error); + XCTAssertEqual(error.domain, MTRErrorDomain); + XCTAssertEqual(error.code, MTRErrorCodeTimeout); + [bogusDeviceTypesWaitExpectation fulfill]; + }]; + XCTAssertNotNil(waiter2); + [self waitForExpectations:@[ bogusDeviceTypesWaitExpectation ] timeout:kTimeoutInSeconds]; + // Before resubscribe, first test write failure and expected value effects NSNumber * testEndpointID = @(1); NSNumber * testClusterID = @(8); @@ -1610,6 +1641,23 @@ - (void)test017_TestMTRDeviceBasics NSDictionary * writeValue = [NSDictionary dictionaryWithObjectsAndKeys:@"UnsignedInteger", @"type", [NSNumber numberWithUnsignedInteger:200], @"value", nil]; + + // Also test that waitForAttributeValues does not pick up the transition to + // the expected value. + XCTestExpectation * nonexistentAttributeValueWaitExpectation = [self expectationWithDescription:@"waiting for a value for an attribute that does not exist should time out"]; + __auto_type * waiter3 = [device waitForAttributeValues:@{ + [MTRAttributePath attributePathWithEndpointID:testEndpointID clusterID:testClusterID attributeID:testAttributeID] : writeValue, + } + timeout:0.5 + queue:queue + completion:^(NSError * _Nullable error) { + XCTAssertNotNil(error); + XCTAssertEqual(error.domain, MTRErrorDomain); + XCTAssertEqual(error.code, MTRErrorCodeTimeout); + [nonexistentAttributeValueWaitExpectation fulfill]; + }]; + XCTAssertNotNil(waiter3); + [device writeAttributeWithEndpointID:testEndpointID clusterID:testClusterID attributeID:testAttributeID @@ -1619,10 +1667,20 @@ - (void)test017_TestMTRDeviceBasics // expected value interval is 20s but expect it get reverted immediately as the write fails because it's writing to a // nonexistent attribute - [self waitForExpectations:@[ expectedValueReportedExpectation, expectedValueRemovedExpectation ] timeout:5 enforceOrder:YES]; - - // Test if previous value is reported on a write - uint16_t testOnTimeValue = 10; + [self waitForExpectations:@[ expectedValueReportedExpectation, expectedValueRemovedExpectation, nonexistentAttributeValueWaitExpectation ] timeout:5 enforceOrder:YES]; + + // Get the current OnTime value, to make sure we are writing a different one. + __auto_type * currentOnTimeValueDictionary = [device readAttributeWithEndpointID:@(1) + clusterID:@(MTRClusterIDTypeOnOffID) + attributeID:@(MTRAttributeIDTypeClusterOnOffAttributeOnTimeID) + params:nil]; + XCTAssertNotNil(currentOnTimeValueDictionary); + XCTAssertEqualObjects(currentOnTimeValueDictionary[MTRTypeKey], MTRUnsignedIntegerValueType); + uint16_t currentOnTimeValue = [currentOnTimeValueDictionary[MTRValueKey] unsignedShortValue]; + + // Test if previous value is reported on a write. Make sure to write a + // value different from the current one. + uint16_t testOnTimeValue = currentOnTimeValue > 10 ? currentOnTimeValue - 1 : currentOnTimeValue + 1; XCTestExpectation * onTimeWriteSuccess = [self expectationWithDescription:@"OnTime write success"]; XCTestExpectation * onTimePreviousValue = [self expectationWithDescription:@"OnTime previous value"]; delegate.onAttributeDataReceived = ^(NSArray *> * data) { @@ -1643,7 +1701,63 @@ - (void)test017_TestMTRDeviceBasics } } }; - NSDictionary * writeOnTimeValue = @{ MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(testOnTimeValue) }; + __auto_type * writeOnTimeValue = @{ MTRTypeKey : MTRUnsignedIntegerValueType, MTRValueKey : @(testOnTimeValue) }; + + // Also set up a few attribute value waits to see what happens. + __auto_type * onTimeValueToWaitFor = @{ + [MTRAttributePath attributePathWithEndpointID:@(1) clusterID:@(MTRClusterIDTypeOnOffID) + attributeID:@(MTRAttributeIDTypeClusterOnOffAttributeOnTimeID)] : writeOnTimeValue, + }; + + XCTestExpectation * waitingForOnTimeValue1Expectation = [self expectationWithDescription:@"OnTime value is now the expected value"]; + __auto_type * waiter4 = [device waitForAttributeValues:onTimeValueToWaitFor timeout:200 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNil(error); + [waitingForOnTimeValue1Expectation fulfill]; + }]; + XCTAssertNotNil(waiter4); + + XCTestExpectation * waitingForOnTimeValue2Expectation = [self expectationWithDescription:@"OnTime value is now the expected value and first device type is the expected value"]; + __auto_type * onTimeAndDeviceTypeValuesToWaitFor = [NSMutableDictionary dictionaryWithDictionary:onTimeValueToWaitFor]; + onTimeAndDeviceTypeValuesToWaitFor[deviceTypes[0][MTRAttributePathKey]] = deviceTypes[0][MTRDataKey]; + + __auto_type * waiter5 = [device waitForAttributeValues:onTimeAndDeviceTypeValuesToWaitFor timeout:200 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNil(error); + [waitingForOnTimeValue2Expectation fulfill]; + }]; + XCTAssertNotNil(waiter5); + + XCTestExpectation * waitingForOnTimeValue3Expectation = [self expectationWithDescription:@"OnTime value is now the expected value and first device type is bogus, or we timed out"]; + __auto_type * onTimeAndBogusDeviceTypeValuesToWaitFor = [NSMutableDictionary dictionaryWithDictionary:onTimeValueToWaitFor]; + [onTimeAndBogusDeviceTypeValuesToWaitFor addEntriesFromDictionary:bogusDeviceType]; + __auto_type * waiter6 = [device waitForAttributeValues:onTimeAndBogusDeviceTypeValuesToWaitFor timeout:0.5 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNotNil(error); + XCTAssertEqual(error.domain, MTRErrorDomain); + XCTAssertEqual(error.code, MTRErrorCodeTimeout); + [waitingForOnTimeValue3Expectation fulfill]; + }]; + XCTAssertNotNil(waiter6); + + XCTestExpectation * waitingForOnTimeValue4Expectation = [self expectationWithDescription:@"Waiter should have been canceled"]; + __auto_type * waiter7 = [device waitForAttributeValues:onTimeValueToWaitFor timeout:200 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNotNil(error); + XCTAssertEqual(error.domain, MTRErrorDomain); + XCTAssertEqual(error.code, MTRErrorCodeCancelled); + [waitingForOnTimeValue4Expectation fulfill]; + }]; + XCTAssertNotNil(waiter7); + [waiter7 cancel]; + + XCTestExpectation * waitingForOnTimeValue5Expectation = [self expectationWithDescription:@"Waiter should have been canceled due to being destroyed"]; + @autoreleasepool { + // To force the waiter created here to die quickly. + [device waitForAttributeValues:onTimeValueToWaitFor timeout:200 queue:queue completion:^(NSError * _Nullable error) { + XCTAssertNotNil(error); + XCTAssertEqual(error.domain, MTRErrorDomain); + XCTAssertEqual(error.code, MTRErrorCodeCancelled); + [waitingForOnTimeValue5Expectation fulfill]; + }]; + } + [device writeAttributeWithEndpointID:@(1) clusterID:@(MTRClusterIDTypeOnOffID) attributeID:@(MTRAttributeIDTypeClusterOnOffAttributeOnTimeID) @@ -1651,7 +1765,16 @@ - (void)test017_TestMTRDeviceBasics expectedValueInterval:@(10000) timedWriteTimeout:nil]; - [self waitForExpectations:@[ onTimeWriteSuccess, onTimePreviousValue ] timeout:10]; + [self waitForExpectations:@[ + onTimeWriteSuccess, + onTimePreviousValue, + waitingForOnTimeValue1Expectation, + waitingForOnTimeValue2Expectation, + waitingForOnTimeValue3Expectation, + waitingForOnTimeValue4Expectation, + waitingForOnTimeValue5Expectation, + ] + timeout:10]; __auto_type getOnOffValue = ^{ return [device readAttributeWithEndpointID:@(1) diff --git a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj index 195dd8e2757316..fa1634da4b9267 100644 --- a/src/darwin/Framework/Matter.xcodeproj/project.pbxproj +++ b/src/darwin/Framework/Matter.xcodeproj/project.pbxproj @@ -161,6 +161,9 @@ 5143851E2A65885500EDC8E6 /* MTRSwiftPairingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5143851D2A65885500EDC8E6 /* MTRSwiftPairingTests.swift */; }; 514654492A72F9DF00904E61 /* MTRDemuxingStorage.mm in Sources */ = {isa = PBXBuildFile; fileRef = 514654482A72F9DF00904E61 /* MTRDemuxingStorage.mm */; }; 5146544B2A72F9F500904E61 /* MTRDemuxingStorage.h in Headers */ = {isa = PBXBuildFile; fileRef = 5146544A2A72F9F500904E61 /* MTRDemuxingStorage.h */; }; + 514A98AF2CD98C5E000EF4FD /* MTRAttributeValueWaiter.h in Headers */ = {isa = PBXBuildFile; fileRef = 514A98AC2CD98C5E000EF4FD /* MTRAttributeValueWaiter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 514A98B02CD98C5E000EF4FD /* MTRAttributeValueWaiter_Internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 514A98AE2CD98C5E000EF4FD /* MTRAttributeValueWaiter_Internal.h */; }; + 514A98B12CD98C5E000EF4FD /* MTRAttributeValueWaiter.mm in Sources */ = {isa = PBXBuildFile; fileRef = 514A98AD2CD98C5E000EF4FD /* MTRAttributeValueWaiter.mm */; }; 514C79F02B62ADDA00DD6D7B /* descriptor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 514C79EF2B62ADDA00DD6D7B /* descriptor.cpp */; }; 514C79F12B62ADDA00DD6D7B /* descriptor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 514C79EF2B62ADDA00DD6D7B /* descriptor.cpp */; }; 514C79F32B62ED5500DD6D7B /* attribute-storage.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 514C79F22B62ED5500DD6D7B /* attribute-storage.cpp */; }; @@ -639,6 +642,9 @@ 5143851D2A65885500EDC8E6 /* MTRSwiftPairingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MTRSwiftPairingTests.swift; sourceTree = ""; }; 514654482A72F9DF00904E61 /* MTRDemuxingStorage.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRDemuxingStorage.mm; sourceTree = ""; }; 5146544A2A72F9F500904E61 /* MTRDemuxingStorage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MTRDemuxingStorage.h; sourceTree = ""; }; + 514A98AC2CD98C5E000EF4FD /* MTRAttributeValueWaiter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRAttributeValueWaiter.h; sourceTree = ""; }; + 514A98AD2CD98C5E000EF4FD /* MTRAttributeValueWaiter.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRAttributeValueWaiter.mm; sourceTree = ""; }; + 514A98AE2CD98C5E000EF4FD /* MTRAttributeValueWaiter_Internal.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRAttributeValueWaiter_Internal.h; sourceTree = ""; }; 514C79EF2B62ADDA00DD6D7B /* descriptor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = descriptor.cpp; path = clusters/descriptor/descriptor.cpp; sourceTree = ""; }; 514C79F22B62ED5500DD6D7B /* attribute-storage.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = "attribute-storage.cpp"; path = "util/attribute-storage.cpp"; sourceTree = ""; }; 514C79F52B62F0B900DD6D7B /* util.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = util.cpp; path = util/util.cpp; sourceTree = ""; }; @@ -1389,6 +1395,9 @@ 7596A84728762783004DAE0E /* MTRAsyncCallbackWorkQueue.mm */, 3DA1A3522ABAB3B4004F0BB9 /* MTRAsyncWorkQueue.h */, 3DA1A3532ABAB3B4004F0BB9 /* MTRAsyncWorkQueue.mm */, + 514A98AC2CD98C5E000EF4FD /* MTRAttributeValueWaiter.h */, + 514A98AD2CD98C5E000EF4FD /* MTRAttributeValueWaiter.mm */, + 514A98AE2CD98C5E000EF4FD /* MTRAttributeValueWaiter_Internal.h */, 3CF134AA289D8DF70017A19E /* MTRDeviceAttestationInfo.h */, 3CF134AC289D8E570017A19E /* MTRDeviceAttestationInfo.mm */, 27A53C1527FBC6920053F131 /* MTRAttestationTrustStoreBridge.h */, @@ -1831,6 +1840,8 @@ B2E0D7B1245B0B5C003C5B48 /* Matter.h in Headers */, 7596A84428762729004DAE0E /* MTRDevice.h in Headers */, B2E0D7B8245B0B5C003C5B48 /* MTRSetupPayload.h in Headers */, + 514A98AF2CD98C5E000EF4FD /* MTRAttributeValueWaiter.h in Headers */, + 514A98B02CD98C5E000EF4FD /* MTRAttributeValueWaiter_Internal.h in Headers */, 1E4D654F29C208DD00BC3478 /* MTRCommissionableBrowser.h in Headers */, 3D843756294AD25A0070D20A /* MTRCertificateInfo.h in Headers */, 7596A83E28751220004DAE0E /* MTRBaseClusters_Internal.h in Headers */, @@ -2195,6 +2206,7 @@ 88E6C9482B6334ED001A1FE0 /* MTRMetrics.mm in Sources */, 1ED276E226C5812A00547A89 /* MTRCluster.mm in Sources */, 9BFE5D512C6D3075007D4319 /* MTRDeviceController_XPC.mm in Sources */, + 514A98B12CD98C5E000EF4FD /* MTRAttributeValueWaiter.mm in Sources */, B2E0D7B3245B0B5C003C5B48 /* MTRError.mm in Sources */, 51E51FC1282AD37A00FC978D /* MTRDeviceControllerStartupParams.mm in Sources */, 51565CAE2A79D42100469F18 /* MTRConversion.mm in Sources */, From 9cd0070b21a4e658cd53f34d54fa3310253f6005 Mon Sep 17 00:00:00 2001 From: lpbeliveau-silabs <112982107+lpbeliveau-silabs@users.noreply.github.com> Date: Wed, 6 Nov 2024 20:43:25 -0500 Subject: [PATCH 078/121] Doesn't provide PIN to the unlock after unlatch when the pin length is 0. (#36405) Co-authored-by: Andrei Litvin --- examples/lock-app/silabs/src/LockManager.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/examples/lock-app/silabs/src/LockManager.cpp b/examples/lock-app/silabs/src/LockManager.cpp index 1a4fd934631707..6f5aba9147f6b2 100644 --- a/examples/lock-app/silabs/src/LockManager.cpp +++ b/examples/lock-app/silabs/src/LockManager.cpp @@ -264,9 +264,11 @@ void LockManager::UnlockAfterUnlatch() bool succes = false; if (mUnlatchContext.mEndpointId != kInvalidEndpointId) { - succes = setLockState( - mUnlatchContext.mEndpointId, mUnlatchContext.mFabricIdx, mUnlatchContext.mNodeId, DlLockState::kUnlocked, - MakeOptional(chip::ByteSpan(mUnlatchContext.mPinBuffer, mUnlatchContext.mPinLength)), mUnlatchContext.mErr); + Optional pin = (mUnlatchContext.mPinLength) + ? MakeOptional(chip::ByteSpan(mUnlatchContext.mPinBuffer, mUnlatchContext.mPinLength)) + : Optional::Missing(); + succes = setLockState(mUnlatchContext.mEndpointId, mUnlatchContext.mFabricIdx, mUnlatchContext.mNodeId, + DlLockState::kUnlocked, pin, mUnlatchContext.mErr); } if (!succes) From ed228522d940b3a661b7ff06f21c30886c9c4009 Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Thu, 7 Nov 2024 03:19:35 -0500 Subject: [PATCH 079/121] Clean up and unify XY command handlers of the color control (#36376) * Clean up and unify XY command handlers of the color control * Replace local variable usage by commandData. --- .../color-control-server.cpp | 177 ++++++++---------- .../color-control-server.h | 25 +-- 2 files changed, 93 insertions(+), 109 deletions(-) diff --git a/src/app/clusters/color-control-server/color-control-server.cpp b/src/app/clusters/color-control-server/color-control-server.cpp index d43590da31af93..2b7c7aa12a92d1 100644 --- a/src/app/clusters/color-control-server/color-control-server.cpp +++ b/src/app/clusters/color-control-server/color-control-server.cpp @@ -313,8 +313,8 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl break; case EnhancedColorMode::kCurrentXAndCurrentY: #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY - ColorControlServer::Instance().moveToColor(colorXTransitionState->finalValue, colorYTransitionState->finalValue, - transitionTime10th, endpoint); + ColorControlServer::Instance().moveToColor(endpoint, colorXTransitionState->finalValue, + colorYTransitionState->finalValue, transitionTime10th); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY break; case EnhancedColorMode::kColorTemperatureMireds: @@ -470,11 +470,9 @@ Status ColorControlServer::stopAllColorTransitions(EndpointId endpoint) return Status::Success; } -bool ColorControlServer::stopMoveStepCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - BitMask optionsMask, BitMask optionsOverride) +Status ColorControlServer::stopMoveStepCommand(EndpointId endpoint, const Commands::StopMoveStep::DecodableType & commandData) { - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; + Status status = Status::Success; // StopMoveStep command has no effect on an active color loop. // Fetch if it is supported and active. @@ -488,7 +486,7 @@ bool ColorControlServer::stopMoveStepCommand(app::CommandHandler * commandObj, c } } - if (shouldExecuteIfOff(endpoint, optionsMask, optionsOverride) && !isColorLoopActive) + if (shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride) && !isColorLoopActive) { status = stopAllColorTransitions(endpoint); @@ -507,8 +505,7 @@ bool ColorControlServer::stopMoveStepCommand(app::CommandHandler * commandObj, c #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV } - commandObj->AddStatus(commandPath, status); - return true; + return status; } bool ColorControlServer::shouldExecuteIfOff(EndpointId endpoint, BitMask optionMask, @@ -2251,13 +2248,13 @@ EmberEventControl * ColorControlServer::configureXYEventControl(EndpointId endpo /** * @brief executes move to saturation command * + * @param endpoint target endpoint where to execute move * @param colorX target X * @param colorY target Y * @param transitionTime transition time in 10th of seconds - * @param endpoint target endpoint where to execute move * @return Status::Success if successful,Status::UnsupportedEndpoint XY is not supported on the endpoint */ -Status ColorControlServer::moveToColor(uint16_t colorX, uint16_t colorY, uint16_t transitionTime, EndpointId endpoint) +Status ColorControlServer::moveToColor(EndpointId endpoint, uint16_t colorX, uint16_t colorY, uint16_t transitionTime) { uint16_t epIndex = getEndpointIndex(endpoint); Color16uTransitionState * colorXTransitionState = getXTransitionStateByIndex(epIndex); @@ -2303,45 +2300,42 @@ Status ColorControlServer::moveToColor(uint16_t colorX, uint16_t colorY, uint16_ return Status::Success; } -bool ColorControlServer::moveToColorCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::MoveToColor::DecodableType & commandData) +/** + * @brief executes move to color command + * @param endpoint endpointId of the recipient Color control cluster + * @param commandData Struct containing the parameters of the command + * @return Status::Success when successful, + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a Color XY transition state (verified in + * moveToColor function), + */ +Status ColorControlServer::moveToColorCommand(EndpointId endpoint, const Commands::MoveToColor::DecodableType & commandData) { - if (!shouldExecuteIfOff(commandPath.mEndpointId, commandData.optionsMask, commandData.optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); - Status status = moveToColor(commandData.colorX, commandData.colorY, commandData.transitionTime, commandPath.mEndpointId); + Status status = moveToColor(endpoint, commandData.colorX, commandData.colorY, commandData.transitionTime); #ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT - ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(commandPath.mEndpointId); + ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); #endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT - commandObj->AddStatus(commandPath, status); - return true; + return status; } -bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::MoveColor::DecodableType & commandData) +/** + * @brief executes move color command + * @param endpoint endpointId of the recipient Color control cluster + * @param commandData Struct containing the parameters of the command + * @return Status::Success when successful, + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a Color XY transition state (verified in + * moveToColor). + */ +Status ColorControlServer::moveColorCommand(EndpointId endpoint, const Commands::MoveColor::DecodableType & commandData) { - int16_t rateX = commandData.rateX; - int16_t rateY = commandData.rateY; - BitMask optionsMask = commandData.optionsMask; - BitMask optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint16_t epIndex = getEndpointIndex(endpoint); Color16uTransitionState * colorXTransitionState = getXTransitionStateByIndex(epIndex); Color16uTransitionState * colorYTransitionState = getYTransitionStateByIndex(epIndex); + VerifyOrReturnValue(colorXTransitionState != nullptr, Status::UnsupportedEndpoint); + VerifyOrReturnValue(colorYTransitionState != nullptr, Status::UnsupportedEndpoint); - VerifyOrExit(colorXTransitionState != nullptr, status = Status::UnsupportedEndpoint); - VerifyOrExit(colorYTransitionState != nullptr, status = Status::UnsupportedEndpoint); - - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); uint16_t transitionTimeX, transitionTimeY; uint16_t unsignedRate; @@ -2349,11 +2343,10 @@ bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, cons // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); - if (rateX == 0 && rateY == 0) + if (commandData.rateX == 0 && commandData.rateY == 0) { // any current transition has been stopped. We are done. - commandObj->AddStatus(commandPath, Status::Success); - return true; + return Status::Success; } // Handle color mode transition, if necessary. @@ -2362,15 +2355,15 @@ bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, cons // now, kick off the state machine. Attributes::CurrentX::Get(endpoint, &(colorXTransitionState->initialValue)); colorXTransitionState->currentValue = colorXTransitionState->initialValue; - if (rateX > 0) + if (commandData.rateX > 0) { colorXTransitionState->finalValue = MAX_CIE_XY_VALUE; - unsignedRate = static_cast(rateX); + unsignedRate = static_cast(commandData.rateX); } else { colorXTransitionState->finalValue = MIN_CIE_XY_VALUE; - unsignedRate = static_cast(rateX * -1); + unsignedRate = static_cast(commandData.rateX * -1); } transitionTimeX = computeTransitionTimeFromStateAndRate(colorXTransitionState, unsignedRate); colorXTransitionState->stepsRemaining = transitionTimeX; @@ -2383,15 +2376,15 @@ bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, cons Attributes::CurrentY::Get(endpoint, &(colorYTransitionState->initialValue)); colorYTransitionState->currentValue = colorYTransitionState->initialValue; - if (rateY > 0) + if (commandData.rateY > 0) { colorYTransitionState->finalValue = MAX_CIE_XY_VALUE; - unsignedRate = static_cast(rateY); + unsignedRate = static_cast(commandData.rateY); } else { colorYTransitionState->finalValue = MIN_CIE_XY_VALUE; - unsignedRate = static_cast(rateY * -1); + unsignedRate = static_cast(commandData.rateY * -1); } transitionTimeY = computeTransitionTimeFromStateAndRate(colorYTransitionState, unsignedRate); colorYTransitionState->stepsRemaining = transitionTimeY; @@ -2406,52 +2399,36 @@ bool ColorControlServer::moveColorCommand(app::CommandHandler * commandObj, cons // kick off the state machine: scheduleTimerCallbackMs(configureXYEventControl(endpoint), TRANSITION_UPDATE_TIME_MS.count()); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } -bool ColorControlServer::stepColorCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::StepColor::DecodableType & commandData) +/** + * @brief executes step color command + * @param endpoint endpointId of the recipient Color control cluster + * @param commandData Struct containing the parameters of the command + * @return Status::Success when successful, + * Status::InvalidCommand when a step X and Y of 0 is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a Color XY transition state. + */ +Status ColorControlServer::stepColorCommand(EndpointId endpoint, const Commands::StepColor::DecodableType & commandData) { - int16_t stepX = commandData.stepX; - int16_t stepY = commandData.stepY; - uint16_t transitionTime = commandData.transitionTime; - BitMask optionsMask = commandData.optionsMask; - BitMask optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - uint16_t currentColorX = 0; - uint16_t currentColorY = 0; - uint16_t colorX = 0; - uint16_t colorY = 0; - - Status status = Status::Success; + VerifyOrReturnValue(commandData.stepX != 0 || commandData.stepY != 0, Status::InvalidCommand); uint16_t epIndex = getEndpointIndex(endpoint); Color16uTransitionState * colorXTransitionState = getXTransitionStateByIndex(epIndex); Color16uTransitionState * colorYTransitionState = getYTransitionStateByIndex(epIndex); - VerifyOrExit(colorXTransitionState != nullptr, status = Status::UnsupportedEndpoint); - VerifyOrExit(colorYTransitionState != nullptr, status = Status::UnsupportedEndpoint); - - if (stepX == 0 && stepY == 0) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } - - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(colorXTransitionState != nullptr, Status::UnsupportedEndpoint); + VerifyOrReturnValue(colorYTransitionState != nullptr, Status::UnsupportedEndpoint); + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); + uint16_t currentColorX = 0; + uint16_t currentColorY = 0; Attributes::CurrentX::Get(endpoint, ¤tColorX); Attributes::CurrentY::Get(endpoint, ¤tColorY); - colorX = findNewColorValueFromStep(currentColorX, stepX); - colorY = findNewColorValueFromStep(currentColorY, stepY); + uint16_t colorX = findNewColorValueFromStep(currentColorX, commandData.stepX); + uint16_t colorY = findNewColorValueFromStep(currentColorY, commandData.stepY); // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); @@ -2463,10 +2440,10 @@ bool ColorControlServer::stepColorCommand(app::CommandHandler * commandObj, cons colorXTransitionState->initialValue = currentColorX; colorXTransitionState->currentValue = currentColorX; colorXTransitionState->finalValue = colorX; - colorXTransitionState->stepsRemaining = std::max(transitionTime, 1); + colorXTransitionState->stepsRemaining = std::max(commandData.transitionTime, 1); colorXTransitionState->stepsTotal = colorXTransitionState->stepsRemaining; - colorXTransitionState->timeRemaining = transitionTime; - colorXTransitionState->transitionTime = transitionTime; + colorXTransitionState->timeRemaining = commandData.transitionTime; + colorXTransitionState->transitionTime = commandData.transitionTime; colorXTransitionState->endpoint = endpoint; colorXTransitionState->lowLimit = MIN_CIE_XY_VALUE; colorXTransitionState->highLimit = MAX_CIE_XY_VALUE; @@ -2476,20 +2453,17 @@ bool ColorControlServer::stepColorCommand(app::CommandHandler * commandObj, cons colorYTransitionState->finalValue = colorY; colorYTransitionState->stepsRemaining = colorXTransitionState->stepsRemaining; colorYTransitionState->stepsTotal = colorXTransitionState->stepsRemaining; - colorYTransitionState->timeRemaining = transitionTime; - colorYTransitionState->transitionTime = transitionTime; + colorYTransitionState->timeRemaining = commandData.transitionTime; + colorYTransitionState->transitionTime = commandData.transitionTime; colorYTransitionState->endpoint = endpoint; colorYTransitionState->lowLimit = MIN_CIE_XY_VALUE; colorYTransitionState->highLimit = MAX_CIE_XY_VALUE; - SetQuietReportRemainingTime(endpoint, transitionTime, true /* isNewTransition */); + SetQuietReportRemainingTime(endpoint, commandData.transitionTime, true /* isNewTransition */); // kick off the state machine: - scheduleTimerCallbackMs(configureXYEventControl(endpoint), transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + scheduleTimerCallbackMs(configureXYEventControl(endpoint), commandData.transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); + return Status::Success; } /** @@ -3300,19 +3274,25 @@ bool emberAfColorControlClusterColorLoopSetCallback(app::CommandHandler * comman bool emberAfColorControlClusterMoveToColorCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveToColor::DecodableType & commandData) { - return ColorControlServer::Instance().moveToColorCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().moveToColorCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterMoveColorCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveColor::DecodableType & commandData) { - return ColorControlServer::Instance().moveColorCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().moveColorCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterStepColorCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::StepColor::DecodableType & commandData) { - return ColorControlServer::Instance().stepColorCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().stepColorCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY @@ -3350,8 +3330,9 @@ void emberAfPluginLevelControlCoupledColorTempChangeCallback(EndpointId endpoint bool emberAfColorControlClusterStopMoveStepCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::StopMoveStep::DecodableType & commandData) { - return ColorControlServer::Instance().stopMoveStepCommand(commandObj, commandPath, commandData.optionsMask, - commandData.optionsOverride); + Status status = ColorControlServer::Instance().stopMoveStepCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } void emberAfColorControlClusterServerInitCallback(EndpointId endpoint) diff --git a/src/app/clusters/color-control-server/color-control-server.h b/src/app/clusters/color-control-server/color-control-server.h index 422c7f592f8b33..aab7c270d14858 100644 --- a/src/app/clusters/color-control-server/color-control-server.h +++ b/src/app/clusters/color-control-server/color-control-server.h @@ -143,9 +143,9 @@ class ColorControlServer bool HasFeature(chip::EndpointId endpoint, Feature feature); chip::Protocols::InteractionModel::Status stopAllColorTransitions(chip::EndpointId endpoint); - bool stopMoveStepCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - chip::BitMask optionsMask, - chip::BitMask optionsOverride); + chip::Protocols::InteractionModel::Status + stopMoveStepCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::StopMoveStep::DecodableType & commandData); #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV bool moveHueCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, @@ -177,12 +177,15 @@ class ColorControlServer #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY - bool moveToColorCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::MoveToColor::DecodableType & commandData); - bool moveColorCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::MoveColor::DecodableType & commandData); - bool stepColorCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::StepColor::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + moveToColorCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::MoveToColor::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + moveColorCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::MoveColor::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + stepColorCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::StepColor::DecodableType & commandData); void updateXYCommand(chip::EndpointId endpoint); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY @@ -255,8 +258,8 @@ class ColorControlServer #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY - chip::Protocols::InteractionModel::Status moveToColor(uint16_t colorX, uint16_t colorY, uint16_t transitionTime, - chip::EndpointId endpoint); + chip::Protocols::InteractionModel::Status moveToColor(chip::EndpointId endpoint, uint16_t colorX, uint16_t colorY, + uint16_t transitionTime); Color16uTransitionState * getXTransitionState(chip::EndpointId endpoint); Color16uTransitionState * getYTransitionState(chip::EndpointId endpoint); Color16uTransitionState * getXTransitionStateByIndex(uint16_t index); From 4edae2032dbcc118e316dcfd34fd5bd2f988d411 Mon Sep 17 00:00:00 2001 From: andrei-menzopol <96489227+andrei-menzopol@users.noreply.github.com> Date: Thu, 7 Nov 2024 10:58:38 +0200 Subject: [PATCH 080/121] [NXP][platform][examples] Low power changes (#36389) * [nxp][examples][common] Add low-power app callbacks default implementation * Add AppMatter_(Allow/Disallow)DeviceToSleep default implementation in AppTaskBase. Signed-off-by: Andrei Menzopol * [nxp][examples][common][contact-sensor-app] Remove low-power app callbacks Signed-off-by: Andrei Menzopol * [nxp][platform][common][ble] Change CHIP_DEVICE_K32W1 define to NXP_DEVICE_K32W1_MCXW7X Signed-off-by: Andrei Menzopol * Restyled by clang-format --------- Signed-off-by: Andrei Menzopol Co-authored-by: Restyled.io --- .../contact-sensor-app/nxp/common/AppTask.cpp | 16 ---------------- .../nxp/common/include/AppTask.h | 4 ---- .../nxp/common/app_task/include/AppTaskBase.h | 4 ++-- .../nxp/common/app_task/source/AppTaskBase.cpp | 15 +++++++++++++++ src/platform/nxp/common/ble/BLEManagerCommon.cpp | 2 +- 5 files changed, 18 insertions(+), 23 deletions(-) diff --git a/examples/contact-sensor-app/nxp/common/AppTask.cpp b/examples/contact-sensor-app/nxp/common/AppTask.cpp index 7539bc61e09a1f..2b102adc1b4924 100644 --- a/examples/contact-sensor-app/nxp/common/AppTask.cpp +++ b/examples/contact-sensor-app/nxp/common/AppTask.cpp @@ -18,10 +18,6 @@ #include "AppTask.h" -#if CONFIG_LOW_POWER -#include "PWR_Interface.h" -#endif - #include #include @@ -36,18 +32,6 @@ void ContactSensorApp::AppTask::PreInitMatterStack() ChipLogProgress(DeviceLayer, "Welcome to NXP Contact Sensor Demo App"); } -#if CONFIG_LOW_POWER -void ContactSensorApp::AppTask::AppMatter_DisallowDeviceToSleep() -{ - PWR_DisallowDeviceToSleep(); -} - -void ContactSensorApp::AppTask::AppMatter_AllowDeviceToSleep() -{ - PWR_AllowDeviceToSleep(); -} -#endif - ContactSensorApp::AppTask & ContactSensorApp::AppTask::GetDefaultInstance() { static ContactSensorApp::AppTask sAppTask; diff --git a/examples/contact-sensor-app/nxp/common/include/AppTask.h b/examples/contact-sensor-app/nxp/common/include/AppTask.h index 407572aad254e6..7a4a9a61617970 100644 --- a/examples/contact-sensor-app/nxp/common/include/AppTask.h +++ b/examples/contact-sensor-app/nxp/common/include/AppTask.h @@ -34,10 +34,6 @@ class AppTask : public chip::NXP::App::AppTaskFreeRTOS // AppTaskFreeRTOS virtual methods void PreInitMatterStack() override; -#if CONFIG_LOW_POWER - void AppMatter_DisallowDeviceToSleep() override; - void AppMatter_AllowDeviceToSleep() override; -#endif // This returns an instance of this class. static AppTask & GetDefaultInstance(); diff --git a/examples/platform/nxp/common/app_task/include/AppTaskBase.h b/examples/platform/nxp/common/app_task/include/AppTaskBase.h index ab29af27c29561..2debabf28d305b 100644 --- a/examples/platform/nxp/common/app_task/include/AppTaskBase.h +++ b/examples/platform/nxp/common/app_task/include/AppTaskBase.h @@ -102,7 +102,7 @@ class AppTaskBase * This function can be overridden in order to implement a specific disallow mechanism. * */ - virtual void AppMatter_DisallowDeviceToSleep(void) {} + virtual void AppMatter_DisallowDeviceToSleep(void); /** * \brief Allow entering low power mode. @@ -110,7 +110,7 @@ class AppTaskBase * This function can be overridden in order to implement a specific allow mechanism. * */ - virtual void AppMatter_AllowDeviceToSleep(void) {} + virtual void AppMatter_AllowDeviceToSleep(void); /** * \brief Print onboarding information. diff --git a/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp b/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp index 2646ffca4ef26d..81907d21634318 100644 --- a/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp +++ b/examples/platform/nxp/common/app_task/source/AppTaskBase.cpp @@ -75,6 +75,7 @@ #if CONFIG_LOW_POWER #include "LowPower.h" +#include "PWR_Interface.h" #endif #if CHIP_DEVICE_CONFIG_ENABLE_OTA_REQUESTOR @@ -431,6 +432,20 @@ void chip::NXP::App::AppTaskBase::FactoryResetHandler(void) chip::Server::GetInstance().ScheduleFactoryReset(); } +void chip::NXP::App::AppTaskBase::AppMatter_DisallowDeviceToSleep(void) +{ +#if CONFIG_LOW_POWER + PWR_DisallowDeviceToSleep(); +#endif +} + +void chip::NXP::App::AppTaskBase::AppMatter_AllowDeviceToSleep(void) +{ +#if CONFIG_LOW_POWER + PWR_AllowDeviceToSleep(); +#endif +} + void chip::NXP::App::AppTaskBase::PrintOnboardingInfo() { #if CONFIG_NETWORK_LAYER_BLE diff --git a/src/platform/nxp/common/ble/BLEManagerCommon.cpp b/src/platform/nxp/common/ble/BLEManagerCommon.cpp index e970dab55cc232..baba33ecdab48c 100644 --- a/src/platform/nxp/common/ble/BLEManagerCommon.cpp +++ b/src/platform/nxp/common/ble/BLEManagerCommon.cpp @@ -1190,7 +1190,7 @@ void BLEManagerCommon::blekw_gap_connection_cb(deviceId_t deviceId, gapConnectio if (pConnectionEvent->eventType == gConnEvtConnected_c) { -#if CHIP_DEVICE_K32W1 +#if NXP_DEVICE_K32W1_MCXW7X #if defined(nxp_use_low_power) && (nxp_use_low_power == 1) /* Disallow must be called here for K32W1, otherwise an assert will be reached. * Disclaimer: this is a workaround until a better cross platform solution is found. */ From 1e1c248f98ac753c0cb77dfd5041166bc134601c Mon Sep 17 00:00:00 2001 From: Mathieu Kardous <84793247+mkardous-silabs@users.noreply.github.com> Date: Thu, 7 Nov 2024 14:29:49 +0100 Subject: [PATCH 081/121] [Silabs] Refactor Wifi eventing structure to be align with C++ standards (#36366) * Move defines to files where they are used * Refactor enums and use BitFlag wrapper instead of bit operations * Refactor wifi eventing to use the Bitflag datatype * Apply suggestions from code review Co-authored-by: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> * Remove unnecassry includes * Restyled by clang-format --------- Co-authored-by: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Co-authored-by: Restyled.io --- .../silabs/SiWx917/SiWxWifiInterface.cpp | 134 +++++++++--------- .../efr32/rs911x/Rsi91xWifiInterface.cpp | 100 ++++++------- .../silabs/efr32/rs911x/hal/efx_spi.c | 1 - .../efr32/rs911x/hal/rsi_hal_mcu_interrupt.c | 1 - .../efr32/rs911x/hal/rsi_hal_mcu_ioports.c | 1 - .../efr32/rs911x/hal/rsi_hal_mcu_timer.c | 3 +- .../efr32/rs911x/hal/sl_si91x_ncp_utility.c | 1 - .../silabs/wifi/WifiInterfaceAbstraction.cpp | 54 ++++--- .../silabs/wifi/WifiInterfaceAbstraction.h | 66 ++++----- 9 files changed, 171 insertions(+), 190 deletions(-) diff --git a/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp b/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp index 2390365384481d..8696d083706638 100644 --- a/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp +++ b/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp @@ -204,8 +204,8 @@ constexpr uint16_t kWifiScanTimeoutTicks = 10000; void DHCPTimerEventHandler(void * arg) { - WfxEvent_t event = { .eventType = WFX_EVT_DHCP_POLL }; - sl_matter_wifi_post_event(&event); + WifiEvent event = WifiEvent::kStationDhcpPoll; + sl_matter_wifi_post_event(event); } void CancelDHCPTimer(void) @@ -283,7 +283,7 @@ sl_status_t sl_wifi_siwx917_init(void) ChipLogError(DeviceLayer, "sl_si91x_trng_program_key failed: 0x%lx", static_cast(status))); #endif // SL_MBEDTLS_USE_TINYCRYPT - wfx_rsi.dev_state |= WFX_RSI_ST_DEV_READY; + wfx_rsi.dev_state.Set(WifiState::kStationInit); osSemaphoreRelease(sl_rs_ble_init_sem); return status; } @@ -404,11 +404,12 @@ sl_status_t SetWifiConfigurations() sl_status_t JoinWifiNetwork(void) { - VerifyOrReturnError(!(wfx_rsi.dev_state & (WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED)), SL_STATUS_IN_PROGRESS); + VerifyOrReturnError(!wfx_rsi.dev_state.HasAny(WifiState::kStationConnecting, WifiState::kStationConnected), + SL_STATUS_IN_PROGRESS); sl_status_t status = SL_STATUS_OK; // Start Join Network - wfx_rsi.dev_state |= WFX_RSI_ST_STA_CONNECTING; + wfx_rsi.dev_state.Set(WifiState::kStationConnecting); status = SetWifiConfigurations(); VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogError(DeviceLayer, "Failure to set the Wifi Configurations!")); @@ -417,9 +418,8 @@ sl_status_t JoinWifiNetwork(void) if (status == SL_STATUS_OK || status == SL_STATUS_IN_PROGRESS) { - WfxEvent_t event; - event.eventType = WFX_EVT_STA_CONN; - sl_matter_wifi_post_event(&event); + WifiEvent event = WifiEvent::kStationConnect; + sl_matter_wifi_post_event(event); return status; } @@ -427,13 +427,13 @@ sl_status_t JoinWifiNetwork(void) ChipLogError(DeviceLayer, "sl_wifi_connect failed: 0x%lx", static_cast(status)); VerifyOrReturnError((wfx_rsi.join_retries <= MAX_JOIN_RETRIES_COUNT), status); - wfx_rsi.dev_state &= ~(WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED); + wfx_rsi.dev_state.Clear(WifiState::kStationConnecting).Clear(WifiState::kStationConnected); + ChipLogProgress(DeviceLayer, "Connection retry attempt %d", wfx_rsi.join_retries); wfx_retry_connection(++wfx_rsi.join_retries); - WfxEvent_t event; - event.eventType = WFX_EVT_STA_START_JOIN; - sl_matter_wifi_post_event(&event); + WifiEvent event = WifiEvent::kStationStartJoin; + sl_matter_wifi_post_event(event); return status; } @@ -632,7 +632,7 @@ sl_status_t show_scan_results(sl_wifi_scan_result_t * scan_result) } // cleanup and return - wfx_rsi.dev_state &= ~WFX_RSI_ST_SCANSTARTED; + wfx_rsi.dev_state.Clear(WifiState::kScanStarted); wfx_rsi.scan_cb((wfx_wifi_scan_result_t *) 0); wfx_rsi.scan_cb = nullptr; if (wfx_rsi.scan_ssid) @@ -662,7 +662,7 @@ void NotifyConnectivity(void) void HandleDHCPPolling(void) { - WfxEvent_t event; + WifiEvent event; // TODO: Notify the application that the interface is not set up or Chipdie here because we are in an unkonwn state struct netif * sta_netif = &wifi_client_context.netif; @@ -674,8 +674,8 @@ void HandleDHCPPolling(void) { wfx_dhcp_got_ipv4((uint32_t) sta_netif->ip_addr.u_addr.ip4.addr); hasNotifiedIPV4 = true; - event.eventType = WFX_EVT_STA_DHCP_DONE; - sl_matter_wifi_post_event(&event); + event = WifiEvent::kStationDhcpDone; + sl_matter_wifi_post_event(event); NotifyConnectivity(); } else if (dhcp_state == DHCP_OFF) @@ -694,27 +694,27 @@ void HandleDHCPPolling(void) ChipLogProgress(DeviceLayer, "SLAAC OK: linklocal addr: %s", addrStr); wfx_ipv6_notify(GET_IPV6_SUCCESS); hasNotifiedIPV6 = true; - event.eventType = WFX_EVT_STA_DHCP_DONE; - sl_matter_wifi_post_event(&event); + event = WifiEvent::kStationDhcpDone; + sl_matter_wifi_post_event(event); NotifyConnectivity(); } } - -void sl_matter_wifi_post_event(WfxEvent_t * event) +void sl_matter_wifi_post_event(WifiEvent event) { - if (osMessageQueuePut(sWifiEventQueue, event, 0, 0) != osOK) + sl_status_t status = osMessageQueuePut(sWifiEventQueue, &event, 0, 0); + + if (status != osOK) { - ChipLogError(DeviceLayer, "sl_matter_wifi_post_event: failed to post event.") - // TODO: Handle error, requeue event depending on queue size or notify relevant task, Chipdie, etc. + ChipLogError(DeviceLayer, "sl_matter_wifi_post_event: failed to post event with status: %ld", status); + // TODO: Handle error, requeue event depending on queue size or notify relevant task, + // Chipdie, etc. } } - /// ResetDHCPNotificationFlags /// @brief Reset the flags that are used to notify the application about DHCP connectivity -/// and emits a WFX_EVT_STA_DO_DHCP event to trigger DHCP polling checks. Helper function for ProcessEvent. +/// and emits a WifiEvent::kStationDoDhcp event to trigger DHCP polling checks. Helper function for ProcessEvent. void ResetDHCPNotificationFlags(void) { - WfxEvent_t outEvent; #if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) hasNotifiedIPV4 = false; @@ -722,27 +722,30 @@ void ResetDHCPNotificationFlags(void) hasNotifiedIPV6 = false; hasNotifiedWifiConnectivity = false; - outEvent.eventType = WFX_EVT_STA_DO_DHCP; - sl_matter_wifi_post_event(&outEvent); + WifiEvent event = WifiEvent::kStationDoDhcp; + sl_matter_wifi_post_event(event); } -void ProcessEvent(WfxEvent_t inEvent) +void ProcessEvent(WifiEvent event) { // Process event - switch (inEvent.eventType) + switch (event) { - case WFX_EVT_STA_CONN: - ChipLogDetail(DeviceLayer, "WFX_EVT_STA_CONN"); - wfx_rsi.dev_state |= WFX_RSI_ST_STA_CONNECTED; + case WifiEvent::kStationConnect: + ChipLogDetail(DeviceLayer, "WifiEvent::kStationConnect"); + wfx_rsi.dev_state.Set(WifiState::kStationConnected); ResetDHCPNotificationFlags(); - break; - case WFX_EVT_STA_DISCONN: - ChipLogDetail(DeviceLayer, "WFX_EVT_STA_DISCONN"); + case WifiEvent::kStationDisconnect: { + ChipLogDetail(DeviceLayer, "WifiEvent::kStationDisconnect"); // TODO: This event is not being posted anywhere, seems to be a dead code or we are missing something - wfx_rsi.dev_state &= - ~(WFX_RSI_ST_STA_READY | WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED | WFX_RSI_ST_STA_DHCP_DONE); + + wfx_rsi.dev_state.Clear(WifiState::kStationReady) + .Clear(WifiState::kStationConnecting) + .Clear(WifiState::kStationConnected) + .Clear(WifiState::kStationDhcpDone); + /* TODO: Implement disconnect notify */ ResetDHCPNotificationFlags(); #if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) @@ -750,22 +753,20 @@ void ProcessEvent(WfxEvent_t inEvent) wfx_ip_changed_notify(IP_STATUS_FAIL); #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ wfx_ipv6_notify(GET_IPV6_FAIL); - break; + } + break; - case WFX_EVT_AP_START: - // TODO: Currently unimplemented - break; - case WFX_EVT_AP_STOP: + case WifiEvent::kAPStart: // TODO: Currently unimplemented break; - case WFX_EVT_SCAN: - ChipLogDetail(DeviceLayer, "WFX_EVT_SCAN"); + case WifiEvent::kScan: + ChipLogDetail(DeviceLayer, "WifiEvent::kScan"); #ifdef SL_WFX_CONFIG_SCAN - if (!(wfx_rsi.dev_state & WFX_RSI_ST_SCANSTARTED)) + if (!(wfx_rsi.dev_state.Has(WifiState::kScanStarted))) { - ChipLogDetail(DeviceLayer, "WFX_EVT_SCAN"); + ChipLogDetail(DeviceLayer, "WifiEvent::kScan"); sl_wifi_scan_configuration_t wifi_scan_configuration; memset(&wifi_scan_configuration, 0, sizeof(wifi_scan_configuration)); @@ -785,7 +786,7 @@ void ProcessEvent(WfxEvent_t inEvent) return; } - if (wfx_rsi.dev_state & WFX_RSI_ST_STA_CONNECTED) + if (wfx_rsi.dev_state.Has(WifiState::kStationConnected)) { /* Terminate with end of scan which is no ap sent back */ wifi_scan_configuration.type = SL_WIFI_SCAN_TYPE_ADV_SCAN; @@ -796,7 +797,7 @@ void ProcessEvent(WfxEvent_t inEvent) wifi_scan_configuration = default_wifi_scan_configuration; } sl_wifi_set_scan_callback(bg_scan_callback_handler, nullptr); - wfx_rsi.dev_state |= WFX_RSI_ST_SCANSTARTED; + wfx_rsi.dev_state.Set(WifiState::kScanStarted); osSemaphoreAcquire(sScanInProgressSemaphore, osWaitForever); status = sl_wifi_start_scan(SL_WIFI_CLIENT_2_4GHZ_INTERFACE, nullptr, &wifi_scan_configuration); @@ -809,27 +810,29 @@ void ProcessEvent(WfxEvent_t inEvent) } #endif /* SL_WFX_CONFIG_SCAN */ break; - case WFX_EVT_STA_START_JOIN: - ChipLogDetail(DeviceLayer, "WFX_EVT_STA_START_JOIN"); - // Trigger Netwrok scan - InitiateScan(); + case WifiEvent::kStationStartJoin: + ChipLogDetail(DeviceLayer, "WifiEvent::kStationStartJoin"); - // Joining to the network + InitiateScan(); JoinWifiNetwork(); break; - case WFX_EVT_STA_DO_DHCP: - ChipLogDetail(DeviceLayer, "WFX_EVT_STA_DO_DHCP"); + case WifiEvent::kStationDoDhcp: + ChipLogDetail(DeviceLayer, "WifiEvent::kStationDoDhcp"); StartDHCPTimer(WFX_RSI_DHCP_POLL_INTERVAL); break; - case WFX_EVT_STA_DHCP_DONE: - ChipLogDetail(DeviceLayer, "WFX_EVT_STA_DHCP_DONE"); + + case WifiEvent::kStationDhcpDone: + ChipLogDetail(DeviceLayer, "WifiEvent::kStationDhcpDone"); CancelDHCPTimer(); break; - case WFX_EVT_DHCP_POLL: - ChipLogDetail(DeviceLayer, "WFX_EVT_DHCP_POLL"); + + case WifiEvent::kStationDhcpPoll: + ChipLogDetail(DeviceLayer, "WifiEvent::kStationDhcpPoll"); HandleDHCPPolling(); + break; + default: break; } @@ -856,7 +859,7 @@ sl_status_t sl_matter_wifi_platform_init(void) VerifyOrReturnError(sScanCompleteSemaphore != nullptr, SL_STATUS_ALLOCATION_FAILED); // Create the message queue - sWifiEventQueue = osMessageQueueNew(kWfxQueueSize, sizeof(WfxEvent_t), nullptr); + sWifiEventQueue = osMessageQueueNew(kWfxQueueSize, sizeof(WifiEvent), nullptr); VerifyOrReturnError(sWifiEventQueue != nullptr, SL_STATUS_ALLOCATION_FAILED); // Create timer for DHCP polling @@ -881,7 +884,7 @@ sl_status_t sl_matter_wifi_platform_init(void) void sl_matter_wifi_task(void * arg) { (void) arg; - WfxEvent_t wfxEvent; + WifiEvent event; sl_status_t status = SL_STATUS_OK; status = sl_wifi_siwx917_init(); @@ -894,9 +897,9 @@ void sl_matter_wifi_task(void * arg) ChipLogDetail(DeviceLayer, "sl_matter_wifi_task: starting event loop"); for (;;) { - if (osMessageQueueGet(sWifiEventQueue, &wfxEvent, nullptr, osWaitForever) == osOK) + if (osMessageQueueGet(sWifiEventQueue, &event, nullptr, osWaitForever) == osOK) { - ProcessEvent(wfxEvent); + ProcessEvent(event); } else { @@ -926,8 +929,7 @@ void wfx_dhcp_got_ipv4(uint32_t ip) ChipLogDetail(DeviceLayer, "DHCP OK: IP=%d.%d.%d.%d", wfx_rsi.ip4_addr[0], wfx_rsi.ip4_addr[1], wfx_rsi.ip4_addr[2], wfx_rsi.ip4_addr[3]); /* Notify the Connectivity Manager - via the app */ - wfx_rsi.dev_state |= WFX_RSI_ST_STA_DHCP_DONE; + wfx_rsi.dev_state.Set(WifiState::kStationDhcpDone).Set(WifiState::kStationReady); wfx_ip_changed_notify(IP_STATUS_SUCCESS); - wfx_rsi.dev_state |= WFX_RSI_ST_STA_READY; } #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ diff --git a/examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp b/examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp index 233230b3698265..5c3a7f7240b21d 100644 --- a/examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp +++ b/examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp @@ -61,6 +61,7 @@ extern "C" { #include #define WFX_QUEUE_SIZE 10 +#define WFX_RSI_BUF_SZ (1024 * 10) static osThreadId_t sDrvThread; constexpr uint32_t kDrvTaskSize = 1792; @@ -108,9 +109,8 @@ static void rsi_wireless_driver_task_wrapper(void * argument) static void DHCPTimerEventHandler(void * arg) { - WfxEvent_t event; - event.eventType = WFX_EVT_DHCP_POLL; - sl_matter_wifi_post_event(&event); + WifiEvent event = WifiEvent::kStationDhcpPoll; + sl_matter_wifi_post_event(event); } static void CancelDHCPTimer(void) @@ -284,8 +284,7 @@ int32_t wfx_rsi_power_save(void) *********************************************************************/ static void wfx_rsi_join_cb(uint16_t status, const uint8_t * buf, const uint16_t len) { - WfxEvent_t WfxEvent; - wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_CONNECTING; + wfx_rsi.dev_state.Clear(WifiState::kStationConnecting); if (status != RSI_SUCCESS) { /* @@ -301,8 +300,8 @@ static void wfx_rsi_join_cb(uint16_t status, const uint8_t * buf, const uint16_t */ ChipLogProgress(DeviceLayer, "wfx_rsi_join_cb: success"); memset(&temp_reset, 0, sizeof(wfx_wifi_scan_ext_t)); - WfxEvent.eventType = WFX_EVT_STA_CONN; - sl_matter_wifi_post_event(&WfxEvent); + WifiEvent event = WifiEvent::kStationConnect; + sl_matter_wifi_post_event(event); wfx_rsi.join_retries = 0; } @@ -319,11 +318,12 @@ static void wfx_rsi_join_cb(uint16_t status, const uint8_t * buf, const uint16_t static void wfx_rsi_join_fail_cb(uint16_t status, uint8_t * buf, uint32_t len) { ChipLogError(DeviceLayer, "wfx_rsi_join_fail_cb: status: %d", status); - WfxEvent_t WfxEvent; wfx_rsi.join_retries += 1; - wfx_rsi.dev_state &= ~(WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED); - WfxEvent.eventType = WFX_EVT_STA_START_JOIN; - sl_matter_wifi_post_event(&WfxEvent); + + wfx_rsi.dev_state.Clear(WifiState::kStationConnecting).Clear(WifiState::kStationConnected); + + WifiEvent event = WifiEvent::kStationStartJoin; + sl_matter_wifi_post_event(event); } /************************************************************************************* * @fn wfx_rsi_wlan_pkt_cb(uint16_t status, uint8_t *buf, uint32_t len) @@ -423,7 +423,7 @@ static int32_t sl_matter_wifi_init(void) wfx_rsi.sta_mac.octet[2], wfx_rsi.sta_mac.octet[3], wfx_rsi.sta_mac.octet[4], wfx_rsi.sta_mac.octet[5]); // Create the message queue - sWifiEventQueue = osMessageQueueNew(WFX_QUEUE_SIZE, sizeof(WfxEvent_t), NULL); + sWifiEventQueue = osMessageQueueNew(WFX_QUEUE_SIZE, sizeof(WifiEvent), NULL); if (sWifiEventQueue == NULL) { return SL_STATUS_ALLOCATION_FAILED; @@ -455,7 +455,7 @@ static int32_t sl_matter_wifi_init(void) rsi_semaphore_post(&sl_rs_ble_init_sem); #endif - wfx_rsi.dev_state |= WFX_RSI_ST_DEV_READY; + wfx_rsi.dev_state.Set(WifiState::kStationInit); return RSI_SUCCESS; } @@ -536,14 +536,10 @@ static void wfx_rsi_save_ap_info(void) // translation **********************************************************************************************/ static void sl_wifi_platform_join_network(void) { - int32_t status = SL_STATUS_OK; + sl_status_t status = SL_STATUS_OK; rsi_security_mode_t connect_security_mode; - if (wfx_rsi.dev_state & (WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED)) - { - ChipLogProgress(DeviceLayer, "sl_wifi_platform_join_network: already in progress"); - return; - } + VerifyOrReturn(!wfx_rsi.dev_state.HasAny(WifiState::kStationConnecting, WifiState::kStationConnected)); switch (wfx_rsi.sec.security) { @@ -577,7 +573,7 @@ static void sl_wifi_platform_join_network(void) /* TODO - make the WFX_SECURITY_xxx - same as RSI_xxx * Right now it's done by hand - we need something better */ - wfx_rsi.dev_state |= WFX_RSI_ST_STA_CONNECTING; + wfx_rsi.dev_state.Set(WifiState::kStationConnecting); if ((status = rsi_wlan_register_callbacks(RSI_JOIN_FAIL_CB, wfx_rsi_join_fail_cb)) != RSI_SUCCESS) { @@ -590,7 +586,7 @@ static void sl_wifi_platform_join_network(void) if ((status = rsi_wlan_connect_async((int8_t *) &wfx_rsi.sec.ssid[0], connect_security_mode, &wfx_rsi.sec.passkey[0], wfx_rsi_join_cb)) != RSI_SUCCESS) { - wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_CONNECTING; + wfx_rsi.dev_state.Clear(WifiState::kStationConnecting); ChipLogProgress(DeviceLayer, "sl_wifi_platform_join_network: rsi_wlan_connect_async failed: %ld on try %d", status, wfx_rsi.join_retries); wfx_retry_connection(++wfx_rsi.join_retries); @@ -613,7 +609,6 @@ void NotifyConnectivity(void) void HandleDHCPPolling(void) { struct netif * sta_netif; - WfxEvent_t event; sta_netif = wfx_get_netif(SL_WFX_STA_INTERFACE); if (sta_netif == NULL) @@ -644,19 +639,19 @@ void HandleDHCPPolling(void) { wfx_ipv6_notify(GET_IPV6_SUCCESS); hasNotifiedIPV6 = true; - event.eventType = WFX_EVT_STA_DHCP_DONE; - sl_matter_wifi_post_event(&event); + WifiEvent event = WifiEvent::kStationDhcpDone; + sl_matter_wifi_post_event(event); NotifyConnectivity(); } } /** ResetDHCPNotificationFlags * @brief Reset the flags that are used to notify the application about DHCP connectivity - * and emits a WFX_EVT_STA_DO_DHCP event to trigger DHCP polling checks. Helper function for ProcessEvent. + * and emits a WifiEvent::kStationDoDhcp event to trigger DHCP polling checks. Helper function for ProcessEvent. */ void ResetDHCPNotificationFlags(void) { - WfxEvent_t outEvent; + WifiEvent outEvent; #if (CHIP_DEVICE_CONFIG_ENABLE_IPV4) hasNotifiedIPV4 = false; @@ -664,13 +659,13 @@ void ResetDHCPNotificationFlags(void) hasNotifiedIPV6 = false; hasNotifiedWifiConnectivity = false; - outEvent.eventType = WFX_EVT_STA_DO_DHCP; - sl_matter_wifi_post_event(&outEvent); + outEvent = WifiEvent::kStationDoDhcp; + sl_matter_wifi_post_event(outEvent); } -void sl_matter_wifi_post_event(WfxEvent_t * event) +void sl_matter_wifi_post_event(WifiEvent event) { - sl_status_t status = osMessageQueuePut(sWifiEventQueue, event, 0, 0); + sl_status_t status = osMessageQueuePut(sWifiEventQueue, &event, 0, 0); if (status != osOK) { @@ -686,16 +681,16 @@ void sl_matter_wifi_post_event(WfxEvent_t * event) * This function is responsible for processing different types of Wi-Fi events and taking appropriate actions based on the event * type. * - * @param inEvent The input Wi-Fi event to be processed. + * @param event The input Wi-Fi event to be processed. */ -void ProcessEvent(WfxEvent_t inEvent) +void ProcessEvent(WifiEvent event) { // Process event - switch (inEvent.eventType) + switch (event) { - case WFX_EVT_STA_CONN: { - ChipLogDetail(DeviceLayer, "_onWFXEvent: WFX_EVT_STA_CONN"); - wfx_rsi.dev_state |= WFX_RSI_ST_STA_CONNECTED; + case WifiEvent::kStationConnect: { + ChipLogDetail(DeviceLayer, "WifiEvent::kStationConnect"); + wfx_rsi.dev_state.Set(WifiState::kStationConnected); ResetDHCPNotificationFlags(); wfx_lwip_set_sta_link_up(); /* We need to get AP Mac - TODO */ @@ -705,11 +700,12 @@ void ProcessEvent(WfxEvent_t inEvent) // is independant of IP connectivity. } break; - case WFX_EVT_STA_DISCONN: { - ChipLogDetail(DeviceLayer, "_onWFXEvent: WFX_EVT_STA_DISCONN"); + case WifiEvent::kStationDisconnect: { + ChipLogDetail(DeviceLayer, "WifiEvent::kStationDisconnect"); // TODO: This event is not being posted anywhere, seems to be a dead code or we are missing something - wfx_rsi.dev_state &= - ~(WFX_RSI_ST_STA_READY | WFX_RSI_ST_STA_CONNECTING | WFX_RSI_ST_STA_CONNECTED | WFX_RSI_ST_STA_DHCP_DONE); + WifiStateFlags flagsToClear = WifiStateFlags(WifiState::kStationReady, WifiState::kStationConnecting, + WifiState::kStationConnected, WifiState::kStationDhcpDone); + wfx_rsi.dev_state.Clear(flagsToClear); /* TODO: Implement disconnect notify */ ResetDHCPNotificationFlags(); wfx_lwip_set_sta_link_down(); // Internally dhcpclient_poll(netif) -> @@ -720,13 +716,10 @@ void ProcessEvent(WfxEvent_t inEvent) wfx_ipv6_notify(GET_IPV6_FAIL); } break; - case WFX_EVT_AP_START: - // TODO: Currently unimplemented - break; - case WFX_EVT_AP_STOP: + case WifiEvent::kAPStart: // TODO: Currently unimplemented break; - case WFX_EVT_SCAN: { + case WifiEvent::kScan: { #ifdef SL_WFX_CONFIG_SCAN rsi_rsp_scan_t scan_rsp = { 0 }; memset(&scan_rsp, 0, sizeof(scan_rsp)); @@ -791,22 +784,22 @@ void ProcessEvent(WfxEvent_t inEvent) #endif /* SL_WFX_CONFIG_SCAN */ } break; - case WFX_EVT_STA_START_JOIN: { + case WifiEvent::kStationStartJoin: { // saving the AP related info wfx_rsi_save_ap_info(); // Joining to the network sl_wifi_platform_join_network(); } break; - case WFX_EVT_STA_DO_DHCP: { + case WifiEvent::kStationDoDhcp: { StartDHCPTimer(WFX_RSI_DHCP_POLL_INTERVAL); } break; - case WFX_EVT_STA_DHCP_DONE: { + case WifiEvent::kStationDhcpDone: { CancelDHCPTimer(); } break; - case WFX_EVT_DHCP_POLL: { + case WifiEvent::kStationDhcpPoll: { HandleDHCPPolling(); } break; @@ -835,17 +828,17 @@ void sl_matter_wifi_task(void * arg) ChipLogError(DeviceLayer, "sl_matter_wifi_task: sl_matter_wifi_init failed: %ld", rsi_status); return; } - WfxEvent_t wfxEvent; + WifiEvent event; sl_matter_lwip_start(); sl_matter_wifi_task_started(); ChipLogProgress(DeviceLayer, "sl_matter_wifi_task: starting event loop"); for (;;) { - osStatus_t status = osMessageQueueGet(sWifiEventQueue, &wfxEvent, NULL, osWaitForever); + osStatus_t status = osMessageQueueGet(sWifiEventQueue, &event, NULL, osWaitForever); if (status == osOK) { - ProcessEvent(wfxEvent); + ProcessEvent(event); } else { @@ -875,9 +868,8 @@ void wfx_dhcp_got_ipv4(uint32_t ip) ChipLogProgress(DeviceLayer, "DHCP OK: IP=%d.%d.%d.%d", wfx_rsi.ip4_addr[0], wfx_rsi.ip4_addr[1], wfx_rsi.ip4_addr[2], wfx_rsi.ip4_addr[3]); /* Notify the Connectivity Manager - via the app */ - wfx_rsi.dev_state |= WFX_RSI_ST_STA_DHCP_DONE; + wfx_rsi.dev_state.Set(WifiState::kStationDhcpDone, WifiState::kStationReady); wfx_ip_changed_notify(IP_STATUS_SUCCESS); - wfx_rsi.dev_state |= WFX_RSI_ST_STA_READY; } #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ diff --git a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c b/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c index b1e4468cfb06e8..443d7be4ab4a2c 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c +++ b/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c @@ -41,7 +41,6 @@ #include "sl_status.h" #include "spidrv.h" -#include "WifiInterfaceAbstraction.h" #include "silabs_utils.h" #include "spi_multiplex.h" #include "wfx_host_events.h" diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c index fb6a947f95a40c..3c67d3955229c8 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c +++ b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c @@ -35,7 +35,6 @@ #include "event_groups.h" #include "task.h" -#include "WifiInterfaceAbstraction.h" #include "wfx_host_events.h" #if (SLI_SI91X_MCU_INTERFACE | EXP_BOARD) diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c index bb7dcf4a70498d..df3438b6ed5409 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c +++ b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c @@ -35,7 +35,6 @@ #include "event_groups.h" #include "task.h" -#include "WifiInterfaceAbstraction.h" #include "wfx_host_events.h" #include "rsi_board_configuration.h" diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c index b8ffea83f97b35..0f0c39a680bd68 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c +++ b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c @@ -39,7 +39,6 @@ extern void xPortSysTickHandler(void); /* RSI Driver include file */ #include "rsi_driver.h" /* RSI WLAN Config include file */ -#include "WifiInterfaceAbstraction.h" #include "rsi_bootup_config.h" #include "rsi_common_apis.h" #include "rsi_data_types.h" @@ -51,6 +50,8 @@ extern void xPortSysTickHandler(void); #include "rsi_wlan_apis.h" #include "rsi_wlan_config.h" +#define WFX_RSI_NUM_TIMERS (2) /* Number of RSI timers to alloc */ + #ifndef _use_the_rsi_defined_functions StaticTimer_t sRsiTimerBuffer; diff --git a/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c b/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c index 4db0470538027f..d6b67440364832 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c +++ b/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c @@ -44,7 +44,6 @@ #include "sl_device_init_hfxo.h" #include "sl_status.h" -#include "WifiInterfaceAbstraction.h" #include "silabs_utils.h" #include "sl_si91x_ncp_utility.h" #include "wfx_host_events.h" diff --git a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp index 0a21244f342194..7c1a9d233b0d55 100644 --- a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp +++ b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp @@ -34,6 +34,8 @@ using namespace chip; using namespace chip::DeviceLayer; +using WifiStateFlags = chip::BitFlags; + namespace { constexpr uint8_t kWlanMinRetryIntervalsInSec = 1; @@ -88,8 +90,8 @@ void RetryConnectionTimerHandler(void * arg) ***********************************************************************/ sl_status_t wfx_wifi_start(void) { - VerifyOrReturnError(!(wfx_rsi.dev_state & WFX_RSI_ST_STARTED), SL_STATUS_OK); - wfx_rsi.dev_state |= WFX_RSI_ST_STARTED; + VerifyOrReturnError(!(wfx_rsi.dev_state.Has(WifiState::kStationStarted)), SL_STATUS_OK); + wfx_rsi.dev_state.Set(WifiState::kStationStarted); // Creating a Wi-Fi driver thread sWlanThread = osThreadNew(sl_matter_wifi_task, NULL, &kWlanTaskAttr); @@ -109,7 +111,7 @@ sl_status_t wfx_wifi_start(void) ***********************************************************************/ void wfx_enable_sta_mode(void) { - wfx_rsi.dev_state |= WFX_RSI_ST_STA_MODE; + wfx_rsi.dev_state.Set(WifiState::kStationMode); } /********************************************************************* @@ -121,9 +123,7 @@ void wfx_enable_sta_mode(void) ***********************************************************************/ bool wfx_is_sta_mode_enabled(void) { - bool mode; - mode = !!(wfx_rsi.dev_state & WFX_RSI_ST_STA_MODE); - return mode; + return wfx_rsi.dev_state.Has(WifiState::kStationMode); } /********************************************************************* @@ -157,7 +157,7 @@ void wfx_set_wifi_provision(wfx_wifi_provision_t * cfg) { VerifyOrReturn(cfg != nullptr); wfx_rsi.sec = *cfg; - wfx_rsi.dev_state |= WFX_RSI_ST_STA_PROVISIONED; + wfx_rsi.dev_state.Set(WifiState::kStationProvisioned); } /********************************************************************* @@ -171,7 +171,7 @@ void wfx_set_wifi_provision(wfx_wifi_provision_t * cfg) bool wfx_get_wifi_provision(wfx_wifi_provision_t * wifiConfig) { VerifyOrReturnError(wifiConfig != nullptr, false); - VerifyOrReturnError(wfx_rsi.dev_state & WFX_RSI_ST_STA_PROVISIONED, false); + VerifyOrReturnError(wfx_rsi.dev_state.Has(WifiState::kStationProvisioned), false); *wifiConfig = wfx_rsi.sec; return true; } @@ -186,7 +186,7 @@ bool wfx_get_wifi_provision(wfx_wifi_provision_t * wifiConfig) void wfx_clear_wifi_provision(void) { memset(&wfx_rsi.sec, 0, sizeof(wfx_rsi.sec)); - wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_PROVISIONED; + wfx_rsi.dev_state.Clear(WifiState::kStationProvisioned); ChipLogProgress(DeviceLayer, "Clear WiFi Provision"); } @@ -199,13 +199,13 @@ void wfx_clear_wifi_provision(void) ****************************************************************************/ sl_status_t wfx_connect_to_ap(void) { - VerifyOrReturnError(wfx_rsi.dev_state & WFX_RSI_ST_STA_PROVISIONED, SL_STATUS_INVALID_CONFIGURATION); + VerifyOrReturnError(wfx_rsi.dev_state.Has(WifiState::kStationProvisioned), SL_STATUS_INVALID_CONFIGURATION); VerifyOrReturnError(wfx_rsi.sec.ssid_length, SL_STATUS_INVALID_CREDENTIALS); VerifyOrReturnError(wfx_rsi.sec.ssid_length <= WFX_MAX_SSID_LENGTH, SL_STATUS_HAS_OVERFLOWED); ChipLogProgress(DeviceLayer, "connect to access point: %s", wfx_rsi.sec.ssid); - WfxEvent_t event; - event.eventType = WFX_EVT_STA_START_JOIN; - sl_matter_wifi_post_event(&event); + + WifiEvent event = WifiEvent::kStationStartJoin; + sl_matter_wifi_post_event(event); return SL_STATUS_OK; } @@ -266,8 +266,7 @@ void wfx_setup_ip6_link_local(sl_wfx_interface_t whichif) ***********************************************************************/ bool wfx_is_sta_connected(void) { - bool status = (wfx_rsi.dev_state & WFX_RSI_ST_STA_CONNECTED) > 0; - return status; + return wfx_rsi.dev_state.Has(WifiState::kStationConnected); } /********************************************************************* @@ -280,7 +279,7 @@ bool wfx_is_sta_connected(void) ***********************************************************************/ wifi_mode_t wfx_get_wifi_mode(void) { - if (wfx_rsi.dev_state & WFX_RSI_ST_DEV_READY) + if (wfx_rsi.dev_state.Has(WifiState::kStationInit)) return WIFI_MODE_STA; return WIFI_MODE_NULL; } @@ -297,7 +296,7 @@ sl_status_t sl_matter_wifi_disconnect(void) { sl_status_t status; status = sl_wifi_platform_disconnect(); - wfx_rsi.dev_state &= ~WFX_RSI_ST_STA_CONNECTED; + wfx_rsi.dev_state.Clear(WifiState::kStationConnected); return status; } #if CHIP_DEVICE_CONFIG_ENABLE_IPV4 @@ -312,7 +311,7 @@ sl_status_t sl_matter_wifi_disconnect(void) bool wfx_have_ipv4_addr(sl_wfx_interface_t which_if) { VerifyOrReturnError(which_if == SL_WFX_STA_INTERFACE, false); - return ((wfx_rsi.dev_state & WFX_RSI_ST_STA_DHCP_DONE) > 0); + return wfx_rsi.dev_state.Has(WifiState::kStationDhcpDone); } #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ @@ -327,8 +326,8 @@ bool wfx_have_ipv4_addr(sl_wfx_interface_t which_if) bool wfx_have_ipv6_addr(sl_wfx_interface_t which_if) { VerifyOrReturnError(which_if == SL_WFX_STA_INTERFACE, false); - // TODO: WFX_RSI_ST_STA_CONNECTED does not guarantee SLAAC IPv6 LLA, maybe use a different FLAG - return ((wfx_rsi.dev_state & WFX_RSI_ST_STA_CONNECTED) > 0); + // TODO: WifiState::kStationConnected does not guarantee SLAAC IPv6 LLA, maybe use a different FLAG + return wfx_rsi.dev_state.Has(WifiState::kStationConnected); } /********************************************************************* @@ -341,7 +340,7 @@ bool wfx_have_ipv6_addr(sl_wfx_interface_t which_if) ***********************************************************************/ bool wfx_hw_ready(void) { - return (wfx_rsi.dev_state & WFX_RSI_ST_DEV_READY) ? true : false; + return wfx_rsi.dev_state.Has(WifiState::kStationInit); } /********************************************************************* @@ -404,9 +403,8 @@ bool wfx_start_scan(char * ssid, void (*callback)(wfx_wifi_scan_result_t *)) VerifyOrReturnError(wfx_rsi.scan_ssid != nullptr, false); chip::Platform::CopyString(wfx_rsi.scan_ssid, wfx_rsi.scan_ssid_length, ssid); - WfxEvent_t event; - event.eventType = WFX_EVT_SCAN; - sl_matter_wifi_post_event(&event); + WifiEvent event = WifiEvent::kScan; + sl_matter_wifi_post_event(event); return true; } @@ -486,7 +484,7 @@ void wfx_connected_notify(int32_t status, sl_wfx_mac_address_t * ap) * notification of disconnection * @param[in] status: * @return None - ********************************************************************************************/ + *************************************************************************************/ void wfx_disconnected_notify(int32_t status) { sl_wfx_disconnect_ind_t evt; @@ -504,7 +502,7 @@ void wfx_disconnected_notify(int32_t status) * notification of ipv6 * @param[in] got_ip: * @return None - ********************************************************************************************/ + *************************************************************************************/ void wfx_ipv6_notify(int got_ip) { sl_wfx_generic_message_t eventData; @@ -521,7 +519,7 @@ void wfx_ipv6_notify(int got_ip) * notification of ip change * @param[in] got_ip: * @return None - ********************************************************************************************/ + *************************************************************************************/ void wfx_ip_changed_notify(int got_ip) { sl_wfx_generic_message_t eventData; @@ -540,7 +538,7 @@ void wfx_ip_changed_notify(int got_ip) * with AP continously after a certain time interval. * @param[in] retryAttempt * @return None - ********************************************************************************************/ + *************************************************************************************/ void wfx_retry_connection(uint16_t retryAttempt) { // During commissioning, we retry to join the network MAX_JOIN_RETRIES_COUNT diff --git a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h index f0383b20e25f85..99ac5fdf88a4bd 100644 --- a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h +++ b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h @@ -18,6 +18,7 @@ #include #include +#include #include #include @@ -25,48 +26,40 @@ * Interface to RSI Sapis */ -#define WFX_RSI_WLAN_TASK_SZ (1024 + 512 + 256) /* Stack for the WLAN task */ // TODO: For rs9116 -#define WFX_RSI_BUF_SZ (1024 * 10) #define WFX_RSI_DHCP_POLL_INTERVAL (250) /* Poll interval in ms for DHCP */ -#define WFX_RSI_NUM_TIMERS (2) /* Number of RSI timers to alloc */ -typedef enum +enum class WifiEvent : uint8_t { - WFX_EVT_STA_CONN, - WFX_EVT_STA_DISCONN, - WFX_EVT_AP_START, - WFX_EVT_AP_STOP, - WFX_EVT_SCAN, /* This is used as scan result and start */ - WFX_EVT_STA_START_JOIN, - WFX_EVT_STA_DO_DHCP, - WFX_EVT_STA_DHCP_DONE, - WFX_EVT_DHCP_POLL -} WfxEventType_e; + kStationConnect = 0, + kStationDisconnect = 1, + kAPStart = 2, + kAPStop = 3, + kScan = 4, /* This is used as scan result and start */ + kStationStartJoin = 5, + kStationDoDhcp = 6, + kStationDhcpDone = 7, + kStationDhcpPoll = 8 +}; -typedef enum +enum class WifiState : uint16_t { - WFX_RSI_ST_DEV_READY = (1 << 0), - WFX_RSI_ST_AP_READY = (1 << 1), - WFX_RSI_ST_STA_PROVISIONED = (1 << 2), - WFX_RSI_ST_STA_CONNECTING = (1 << 3), - WFX_RSI_ST_STA_CONNECTED = (1 << 4), - WFX_RSI_ST_STA_DHCP_DONE = (1 << 6), /* Requested to do DHCP after conn */ - WFX_RSI_ST_STA_MODE = (1 << 7), /* Enable Station Mode */ - WFX_RSI_ST_AP_MODE = (1 << 8), /* Enable AP Mode */ - WFX_RSI_ST_STA_READY = (WFX_RSI_ST_STA_CONNECTED | WFX_RSI_ST_STA_DHCP_DONE), - WFX_RSI_ST_STARTED = (1 << 9), /* RSI task started */ - WFX_RSI_ST_SCANSTARTED = (1 << 10), /* Scan Started */ -} WfxStateType_e; - -typedef struct WfxEvent_s -{ - WfxEventType_e eventType; - void * eventData; // event data TODO: confirm needed -} WfxEvent_t; + kStationInit = (1 << 0), + kAPReady = (1 << 1), + kStationProvisioned = (1 << 2), + kStationConnecting = (1 << 3), + kStationConnected = (1 << 4), + kStationDhcpDone = (1 << 6), /* Requested to do DHCP after conn */ + kStationMode = (1 << 7), /* Enable Station Mode */ + kAPMode = (1 << 8), /* Enable AP Mode */ + kStationReady = (kStationConnected | kStationDhcpDone), + kStationStarted = (1 << 9), /* RSI task started */ + kScanStarted = (1 << 10), /* Scan Started */ +}; +using WifiStateFlags = chip::BitFlags; typedef struct wfx_rsi_s { - uint16_t dev_state; + WifiStateFlags dev_state; uint16_t ap_chan; /* The chan our STA is using */ wfx_wifi_provision_t sec; #ifdef SL_WFX_CONFIG_SCAN @@ -118,7 +111,6 @@ int32_t wfx_rsi_power_save(); /** * @brief Posts an event to the Wi-Fi task * - * @param[in] event Event to process. Must be valid ptr + * @param[in] event Event to process. */ -// TODO: Can't be a const & since the ncp builds are still using c files -void sl_matter_wifi_post_event(WfxEvent_t * event); +void sl_matter_wifi_post_event(WifiEvent event); From 9961bb8e8e947a38acf808edc7f89905f2dab477 Mon Sep 17 00:00:00 2001 From: Pradip De Date: Thu, 7 Nov 2024 05:40:28 -0800 Subject: [PATCH 082/121] Add largeMessage property support to Commands based on the quality setting in xml. (#36310) * Expose a bool-returning method 'CommandIsLarge' via the cluster-objects zap template. * Set the largeMessage=true for the 'CaptureSnapshot' command in AVStreamMgmt cluster xml. --- .../CodegenDataModelProvider.cpp | 2 ++ src/app/data-model-provider/MetadataTypes.h | 2 ++ .../templates/app/cluster-objects-src.zapt | 16 ++++++++++++++++ .../templates/app/cluster-objects.zapt | 1 + .../chip/camera-av-stream-management-cluster.xml | 2 ++ .../app-common/zap-generated/cluster-objects.cpp | 15 +++++++++++++++ .../app-common/zap-generated/cluster-objects.h | 1 + 7 files changed, 39 insertions(+) diff --git a/src/app/codegen-data-model-provider/CodegenDataModelProvider.cpp b/src/app/codegen-data-model-provider/CodegenDataModelProvider.cpp index eab221a86906b8..3e5e3a8cf039c8 100644 --- a/src/app/codegen-data-model-provider/CodegenDataModelProvider.cpp +++ b/src/app/codegen-data-model-provider/CodegenDataModelProvider.cpp @@ -241,6 +241,8 @@ DataModel::CommandEntry CommandEntryFrom(const ConcreteClusterPath & clusterPath entry.info.flags.Set(DataModel::CommandQualityFlags::kFabricScoped, CommandIsFabricScoped(clusterPath.mClusterId, clusterCommandId)); + entry.info.flags.Set(DataModel::CommandQualityFlags::kLargeMessage, + CommandHasLargePayload(clusterPath.mClusterId, clusterCommandId)); return entry; } diff --git a/src/app/data-model-provider/MetadataTypes.h b/src/app/data-model-provider/MetadataTypes.h index a3541faeabbf25..c1d173c985ee7a 100644 --- a/src/app/data-model-provider/MetadataTypes.h +++ b/src/app/data-model-provider/MetadataTypes.h @@ -83,10 +83,12 @@ struct AttributeEntry static const AttributeEntry kInvalid; }; +// Bitmask values for different Command qualities. enum class CommandQualityFlags : uint32_t { kFabricScoped = 0x0001, kTimed = 0x0002, // `T` quality on commands + kLargeMessage = 0x0004, // `L` quality on commands }; struct CommandInfo diff --git a/src/app/zap-templates/templates/app/cluster-objects-src.zapt b/src/app/zap-templates/templates/app/cluster-objects-src.zapt index 1322756b85213e..2663a6dd44c7a3 100644 --- a/src/app/zap-templates/templates/app/cluster-objects-src.zapt +++ b/src/app/zap-templates/templates/app/cluster-objects-src.zapt @@ -261,5 +261,21 @@ bool CommandIsFabricScoped(ClusterId aCluster, CommandId aCommand) return false; } +bool CommandHasLargePayload(ClusterId aCluster, CommandId aCommand) +{ + {{#zcl_clusters}} + {{#zcl_commands}} + {{#if isLargeMessage}} + if ((aCluster == Clusters::{{asUpperCamelCase parent.name}}::Id) && + (aCommand == Clusters::{{asUpperCamelCase parent.name}}::Commands::{{asUpperCamelCase name}}::Id)) + { + return true; + } + {{/if}} + {{/zcl_commands}} + {{/zcl_clusters}} + return false; +} + } // namespace app } // namespace chip diff --git a/src/app/zap-templates/templates/app/cluster-objects.zapt b/src/app/zap-templates/templates/app/cluster-objects.zapt index e9f42b17c5ff66..00cd367f85bfcb 100644 --- a/src/app/zap-templates/templates/app/cluster-objects.zapt +++ b/src/app/zap-templates/templates/app/cluster-objects.zapt @@ -228,6 +228,7 @@ public: bool CommandNeedsTimedInvoke(ClusterId aCluster, CommandId aCommand); bool CommandIsFabricScoped(ClusterId aCluster, CommandId aCommand); +bool CommandHasLargePayload(ClusterId aCluster, CommandId aCommand); } // namespace app } // namespace chip diff --git a/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml index 13d1f7a9e77be2..67761b41e8efc2 100644 --- a/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml @@ -380,6 +380,7 @@ Git: 0.9-fall2024-411-g9835b5cd7 This command SHALL return a Snapshot from the camera. + @@ -387,6 +388,7 @@ Git: 0.9-fall2024-411-g9835b5cd7 This command SHALL be sent by the device in response to the CaptureSnapshot command, carrying the requested snapshot. + diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp index 111324e9cb51ae..9dd42a69d9e430 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp @@ -35101,5 +35101,20 @@ bool CommandIsFabricScoped(ClusterId aCluster, CommandId aCommand) return false; } +bool CommandHasLargePayload(ClusterId aCluster, CommandId aCommand) +{ + if ((aCluster == Clusters::CameraAvStreamManagement::Id) && + (aCommand == Clusters::CameraAvStreamManagement::Commands::CaptureSnapshot::Id)) + { + return true; + } + if ((aCluster == Clusters::CameraAvStreamManagement::Id) && + (aCommand == Clusters::CameraAvStreamManagement::Commands::CaptureSnapshotResponse::Id)) + { + return true; + } + return false; +} + } // namespace app } // namespace chip diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h index d7f69cc3818e3e..62a98d4eabfb3e 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h @@ -47768,6 +47768,7 @@ struct DecodableType bool CommandNeedsTimedInvoke(ClusterId aCluster, CommandId aCommand); bool CommandIsFabricScoped(ClusterId aCluster, CommandId aCommand); +bool CommandHasLargePayload(ClusterId aCluster, CommandId aCommand); } // namespace app } // namespace chip From 26e22b612ca82cc35604055b84bdc6ca38198b68 Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Thu, 7 Nov 2024 09:59:30 -0500 Subject: [PATCH 083/121] [Silabs]Update our refrigerator app zap configs. (#36373) * Update our refrigerator app zap configs. * fix missed rename from a previous pr * Move identify cluster to endpoint 1 (from 0) --- examples/refrigerator-app/silabs/BUILD.gn | 4 +- .../data_model/refrigerator-thread-app.matter | 127 ++++--- .../data_model/refrigerator-thread-app.zap | 340 ++++++++--------- .../data_model/refrigerator-wifi-app.matter | 126 ++++--- .../data_model/refrigerator-wifi-app.zap | 342 ++++++++---------- 5 files changed, 444 insertions(+), 495 deletions(-) diff --git a/examples/refrigerator-app/silabs/BUILD.gn b/examples/refrigerator-app/silabs/BUILD.gn index 9e63c6c10e164b..200c909b1f2629 100644 --- a/examples/refrigerator-app/silabs/BUILD.gn +++ b/examples/refrigerator-app/silabs/BUILD.gn @@ -18,7 +18,7 @@ import("//build_overrides/efr32_sdk.gni") import("//build_overrides/pigweed.gni") import("${build_root}/config/defaults.gni") -import("${efr32_sdk_build_root}/silabs_executable.gni") +import("${silabs_sdk_build_root}/silabs_executable.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/platform/device.gni") @@ -38,7 +38,7 @@ if (wifi_soc) { import("${chip_root}/third_party/silabs/SiWx917_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/SiWx917" } else { - import("${efr32_sdk_build_root}/efr32_sdk.gni") + import("${silabs_sdk_build_root}/efr32_sdk.gni") examples_plat_dir = "${chip_root}/examples/platform/silabs/efr32" } diff --git a/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.matter b/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.matter index 173823b22d6439..49f9672046088a 100644 --- a/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.matter +++ b/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.matter @@ -241,6 +241,56 @@ struct AtomicAttributeStatusStruct { status statusCode = 1; } +/** Attributes and commands for putting a device into Identification mode (e.g. flashing a light). */ +cluster Identify = 3 { + revision 4; + + enum EffectIdentifierEnum : enum8 { + kBlink = 0; + kBreathe = 1; + kOkay = 2; + kChannelChange = 11; + kFinishEffect = 254; + kStopEffect = 255; + } + + enum EffectVariantEnum : enum8 { + kDefault = 0; + } + + enum IdentifyTypeEnum : enum8 { + kNone = 0; + kLightOutput = 1; + kVisibleIndicator = 2; + kAudibleBeep = 3; + kDisplay = 4; + kActuator = 5; + } + + attribute int16u identifyTime = 0; + readonly attribute IdentifyTypeEnum identifyType = 1; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct IdentifyRequest { + int16u identifyTime = 0; + } + + request struct TriggerEffectRequest { + EffectIdentifierEnum effectIdentifier = 0; + EffectVariantEnum effectVariant = 1; + } + + /** Command description for Identify */ + command access(invoke: manage) Identify(IdentifyRequest): DefaultSuccess = 0; + /** Command description for TriggerEffect */ + command access(invoke: manage) TriggerEffect(TriggerEffectRequest): DefaultSuccess = 64; +} + /** The Descriptor Cluster is meant to replace the support from the Zigbee Device Object (ZDO) for describing a node, its endpoints and clusters. */ cluster Descriptor = 29 { revision 2; @@ -922,53 +972,6 @@ cluster NetworkCommissioning = 49 { command access(invoke: administer) QueryIdentity(QueryIdentityRequest): QueryIdentityResponse = 9; } -/** The cluster provides commands for retrieving unstructured diagnostic logs from a Node that may be used to aid in diagnostics. */ -cluster DiagnosticLogs = 50 { - revision 1; // NOTE: Default/not specifically set - - enum IntentEnum : enum8 { - kEndUserSupport = 0; - kNetworkDiag = 1; - kCrashLogs = 2; - } - - enum StatusEnum : enum8 { - kSuccess = 0; - kExhausted = 1; - kNoLogs = 2; - kBusy = 3; - kDenied = 4; - } - - enum TransferProtocolEnum : enum8 { - kResponsePayload = 0; - kBDX = 1; - } - - readonly attribute command_id generatedCommandList[] = 65528; - readonly attribute command_id acceptedCommandList[] = 65529; - readonly attribute event_id eventList[] = 65530; - readonly attribute attrib_id attributeList[] = 65531; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct RetrieveLogsRequestRequest { - IntentEnum intent = 0; - TransferProtocolEnum requestedProtocol = 1; - optional char_string<32> transferFileDesignator = 2; - } - - response struct RetrieveLogsResponse = 1 { - StatusEnum status = 0; - long_octet_string logContent = 1; - optional epoch_us UTCTimeStamp = 2; - optional systime_us timeSinceBoot = 3; - } - - /** Retrieving diagnostic logs from a Node */ - command RetrieveLogsRequest(RetrieveLogsRequestRequest): RetrieveLogsResponse = 0; -} - /** The General Diagnostics Cluster, along with other diagnostics clusters, provide a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. */ cluster GeneralDiagnostics = 51 { revision 2; @@ -1756,10 +1759,12 @@ endpoint 0 { ram attribute lastNetworkingStatus; ram attribute lastNetworkID; ram attribute lastConnectErrorValue; + callback attribute supportedThreadFeatures; + callback attribute threadVersion; callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute attributeList; - ram attribute featureMap default = 2; + callback attribute featureMap default = 2; ram attribute clusterRevision default = 1; handle command ScanNetworks; @@ -1772,17 +1777,6 @@ endpoint 0 { handle command ReorderNetwork; } - server cluster DiagnosticLogs { - callback attribute generatedCommandList; - callback attribute acceptedCommandList; - callback attribute attributeList; - ram attribute featureMap default = 0; - ram attribute clusterRevision default = 1; - - handle command RetrieveLogsRequest; - handle command RetrieveLogsResponse; - } - server cluster GeneralDiagnostics { emits event HardwareFaultChange; emits event RadioFaultChange; @@ -1894,6 +1888,19 @@ endpoint 1 { device type ma_refrigerator = 112, version 1; + server cluster Identify { + ram attribute identifyTime default = 0x0; + ram attribute identifyType default = 0x00; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 4; + + handle command Identify; + handle command TriggerEffect; + } + server cluster Descriptor { callback attribute deviceTypeList; callback attribute serverList; @@ -1920,7 +1927,7 @@ endpoint 1 { } server cluster RefrigeratorAlarm { - ram attribute mask default = 0; + ram attribute mask default = 1; ram attribute state default = 0; ram attribute supported default = 0; callback attribute generatedCommandList; diff --git a/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.zap b/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.zap index 57785bd3adc150..3a6bcd833161f6 100644 --- a/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.zap +++ b/examples/refrigerator-app/silabs/data_model/refrigerator-thread-app.zap @@ -1,6 +1,6 @@ { "fileFormat": 2, - "featureLevel": 103, + "featureLevel": 104, "creator": "zap", "keyValuePairs": [ { @@ -950,22 +950,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -1120,22 +1104,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -1609,113 +1577,37 @@ "reportableChange": 0 }, { - "name": "GeneratedCommandList", - "code": 65528, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, - { - "name": "AcceptedCommandList", - "code": 65529, + "name": "SupportedThreadFeatures", + "code": 9, "mfgCode": null, "side": "server", - "type": "array", + "type": "ThreadCapabilitiesBitmap", "included": 1, "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": null, + "defaultValue": "", "reportable": 1, "minInterval": 1, "maxInterval": 65534, "reportableChange": 0 }, { - "name": "AttributeList", - "code": 65531, + "name": "ThreadVersion", + "code": 10, "mfgCode": null, "side": "server", - "type": "array", + "type": "int16u", "included": 1, "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, - { - "name": "FeatureMap", - "code": 65532, - "mfgCode": null, - "side": "server", - "type": "bitmap32", - "included": 1, - "storageOption": "RAM", - "singleton": 0, - "bounded": 0, - "defaultValue": "2", + "defaultValue": "", "reportable": 1, "minInterval": 1, "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "ClusterRevision", - "code": 65533, - "mfgCode": null, - "side": "server", - "type": "int16u", - "included": 1, - "storageOption": "RAM", - "singleton": 0, - "bounded": 0, - "defaultValue": "1", - "reportable": 1, - "minInterval": 0, - "maxInterval": 65344, - "reportableChange": 0 - } - ] - }, - { - "name": "Diagnostic Logs", - "code": 50, - "mfgCode": null, - "define": "DIAGNOSTIC_LOGS_CLUSTER", - "side": "server", - "enabled": 1, - "commands": [ - { - "name": "RetrieveLogsRequest", - "code": 0, - "mfgCode": null, - "source": "client", - "isIncoming": 1, - "isEnabled": 1 - }, - { - "name": "RetrieveLogsResponse", - "code": 1, - "mfgCode": null, - "source": "server", - "isIncoming": 0, - "isEnabled": 1 - } - ], - "attributes": [ { "name": "GeneratedCommandList", "code": 65528, @@ -1748,22 +1640,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -1787,10 +1663,10 @@ "side": "server", "type": "bitmap32", "included": 1, - "storageOption": "RAM", + "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "2", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -1808,8 +1684,8 @@ "bounded": 0, "defaultValue": "1", "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, + "minInterval": 0, + "maxInterval": 65344, "reportableChange": 0 } ] @@ -2416,22 +2292,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -3109,6 +2969,146 @@ "deviceTypeCode": 112, "deviceTypeProfileId": 259, "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x00", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "4", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, { "name": "Descriptor", "code": 29, @@ -3353,22 +3353,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -3437,7 +3421,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "1", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -3507,22 +3491,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, diff --git a/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.matter b/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.matter index d3a8603e740154..b4386fe9ef77ac 100644 --- a/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.matter +++ b/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.matter @@ -241,6 +241,56 @@ struct AtomicAttributeStatusStruct { status statusCode = 1; } +/** Attributes and commands for putting a device into Identification mode (e.g. flashing a light). */ +cluster Identify = 3 { + revision 4; + + enum EffectIdentifierEnum : enum8 { + kBlink = 0; + kBreathe = 1; + kOkay = 2; + kChannelChange = 11; + kFinishEffect = 254; + kStopEffect = 255; + } + + enum EffectVariantEnum : enum8 { + kDefault = 0; + } + + enum IdentifyTypeEnum : enum8 { + kNone = 0; + kLightOutput = 1; + kVisibleIndicator = 2; + kAudibleBeep = 3; + kDisplay = 4; + kActuator = 5; + } + + attribute int16u identifyTime = 0; + readonly attribute IdentifyTypeEnum identifyType = 1; + readonly attribute command_id generatedCommandList[] = 65528; + readonly attribute command_id acceptedCommandList[] = 65529; + readonly attribute event_id eventList[] = 65530; + readonly attribute attrib_id attributeList[] = 65531; + readonly attribute bitmap32 featureMap = 65532; + readonly attribute int16u clusterRevision = 65533; + + request struct IdentifyRequest { + int16u identifyTime = 0; + } + + request struct TriggerEffectRequest { + EffectIdentifierEnum effectIdentifier = 0; + EffectVariantEnum effectVariant = 1; + } + + /** Command description for Identify */ + command access(invoke: manage) Identify(IdentifyRequest): DefaultSuccess = 0; + /** Command description for TriggerEffect */ + command access(invoke: manage) TriggerEffect(TriggerEffectRequest): DefaultSuccess = 64; +} + /** The Descriptor Cluster is meant to replace the support from the Zigbee Device Object (ZDO) for describing a node, its endpoints and clusters. */ cluster Descriptor = 29 { revision 2; @@ -922,53 +972,6 @@ cluster NetworkCommissioning = 49 { command access(invoke: administer) QueryIdentity(QueryIdentityRequest): QueryIdentityResponse = 9; } -/** The cluster provides commands for retrieving unstructured diagnostic logs from a Node that may be used to aid in diagnostics. */ -cluster DiagnosticLogs = 50 { - revision 1; // NOTE: Default/not specifically set - - enum IntentEnum : enum8 { - kEndUserSupport = 0; - kNetworkDiag = 1; - kCrashLogs = 2; - } - - enum StatusEnum : enum8 { - kSuccess = 0; - kExhausted = 1; - kNoLogs = 2; - kBusy = 3; - kDenied = 4; - } - - enum TransferProtocolEnum : enum8 { - kResponsePayload = 0; - kBDX = 1; - } - - readonly attribute command_id generatedCommandList[] = 65528; - readonly attribute command_id acceptedCommandList[] = 65529; - readonly attribute event_id eventList[] = 65530; - readonly attribute attrib_id attributeList[] = 65531; - readonly attribute bitmap32 featureMap = 65532; - readonly attribute int16u clusterRevision = 65533; - - request struct RetrieveLogsRequestRequest { - IntentEnum intent = 0; - TransferProtocolEnum requestedProtocol = 1; - optional char_string<32> transferFileDesignator = 2; - } - - response struct RetrieveLogsResponse = 1 { - StatusEnum status = 0; - long_octet_string logContent = 1; - optional epoch_us UTCTimeStamp = 2; - optional systime_us timeSinceBoot = 3; - } - - /** Retrieving diagnostic logs from a Node */ - command RetrieveLogsRequest(RetrieveLogsRequestRequest): RetrieveLogsResponse = 0; -} - /** The General Diagnostics Cluster, along with other diagnostics clusters, provide a means to acquire standardized diagnostics metrics that MAY be used by a Node to assist a user or Administrative Node in diagnosing potential problems. */ cluster GeneralDiagnostics = 51 { revision 2; @@ -1667,10 +1670,11 @@ endpoint 0 { ram attribute lastNetworkingStatus; ram attribute lastNetworkID; ram attribute lastConnectErrorValue; + callback attribute supportedWiFiBands; callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute attributeList; - ram attribute featureMap default = 2; + callback attribute featureMap default = 2; ram attribute clusterRevision default = 1; handle command ScanNetworks; @@ -1683,17 +1687,6 @@ endpoint 0 { handle command ReorderNetwork; } - server cluster DiagnosticLogs { - callback attribute generatedCommandList; - callback attribute acceptedCommandList; - callback attribute attributeList; - ram attribute featureMap default = 0; - ram attribute clusterRevision default = 1; - - handle command RetrieveLogsRequest; - handle command RetrieveLogsResponse; - } - server cluster GeneralDiagnostics { emits event HardwareFaultChange; emits event RadioFaultChange; @@ -1803,6 +1796,19 @@ endpoint 1 { device type ma_refrigerator = 112, version 1; + server cluster Identify { + ram attribute identifyTime default = 0x0; + ram attribute identifyType default = 0x00; + callback attribute generatedCommandList; + callback attribute acceptedCommandList; + callback attribute attributeList; + ram attribute featureMap default = 0; + ram attribute clusterRevision default = 4; + + handle command Identify; + handle command TriggerEffect; + } + server cluster Descriptor { callback attribute deviceTypeList; callback attribute serverList; @@ -1829,7 +1835,7 @@ endpoint 1 { } server cluster RefrigeratorAlarm { - ram attribute mask default = 0; + ram attribute mask default = 1; ram attribute state default = 0; ram attribute supported default = 0; callback attribute generatedCommandList; diff --git a/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.zap b/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.zap index edc35aa7a37657..addfd6f5198818 100644 --- a/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.zap +++ b/examples/refrigerator-app/silabs/data_model/refrigerator-wifi-app.zap @@ -1,6 +1,6 @@ { "fileFormat": 2, - "featureLevel": 103, + "featureLevel": 104, "creator": "zap", "keyValuePairs": [ { @@ -17,13 +17,6 @@ } ], "package": [ - { - "pathRelativity": "relativeToZap", - "path": "../../../../src/app/zap-templates/app-templates.json", - "type": "gen-templates-json", - "category": "matter", - "version": "chip-v1" - }, { "pathRelativity": "relativeToZap", "path": "../../../../src/app/zap-templates/zcl/zcl.json", @@ -31,6 +24,13 @@ "category": "matter", "version": 1, "description": "Matter SDK ZCL data" + }, + { + "pathRelativity": "relativeToZap", + "path": "../../../../src/app/zap-templates/app-templates.json", + "type": "gen-templates-json", + "category": "matter", + "version": "chip-v1" } ], "endpointTypes": [ @@ -950,22 +950,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -1120,22 +1104,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -1609,40 +1577,8 @@ "reportableChange": 0 }, { - "name": "GeneratedCommandList", - "code": 65528, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, - { - "name": "AcceptedCommandList", - "code": 65529, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, - { - "name": "AttributeList", - "code": 65531, + "name": "SupportedWiFiBands", + "code": 8, "mfgCode": null, "side": "server", "type": "array", @@ -1656,66 +1592,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "FeatureMap", - "code": 65532, - "mfgCode": null, - "side": "server", - "type": "bitmap32", - "included": 1, - "storageOption": "RAM", - "singleton": 0, - "bounded": 0, - "defaultValue": "2", - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, - { - "name": "ClusterRevision", - "code": 65533, - "mfgCode": null, - "side": "server", - "type": "int16u", - "included": 1, - "storageOption": "RAM", - "singleton": 0, - "bounded": 0, - "defaultValue": "1", - "reportable": 1, - "minInterval": 0, - "maxInterval": 65344, - "reportableChange": 0 - } - ] - }, - { - "name": "Diagnostic Logs", - "code": 50, - "mfgCode": null, - "define": "DIAGNOSTIC_LOGS_CLUSTER", - "side": "server", - "enabled": 1, - "commands": [ - { - "name": "RetrieveLogsRequest", - "code": 0, - "mfgCode": null, - "source": "client", - "isIncoming": 1, - "isEnabled": 1 - }, - { - "name": "RetrieveLogsResponse", - "code": 1, - "mfgCode": null, - "source": "server", - "isIncoming": 0, - "isEnabled": 1 - } - ], - "attributes": [ { "name": "GeneratedCommandList", "code": 65528, @@ -1748,22 +1624,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -1787,10 +1647,10 @@ "side": "server", "type": "bitmap32", "included": 1, - "storageOption": "RAM", + "storageOption": "External", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "2", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -1808,8 +1668,8 @@ "bounded": 0, "defaultValue": "1", "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, + "minInterval": 0, + "maxInterval": 65344, "reportableChange": 0 } ] @@ -3014,6 +2874,146 @@ "deviceTypeCode": 112, "deviceTypeProfileId": 259, "clusters": [ + { + "name": "Identify", + "code": 3, + "mfgCode": null, + "define": "IDENTIFY_CLUSTER", + "side": "server", + "enabled": 1, + "commands": [ + { + "name": "Identify", + "code": 0, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + }, + { + "name": "TriggerEffect", + "code": 64, + "mfgCode": null, + "source": "client", + "isIncoming": 1, + "isEnabled": 1 + } + ], + "attributes": [ + { + "name": "IdentifyTime", + "code": 0, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "IdentifyType", + "code": 1, + "mfgCode": null, + "side": "server", + "type": "IdentifyTypeEnum", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0x00", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "GeneratedCommandList", + "code": 65528, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AcceptedCommandList", + "code": 65529, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "AttributeList", + "code": 65531, + "mfgCode": null, + "side": "server", + "type": "array", + "included": 1, + "storageOption": "External", + "singleton": 0, + "bounded": 0, + "defaultValue": "", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "FeatureMap", + "code": 65532, + "mfgCode": null, + "side": "server", + "type": "bitmap32", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "0", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + }, + { + "name": "ClusterRevision", + "code": 65533, + "mfgCode": null, + "side": "server", + "type": "int16u", + "included": 1, + "storageOption": "RAM", + "singleton": 0, + "bounded": 0, + "defaultValue": "4", + "reportable": 1, + "minInterval": 1, + "maxInterval": 65534, + "reportableChange": 0 + } + ] + }, { "name": "Descriptor", "code": 29, @@ -3258,22 +3258,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, @@ -3342,7 +3326,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0", + "defaultValue": "1", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -3412,22 +3396,6 @@ "maxInterval": 65534, "reportableChange": 0 }, - { - "name": "EventList", - "code": 65530, - "mfgCode": null, - "side": "server", - "type": "array", - "included": 1, - "storageOption": "External", - "singleton": 0, - "bounded": 0, - "defaultValue": null, - "reportable": 1, - "minInterval": 1, - "maxInterval": 65534, - "reportableChange": 0 - }, { "name": "AttributeList", "code": 65531, From 5e101e0b0264272a24047f3074edc5d267edd4a3 Mon Sep 17 00:00:00 2001 From: BoB13-Matter Date: Fri, 8 Nov 2024 01:07:19 +0900 Subject: [PATCH 084/121] Ensure SYSTEM_STATS_INCREMENT only on successful memory allocation in SystemPacketBuffer (#36415) --- src/system/SystemPacketBuffer.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/system/SystemPacketBuffer.cpp b/src/system/SystemPacketBuffer.cpp index 79e1bd25a67d8a..f644d1a23eb323 100644 --- a/src/system/SystemPacketBuffer.cpp +++ b/src/system/SystemPacketBuffer.cpp @@ -620,7 +620,6 @@ PacketBufferHandle PacketBufferHandle::New(size_t aAvailableSize, uint16_t aRese // checked to fit in a size_t. const size_t lBlockSize = static_cast(sumOfSizes); lPacket = reinterpret_cast(chip::Platform::MemoryAlloc(lBlockSize)); - SYSTEM_STATS_INCREMENT(chip::System::Stats::kSystemLayer_NumPacketBufs); #else #error "Unimplemented PacketBuffer storage case" @@ -632,6 +631,8 @@ PacketBufferHandle PacketBufferHandle::New(size_t aAvailableSize, uint16_t aRese return PacketBufferHandle(); } + SYSTEM_STATS_INCREMENT(chip::System::Stats::kSystemLayer_NumPacketBufs); + lPacket->payload = lPacket->ReserveStart() + aReservedSize; lPacket->len = lPacket->tot_len = 0; lPacket->next = nullptr; From 44499b41c2000c4f106afed975fa8ee049b1a3b0 Mon Sep 17 00:00:00 2001 From: Amine Alami <43780877+Alami-Amine@users.noreply.github.com> Date: Thu, 7 Nov 2024 17:10:35 +0100 Subject: [PATCH 085/121] Migrate from deprecated OpenSSL SHA256_* APIs to EVP APIs (#36386) * Migrate from deprecated OpenSSL SHA256_* APIs to EVP APIs * Integrating comments --- src/crypto/CHIPCryptoPAL.h | 3 ++ src/crypto/CHIPCryptoPALOpenSSL.cpp | 82 ++++++++++++++++++++++------- 2 files changed, 67 insertions(+), 18 deletions(-) diff --git a/src/crypto/CHIPCryptoPAL.h b/src/crypto/CHIPCryptoPAL.h index 80611e93d12d88..b0790f85deb54f 100644 --- a/src/crypto/CHIPCryptoPAL.h +++ b/src/crypto/CHIPCryptoPAL.h @@ -942,6 +942,9 @@ class Hash_SHA256_stream private: HashSHA256OpaqueContext mContext; +#if CHIP_CRYPTO_BORINGSSL || CHIP_CRYPTO_OPENSSL + bool mInitialized = false; +#endif }; class HKDF_sha diff --git a/src/crypto/CHIPCryptoPALOpenSSL.cpp b/src/crypto/CHIPCryptoPALOpenSSL.cpp index c1182ac8ebe03c..56e8bf9fc40922 100644 --- a/src/crypto/CHIPCryptoPALOpenSSL.cpp +++ b/src/crypto/CHIPCryptoPALOpenSSL.cpp @@ -433,36 +433,57 @@ CHIP_ERROR Hash_SHA1(const uint8_t * data, const size_t data_length, uint8_t * o return CHIP_NO_ERROR; } -Hash_SHA256_stream::Hash_SHA256_stream() {} +// For OpenSSL, we store a pointer to the digest context (EVP_MD_CTX) since EVP_MD_CTX is Opaque. +static_assert(kMAX_Hash_SHA256_Context_Size >= sizeof(void *), + "kMAX_Hash_SHA256_Context_Size needs to at least be able to store a pointer"); -Hash_SHA256_stream::~Hash_SHA256_stream() +// Storing a pointer to EVP_MD_CTX in HashSHA256OpaqueContext instead of the actual EVP_MD_CTX structure, as EVP_MD_CTX was made +// opaque by OpenSSL and is dynamically allocated. +static inline void set_inner_hash_evp_md_ctx(HashSHA256OpaqueContext * context, EVP_MD_CTX * evp_ctx) { - Clear(); + *SafePointerCast(context) = evp_ctx; } -static_assert(kMAX_Hash_SHA256_Context_Size >= sizeof(SHA256_CTX), - "kMAX_Hash_SHA256_Context_Size is too small for the size of underlying SHA256_CTX"); +static inline EVP_MD_CTX * to_inner_hash_evp_md_ctx(HashSHA256OpaqueContext * context) +{ + return *SafePointerCast(context); +} -static inline SHA256_CTX * to_inner_hash_sha256_context(HashSHA256OpaqueContext * context) +Hash_SHA256_stream::Hash_SHA256_stream() : mInitialized(false) { - return SafePointerCast(context); + set_inner_hash_evp_md_ctx(&mContext, nullptr); +} + +Hash_SHA256_stream::~Hash_SHA256_stream() +{ + Clear(); } CHIP_ERROR Hash_SHA256_stream::Begin() { - SHA256_CTX * const context = to_inner_hash_sha256_context(&mContext); - const int result = SHA256_Init(context); + EVP_MD_CTX * mdctx = EVP_MD_CTX_new(); + VerifyOrReturnError(mdctx != nullptr, CHIP_ERROR_INTERNAL); + + set_inner_hash_evp_md_ctx(&mContext, mdctx); + + const int result = EVP_DigestInit_ex(mdctx, _digestForType(DigestType::SHA256), nullptr); + VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL); + mInitialized = true; return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA256_stream::AddData(const ByteSpan data) { - SHA256_CTX * const context = to_inner_hash_sha256_context(&mContext); + VerifyOrReturnError(mInitialized, CHIP_ERROR_UNINITIALIZED); + + EVP_MD_CTX * mdctx = to_inner_hash_evp_md_ctx(&mContext); + VerifyOrReturnError(mdctx != nullptr, CHIP_ERROR_INTERNAL); + + const int result = EVP_DigestUpdate(mdctx, data.data(), data.size()); - const int result = SHA256_Update(context, Uint8::to_const_uchar(data.data()), data.size()); VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; @@ -470,27 +491,43 @@ CHIP_ERROR Hash_SHA256_stream::AddData(const ByteSpan data) CHIP_ERROR Hash_SHA256_stream::GetDigest(MutableByteSpan & out_buffer) { - SHA256_CTX * context = to_inner_hash_sha256_context(&mContext); - // Back-up context as we are about to finalize the hash to extract digest. - SHA256_CTX previous_ctx = *context; + VerifyOrReturnError(mInitialized, CHIP_ERROR_UNINITIALIZED); + + EVP_MD_CTX * mdctx = to_inner_hash_evp_md_ctx(&mContext); + + // Back-up the context as we are about to finalize the hash to extract digest. + EVP_MD_CTX * previous_mdctx = EVP_MD_CTX_new(); + VerifyOrReturnError(previous_mdctx != nullptr, CHIP_ERROR_INTERNAL); + const int copy_result = EVP_MD_CTX_copy_ex(previous_mdctx, mdctx); + VerifyOrReturnError(copy_result == 1, CHIP_ERROR_INTERNAL); // Pad + compute digest, then finalize context. It is restored next line to continue. CHIP_ERROR result = Finish(out_buffer); - // Restore context prior to finalization. - *context = previous_ctx; + // free the finalized context. + EVP_MD_CTX_free(mdctx); + + // Restore the backed up context, to be able to get intermediate digest again if needed + set_inner_hash_evp_md_ctx(&mContext, previous_mdctx); return result; } CHIP_ERROR Hash_SHA256_stream::Finish(MutableByteSpan & out_buffer) { + unsigned int size; + VerifyOrReturnError(out_buffer.size() >= kSHA256_Hash_Length, CHIP_ERROR_BUFFER_TOO_SMALL); + VerifyOrReturnError(mInitialized, CHIP_ERROR_UNINITIALIZED); + + EVP_MD_CTX * mdctx = to_inner_hash_evp_md_ctx(&mContext); + + const int result = EVP_DigestFinal_ex(mdctx, out_buffer.data(), &size); - SHA256_CTX * const context = to_inner_hash_sha256_context(&mContext); - const int result = SHA256_Final(Uint8::to_uchar(out_buffer.data()), context); VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL); + VerifyOrReturnError(size == kSHA256_Hash_Length, CHIP_ERROR_INTERNAL); + out_buffer = out_buffer.SubSpan(0, kSHA256_Hash_Length); return CHIP_NO_ERROR; @@ -498,6 +535,13 @@ CHIP_ERROR Hash_SHA256_stream::Finish(MutableByteSpan & out_buffer) void Hash_SHA256_stream::Clear() { + EVP_MD_CTX * mdctx = to_inner_hash_evp_md_ctx(&mContext); + + // EVP_MD_CTX_free does nothing if a nullptr is passed to it + EVP_MD_CTX_free(mdctx); + set_inner_hash_evp_md_ctx(&mContext, nullptr); + + mInitialized = false; OPENSSL_cleanse(this, sizeof(*this)); } @@ -1405,6 +1449,8 @@ void Spake2p_P256_SHA256_HKDF_HMAC::Clear() BN_CTX_free(context->bn_ctx); } + sha256_hash_ctx.Clear(); + free_point(M); free_point(N); free_point(X); From c7d0fe473a9658db72510980139a1c5009fc414f Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Thu, 7 Nov 2024 11:23:36 -0500 Subject: [PATCH 086/121] Fix android CHIPTest linkage after #36297 . (#36424) Tested locally that `android-arm64-chip-test` builds. Co-authored-by: Andrei Litvin --- examples/android/CHIPTest/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/android/CHIPTest/BUILD.gn b/examples/android/CHIPTest/BUILD.gn index c8ccb2e614c103..7dee07e6f693c1 100644 --- a/examples/android/CHIPTest/BUILD.gn +++ b/examples/android/CHIPTest/BUILD.gn @@ -39,6 +39,7 @@ shared_library("jni") { "${chip_root}/src/platform/android:java", "${chip_root}/src/platform/android:logging", "${chip_root}/src/platform/tests:tests", + "${chip_root}/src/pw_backends/assert:assert.impl", "${chip_root}/third_party/inipp", "${chip_root}/third_party/nlfaultinjection:nlfaultinjection", ] From 8aa5f608da3ad39bf587d45f60a31870841ceb71 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Thu, 7 Nov 2024 08:23:46 -0800 Subject: [PATCH 087/121] [Fabric-Sync] Add 'add-device' and 'remove-device' commands (#36390) --- examples/fabric-sync/admin/DeviceManager.cpp | 44 +++++++++++ examples/fabric-sync/admin/DeviceManager.h | 47 +++++++++++ examples/fabric-sync/admin/PairingManager.cpp | 12 ++- examples/fabric-sync/admin/PairingManager.h | 14 +--- .../bridge/include/CHIPProjectAppConfig.h | 3 + .../fabric-sync/shell/AddBridgeCommand.cpp | 2 +- examples/fabric-sync/shell/AddBridgeCommand.h | 2 +- .../fabric-sync/shell/AddDeviceCommand.cpp | 79 +++++++++++++++++++ examples/fabric-sync/shell/AddDeviceCommand.h | 40 ++++++++++ examples/fabric-sync/shell/BUILD.gn | 4 + .../fabric-sync/shell/RemoveDeviceCommand.cpp | 67 ++++++++++++++++ .../fabric-sync/shell/RemoveDeviceCommand.h | 37 +++++++++ examples/fabric-sync/shell/ShellCommands.cpp | 76 ++++++++++++++++++ 13 files changed, 411 insertions(+), 16 deletions(-) create mode 100644 examples/fabric-sync/shell/AddDeviceCommand.cpp create mode 100644 examples/fabric-sync/shell/AddDeviceCommand.h create mode 100644 examples/fabric-sync/shell/RemoveDeviceCommand.cpp create mode 100644 examples/fabric-sync/shell/RemoveDeviceCommand.h diff --git a/examples/fabric-sync/admin/DeviceManager.cpp b/examples/fabric-sync/admin/DeviceManager.cpp index 3d2055444f92a8..814b7f39356c9d 100644 --- a/examples/fabric-sync/admin/DeviceManager.cpp +++ b/examples/fabric-sync/admin/DeviceManager.cpp @@ -79,6 +79,37 @@ CHIP_ERROR DeviceManager::PairRemoteFabricBridge(NodeId nodeId, uint32_t setupPI return CHIP_NO_ERROR; } +CHIP_ERROR DeviceManager::PairRemoteDevice(NodeId nodeId, const char * payload) +{ + CHIP_ERROR err = PairingManager::Instance().PairDeviceWithCode(nodeId, payload); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to pair device: Node ID " ChipLogFormatX64 " with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(nodeId), err.Format()); + return err; + } + + ChipLogProgress(NotSpecified, "Successfully paired device: Node ID " ChipLogFormatX64, ChipLogValueX64(nodeId)); + return CHIP_NO_ERROR; +} + +CHIP_ERROR DeviceManager::PairRemoteDevice(NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, + uint16_t deviceRemotePort) +{ + CHIP_ERROR err = PairingManager::Instance().PairDevice(nodeId, setupPINCode, deviceRemoteIp, deviceRemotePort); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to pair device: Node ID " ChipLogFormatX64 " with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(nodeId), err.Format()); + return err; + } + + ChipLogProgress(NotSpecified, "Successfully paired device: Node ID " ChipLogFormatX64, ChipLogValueX64(nodeId)); + return CHIP_NO_ERROR; +} + CHIP_ERROR DeviceManager::UnpairRemoteFabricBridge() { if (mRemoteBridgeNodeId == kUndefinedNodeId) @@ -99,6 +130,19 @@ CHIP_ERROR DeviceManager::UnpairRemoteFabricBridge() return CHIP_NO_ERROR; } +CHIP_ERROR DeviceManager::UnpairRemoteDevice(NodeId nodeId) +{ + CHIP_ERROR err = PairingManager::Instance().UnpairDevice(nodeId); + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, "Failed to unpair remote device " ChipLogFormatX64, ChipLogValueX64(nodeId)); + return err; + } + + ChipLogProgress(NotSpecified, "Successfully unpaired remote device: Node ID " ChipLogFormatX64, ChipLogValueX64(nodeId)); + return CHIP_NO_ERROR; +} + void DeviceManager::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) { if (err != CHIP_NO_ERROR) diff --git a/examples/fabric-sync/admin/DeviceManager.h b/examples/fabric-sync/admin/DeviceManager.h index 866e0c20f6c333..57a3bd300af2e8 100644 --- a/examples/fabric-sync/admin/DeviceManager.h +++ b/examples/fabric-sync/admin/DeviceManager.h @@ -67,8 +67,55 @@ class DeviceManager : public PairingDelegate CHIP_ERROR PairRemoteFabricBridge(chip::NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, uint16_t deviceRemotePort); + /** + * @brief Pair a remote Matter device to the current fabric. + * + * This function initiates the pairing process for a remote device using the specified parameters. + + * @param nodeId The user-defined ID for the node being commissioned. It doesn’t need to be the same ID, + * as for the first fabric. + * @param payload The the QR code payload or a manual pairing code generated by the first commissioner + * instance when opened commissioning window. + * + * @return CHIP_ERROR Returns CHIP_NO_ERROR on success or an appropriate error code on failure. + */ + CHIP_ERROR PairRemoteDevice(chip::NodeId nodeId, const char * payload); + + /** + * @brief Pair a remote Matter device to the current fabric. + * + * This function initiates the pairing process for a remote device using the specified parameters. + + * @param nodeId The user-defined ID for the node being commissioned. It doesn’t need to be the same ID, + * as for the first fabric. + * @param setupPINCode The setup PIN code used to authenticate the pairing process. + * @param deviceRemoteIp The IP address of the remote device that is being paired as part of the fabric bridge. + * @param deviceRemotePort The secured device port of the remote device that is being paired as part of the fabric bridge. + * + * @return CHIP_ERROR Returns CHIP_NO_ERROR on success or an appropriate error code on failure. + */ + CHIP_ERROR PairRemoteDevice(chip::NodeId nodeId, uint32_t setupPINCode, const char * deviceRemoteIp, uint16_t deviceRemotePort); + + /** + * @brief Unpair the remote Matter fabric bridge. + * + * This function initiates the unpairing process for the remote Matter fabric bridge from the current fabric. + * + * @return CHIP_ERROR Returns CHIP_NO_ERROR on success or an appropriate error code on failure. + */ CHIP_ERROR UnpairRemoteFabricBridge(); + /** + * @brief Unpair a specific remote Matter device from the current fabric. + * + * This function removes a specific remote device, identified by the node ID, from the fabric. + * + * @param nodeId The user-defined ID of the node that is being unpaired. + * + * @return CHIP_ERROR Returns CHIP_NO_ERROR on success or an appropriate error code on failure. + */ + CHIP_ERROR UnpairRemoteDevice(chip::NodeId nodeId); + private: friend DeviceManager & DeviceMgr(); diff --git a/examples/fabric-sync/admin/PairingManager.cpp b/examples/fabric-sync/admin/PairingManager.cpp index 32317b4fa30e3a..6b5f707d0c2132 100644 --- a/examples/fabric-sync/admin/PairingManager.cpp +++ b/examples/fabric-sync/admin/PairingManager.cpp @@ -290,10 +290,10 @@ void PairingManager::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err) ChipLogProgress(NotSpecified, "Device commissioning Failure: %s", ErrorStr(err)); } - if (mCommissioningDelegate) + if (mPairingDelegate) { - mCommissioningDelegate->OnCommissioningComplete(nodeId, err); - SetCommissioningDelegate(nullptr); + mPairingDelegate->OnCommissioningComplete(nodeId, err); + SetPairingDelegate(nullptr); } } @@ -454,6 +454,12 @@ void PairingManager::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E { // print to console fprintf(stderr, "Device with Node ID: " ChipLogFormatX64 " has been successfully removed.\n", ChipLogValueX64(nodeId)); + + if (self->mPairingDelegate) + { + self->mPairingDelegate->OnDeviceRemoved(nodeId, err); + self->SetPairingDelegate(nullptr); + } } else { diff --git a/examples/fabric-sync/admin/PairingManager.h b/examples/fabric-sync/admin/PairingManager.h index 5ef8a0761f7f28..b9b404ee76bbfd 100644 --- a/examples/fabric-sync/admin/PairingManager.h +++ b/examples/fabric-sync/admin/PairingManager.h @@ -36,18 +36,12 @@ class CommissioningWindowDelegate virtual ~CommissioningWindowDelegate() = default; }; -class CommissioningDelegate -{ -public: - virtual void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) = 0; - virtual ~CommissioningDelegate() = default; -}; - class PairingDelegate { public: - virtual void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) = 0; - virtual ~PairingDelegate() = default; + virtual void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) {} + virtual void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) {} + virtual ~PairingDelegate() = default; }; /** @@ -84,7 +78,6 @@ class PairingManager : public chip::Controller::DevicePairingDelegate, CHIP_ERROR Init(chip::Controller::DeviceCommissioner * commissioner); void SetOpenCommissioningWindowDelegate(CommissioningWindowDelegate * delegate) { mCommissioningWindowDelegate = delegate; } - void SetCommissioningDelegate(CommissioningDelegate * delegate) { mCommissioningDelegate = delegate; } void SetPairingDelegate(PairingDelegate * delegate) { mPairingDelegate = delegate; } PairingDelegate * GetPairingDelegate() { return mPairingDelegate; } @@ -177,7 +170,6 @@ class PairingManager : public chip::Controller::DevicePairingDelegate, chip::Controller::DeviceCommissioner * mCommissioner = nullptr; CommissioningWindowDelegate * mCommissioningWindowDelegate = nullptr; - CommissioningDelegate * mCommissioningDelegate = nullptr; PairingDelegate * mPairingDelegate = nullptr; chip::NodeId mNodeId = chip::kUndefinedNodeId; diff --git a/examples/fabric-sync/bridge/include/CHIPProjectAppConfig.h b/examples/fabric-sync/bridge/include/CHIPProjectAppConfig.h index b1a711658d3b91..58f45c03052b17 100644 --- a/examples/fabric-sync/bridge/include/CHIPProjectAppConfig.h +++ b/examples/fabric-sync/bridge/include/CHIPProjectAppConfig.h @@ -36,6 +36,9 @@ // FabricSync needs to be both commissioners and commissionees #define CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE 1 +// See issue 23625. +#define CHIP_CONFIG_UNSAFE_SUBSCRIPTION_EXCHANGE_MANAGER_USE 1 + // Enable app platform #define CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED 1 diff --git a/examples/fabric-sync/shell/AddBridgeCommand.cpp b/examples/fabric-sync/shell/AddBridgeCommand.cpp index 09246c11528e7e..936ac1c321ca50 100644 --- a/examples/fabric-sync/shell/AddBridgeCommand.cpp +++ b/examples/fabric-sync/shell/AddBridgeCommand.cpp @@ -73,7 +73,7 @@ CHIP_ERROR AddBridgeCommand::RunCommand() return CHIP_NO_ERROR; } - admin::PairingManager::Instance().SetCommissioningDelegate(this); + admin::PairingManager::Instance().SetPairingDelegate(this); return admin::DeviceMgr().PairRemoteFabricBridge(mBridgeNodeId, mSetupPINCode, mRemoteAddr, mRemotePort); } diff --git a/examples/fabric-sync/shell/AddBridgeCommand.h b/examples/fabric-sync/shell/AddBridgeCommand.h index 48c1830260421e..d2f6ff7b306c94 100644 --- a/examples/fabric-sync/shell/AddBridgeCommand.h +++ b/examples/fabric-sync/shell/AddBridgeCommand.h @@ -23,7 +23,7 @@ namespace commands { -class AddBridgeCommand : public Command, public admin::CommissioningDelegate +class AddBridgeCommand : public Command, public admin::PairingDelegate { public: AddBridgeCommand(chip::NodeId nodeId, uint32_t setupPINCode, const char * remoteAddr, uint16_t remotePort); diff --git a/examples/fabric-sync/shell/AddDeviceCommand.cpp b/examples/fabric-sync/shell/AddDeviceCommand.cpp new file mode 100644 index 00000000000000..218691e74401ea --- /dev/null +++ b/examples/fabric-sync/shell/AddDeviceCommand.cpp @@ -0,0 +1,79 @@ +/* + * 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 "AddDeviceCommand.h" + +#include +#include + +using namespace ::chip; + +namespace commands { + +AddDeviceCommand::AddDeviceCommand(chip::NodeId nodeId, uint32_t setupPINCode, const char * remoteAddr, uint16_t remotePort) : + mNodeId(nodeId), mSetupPINCode(setupPINCode), mRemoteAddr(remoteAddr), mRemotePort(remotePort) +{} + +void AddDeviceCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERROR err) +{ + if (mNodeId != deviceId) + { + if (err != CHIP_NO_ERROR) + { + ChipLogError(NotSpecified, + "Failed to pair non-specified device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + else + { + ChipLogProgress(NotSpecified, "Commissioning complete for non-specified device: NodeId: " ChipLogFormatX64, + ChipLogValueX64(deviceId)); + } + return; + } + + if (err == CHIP_NO_ERROR) + { + ChipLogProgress(NotSpecified, "Successfully paired device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mNodeId)); + + admin::DeviceMgr().UpdateLastUsedNodeId(mNodeId); + } + else + { + ChipLogError(NotSpecified, "Failed to pair device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + + CommandRegistry::Instance().ResetActiveCommand(); +} + +CHIP_ERROR AddDeviceCommand::RunCommand() +{ + if (admin::DeviceMgr().IsCurrentBridgeDevice(mNodeId)) + { + // print to console + fprintf(stderr, "The specified node ID has been reserved by the Fabric Bridge.\n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + admin::PairingManager::Instance().SetPairingDelegate(this); + + return admin::DeviceMgr().PairRemoteDevice(mNodeId, mSetupPINCode, mRemoteAddr, mRemotePort); +} + +} // namespace commands diff --git a/examples/fabric-sync/shell/AddDeviceCommand.h b/examples/fabric-sync/shell/AddDeviceCommand.h new file mode 100644 index 00000000000000..35d0ed93d9a416 --- /dev/null +++ b/examples/fabric-sync/shell/AddDeviceCommand.h @@ -0,0 +1,40 @@ +/* + * 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. + * + */ + +#pragma once + +#include +#include + +namespace commands { + +class AddDeviceCommand : public Command, public admin::PairingDelegate +{ +public: + AddDeviceCommand(chip::NodeId nodeId, uint32_t setupPINCode, const char * remoteAddr, uint16_t remotePort); + void OnCommissioningComplete(chip::NodeId deviceId, CHIP_ERROR err) override; + CHIP_ERROR RunCommand() override; + +private: + chip::NodeId mNodeId; + uint32_t mSetupPINCode; + const char * mRemoteAddr; + uint16_t mRemotePort; +}; + +} // namespace commands diff --git a/examples/fabric-sync/shell/BUILD.gn b/examples/fabric-sync/shell/BUILD.gn index 6f64b9106ab2bf..b3726ee178f9e0 100644 --- a/examples/fabric-sync/shell/BUILD.gn +++ b/examples/fabric-sync/shell/BUILD.gn @@ -29,9 +29,13 @@ source_set("shell") { sources = [ "AddBridgeCommand.cpp", "AddBridgeCommand.h", + "AddDeviceCommand.cpp", + "AddDeviceCommand.h", "CommandRegistry.h", "RemoveBridgeCommand.cpp", "RemoveBridgeCommand.h", + "RemoveDeviceCommand.cpp", + "RemoveDeviceCommand.h", "ShellCommands.cpp", "ShellCommands.h", ] diff --git a/examples/fabric-sync/shell/RemoveDeviceCommand.cpp b/examples/fabric-sync/shell/RemoveDeviceCommand.cpp new file mode 100644 index 00000000000000..266a2ad1065569 --- /dev/null +++ b/examples/fabric-sync/shell/RemoveDeviceCommand.cpp @@ -0,0 +1,67 @@ +/* + * 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 "RemoveDeviceCommand.h" + +#include +#include + +using namespace ::chip; + +namespace commands { + +RemoveDeviceCommand::RemoveDeviceCommand(NodeId nodeId) : mNodeId(nodeId) {} + +void RemoveDeviceCommand::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) +{ + if (mNodeId != deviceId) + { + ChipLogProgress(NotSpecified, "An non-specified device: NodeId: " ChipLogFormatX64 " is removed.", + ChipLogValueX64(deviceId)); + return; + } + + if (err == CHIP_NO_ERROR) + { + // print to console + fprintf(stderr, "Successfully removed device: NodeId: " ChipLogFormatX64 "\n", ChipLogValueX64(mNodeId)); + } + else + { + ChipLogError(NotSpecified, "Failed to remove device (0x:" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, + ChipLogValueX64(deviceId), err.Format()); + } + + CommandRegistry::Instance().ResetActiveCommand(); +} + +CHIP_ERROR RemoveDeviceCommand::RunCommand() +{ + if (admin::DeviceMgr().IsCurrentBridgeDevice(mNodeId)) + { + // print to console + fprintf(stderr, "The specified node ID has been reserved by the Fabric Bridge.\n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + admin::PairingManager::Instance().SetPairingDelegate(this); + + return admin::DeviceMgr().UnpairRemoteDevice(mNodeId); +} + +} // namespace commands diff --git a/examples/fabric-sync/shell/RemoveDeviceCommand.h b/examples/fabric-sync/shell/RemoveDeviceCommand.h new file mode 100644 index 00000000000000..cb394d66b3b4ff --- /dev/null +++ b/examples/fabric-sync/shell/RemoveDeviceCommand.h @@ -0,0 +1,37 @@ +/* + * 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. + * + */ + +#pragma once + +#include +#include + +namespace commands { + +class RemoveDeviceCommand : public Command, public admin::PairingDelegate +{ +public: + RemoveDeviceCommand(chip::NodeId nodeId); + void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; + CHIP_ERROR RunCommand() override; + +private: + chip::NodeId mNodeId = chip::kUndefinedNodeId; +}; + +} // namespace commands diff --git a/examples/fabric-sync/shell/ShellCommands.cpp b/examples/fabric-sync/shell/ShellCommands.cpp index 1edbd433eac64a..a654fbcc9f98f1 100644 --- a/examples/fabric-sync/shell/ShellCommands.cpp +++ b/examples/fabric-sync/shell/ShellCommands.cpp @@ -17,7 +17,9 @@ #include "ShellCommands.h" #include "AddBridgeCommand.h" +#include "AddDeviceCommand.h" #include "RemoveBridgeCommand.h" +#include "RemoveDeviceCommand.h" #include #include @@ -41,6 +43,10 @@ static CHIP_ERROR PrintAllCommands() " add-bridge Pair remote fabric bridge to local fabric. Usage: app add-bridge node-id setup-pin-code " "device-remote-ip device-remote-port\r\n"); streamer_printf(sout, " remove-bridge Remove the remote fabric bridge from the local fabric. Usage: app remove-bridge\r\n"); + streamer_printf(sout, + " add-device Pair a device to local fabric. Usage: app add-device node-id setup-pin-code " + "device-remote-ip device-remote-port\r\n"); + streamer_printf(sout, " remove-device Remove a device from the local fabric. Usage: app remove-device node-id\r\n"); streamer_printf(sout, " sync-device Sync a device from other ecosystem. Usage: app sync-device endpointid\r\n"); streamer_printf(sout, "\r\n"); @@ -106,6 +112,68 @@ static CHIP_ERROR HandleRemoveBridgeCommand(int argc, char ** argv) return result; } +static CHIP_ERROR HandleAddDeviceCommand(int argc, char ** argv) +{ + if (argc != 5) + { + fprintf(stderr, + "Invalid arguments. Usage: app add-device \n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + // Check if there is already an active command + if (commands::CommandRegistry::Instance().IsCommandActive()) + { + fprintf(stderr, "Another command is currently active. Please wait until it completes.\n"); + return CHIP_ERROR_BUSY; + } + + // Parse arguments + chip::NodeId nodeId = static_cast(strtoull(argv[1], nullptr, 10)); + uint32_t setupPINCode = static_cast(strtoul(argv[2], nullptr, 10)); + const char * remoteAddr = argv[3]; + uint16_t remotePort = static_cast(strtoul(argv[4], nullptr, 10)); + + auto command = std::make_unique(nodeId, setupPINCode, remoteAddr, remotePort); + + CHIP_ERROR result = command->RunCommand(); + if (result == CHIP_NO_ERROR) + { + commands::CommandRegistry::Instance().SetActiveCommand(std::move(command)); + } + + return result; +} + +static CHIP_ERROR HandleRemoveDeviceCommand(int argc, char ** argv) +{ + if (argc != 2) + { + fprintf(stderr, "Invalid arguments. Usage: app remove-device \n"); + return CHIP_ERROR_INVALID_ARGUMENT; + } + + // Check if there is already an active command + if (commands::CommandRegistry::Instance().IsCommandActive()) + { + fprintf(stderr, "Another command is currently active. Please wait until it completes.\n"); + return CHIP_ERROR_BUSY; + } + + // Parse arguments + chip::NodeId nodeId = static_cast(strtoull(argv[1], nullptr, 10)); + + auto command = std::make_unique(nodeId); + + CHIP_ERROR result = command->RunCommand(); + if (result == CHIP_NO_ERROR) + { + commands::CommandRegistry::Instance().SetActiveCommand(std::move(command)); + } + + return result; +} + static CHIP_ERROR AppPlatformHandler(int argc, char ** argv) { CHIP_ERROR error = CHIP_NO_ERROR; @@ -126,6 +194,14 @@ static CHIP_ERROR AppPlatformHandler(int argc, char ** argv) { return HandleRemoveBridgeCommand(argc, argv); } + else if (strcmp(argv[0], "add-device") == 0) + { + return HandleAddDeviceCommand(argc, argv); + } + else if (strcmp(argv[0], "remove-device") == 0) + { + return HandleRemoveDeviceCommand(argc, argv); + } else { return CHIP_ERROR_INVALID_ARGUMENT; From 078bc30d3f9f5d46c989272b2a50b3f5e8eb2f55 Mon Sep 17 00:00:00 2001 From: lpbeliveau-silabs <112982107+lpbeliveau-silabs@users.noreply.github.com> Date: Thu, 7 Nov 2024 11:45:45 -0500 Subject: [PATCH 088/121] [SL-UP] Circular callback fix (#85) (#36406) --- .../all-clusters-common/src/fan-stub.cpp | 7 +- .../fan-control-server/fan-control-server.cpp | 77 +++++++++++++++---- .../fan-control-server/fan-control-server.h | 10 +++ src/app/util/util.cpp | 2 +- 4 files changed, 73 insertions(+), 23 deletions(-) diff --git a/examples/all-clusters-app/all-clusters-common/src/fan-stub.cpp b/examples/all-clusters-app/all-clusters-common/src/fan-stub.cpp index e0fb68c95f647c..06de80e2f94a06 100644 --- a/examples/all-clusters-app/all-clusters-common/src/fan-stub.cpp +++ b/examples/all-clusters-app/all-clusters-common/src/fan-stub.cpp @@ -19,7 +19,6 @@ #include #include #include -#include #include #include #include @@ -34,13 +33,11 @@ using namespace chip::app::Clusters::FanControl::Attributes; using Protocols::InteractionModel::Status; namespace { -class FanControlManager : public AttributeAccessInterface, public Delegate +class FanControlManager : public FanControlAttributeAccessInterface, public Delegate { public: // Register for the FanControl cluster on all endpoints. - FanControlManager(EndpointId aEndpointId) : - AttributeAccessInterface(Optional(aEndpointId), FanControl::Id), Delegate(aEndpointId) - {} + FanControlManager(EndpointId aEndpointId) : FanControlAttributeAccessInterface(aEndpointId), Delegate(aEndpointId) {} CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override; Status HandleStep(StepDirectionEnum aDirection, bool aWrap, bool aLowestOff) override; diff --git a/src/app/clusters/fan-control-server/fan-control-server.cpp b/src/app/clusters/fan-control-server/fan-control-server.cpp index 46f4c6d7c0bb70..4e10a1b6c92aeb 100644 --- a/src/app/clusters/fan-control-server/fan-control-server.cpp +++ b/src/app/clusters/fan-control-server/fan-control-server.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -389,7 +390,7 @@ void MatterFanControlClusterServerAttributeChangedCallback(const app::ConcreteAt // Plus 99 then integer divide by 100 instead of multiplying 0.01 to avoid floating point precision error uint8_t speedSetting = static_cast((speedMax * percent + 99) / 100); - if (currentSpeedSetting.IsNull() || speedSetting != currentSpeedSetting.Value()) + if (currentSpeedSetting != speedSetting) { status = SpeedSetting::Set(attributePath.mEndpointId, speedSetting); VerifyOrReturn(Status::Success == status, @@ -413,26 +414,67 @@ void MatterFanControlClusterServerAttributeChangedCallback(const app::ConcreteAt ChipLogError(Zcl, "Failed to set FanMode to off with error: 0x%02x", to_underlying(status))); } - // Adjust PercentSetting from a speed value change for SpeedSetting - // percent = floor( speed/SpeedMax * 100 ) - uint8_t speedMax; - status = SpeedMax::Get(attributePath.mEndpointId, &speedMax); - VerifyOrReturn(Status::Success == status, - ChipLogError(Zcl, "Failed to get SpeedMax with error: 0x%02x", to_underlying(status))); + // Adjust PercentSetting from a speed value change for SpeedSetting only when the SpeedSetting change was received + // on a write command, not when it was changed by the server or the app logic. This avoids circular logic such as + //(with a SpeedMax of 10): + // 1. Client sets the PercetSetting to 25% + // 2. Server sets the SpeedSetting to 3 through the server callbackm, which sets the PercentSetting to 30% + // 3. Server sets the PercentSetting to 30% through the server callback + } + break; + } + default: + break; + } +} - DataModel::Nullable currentPercentSetting; - status = PercentSetting::Get(attributePath.mEndpointId, currentPercentSetting); - VerifyOrReturn(Status::Success == status, - ChipLogError(Zcl, "Failed to get PercentSetting with error: 0x%02x", to_underlying(status))); +CHIP_ERROR FanControlAttributeAccessInterface::Write(const ConcreteDataAttributePath & aPath, AttributeValueDecoder & aDecoder) +{ + Status status = Status::Success; + switch (aPath.mAttributeId) + { + case SpeedSetting::Id: { + DataModel::Nullable speedSetting; + ReturnErrorOnFailure(aDecoder.Decode(speedSetting)); + + DataModel::Nullable currentSpeedSetting; + status = SpeedSetting::Get(aPath.mEndpointId, currentSpeedSetting); + ReturnLogErrorOnFailure(StatusIB(status).ToChipError()); - float speed = speedSetting.Value(); - Percent percentSetting = static_cast(speed / speedMax * 100); + if (speedSetting != currentSpeedSetting) + { + status = SpeedSetting::Set(aPath.mEndpointId, speedSetting); + ReturnLogErrorOnFailure(StatusIB(status).ToChipError()); + // Skip the last step if we are writing NULL + VerifyOrReturnValue(!speedSetting.IsNull(), CHIP_NO_ERROR); - if (currentPercentSetting.IsNull() || percentSetting != currentPercentSetting.Value()) + if (SupportsMultiSpeed(aPath.mEndpointId)) { - status = PercentSetting::Set(attributePath.mEndpointId, percentSetting); - VerifyOrReturn(Status::Success == status, - ChipLogError(Zcl, "Failed to set PercentSetting with error: 0x%02x", to_underlying(status))); + // If SpeedSetting is set to 0, the server SHALL set the FanMode attribute value to Off. + if (speedSetting.Value() == 0) + { + status = SetFanModeToOff(aPath.mEndpointId); + ReturnLogErrorOnFailure(StatusIB(status).ToChipError()); + } + + // Adjust PercentSetting from a speed value change for SpeedSetting + // percent = floor( speed/SpeedMax * 100 ) + uint8_t speedMax; + status = SpeedMax::Get(aPath.mEndpointId, &speedMax); + ReturnLogErrorOnFailure(StatusIB(status).ToChipError()); + + DataModel::Nullable currentPercentSetting; + status = PercentSetting::Get(aPath.mEndpointId, currentPercentSetting); + ReturnLogErrorOnFailure(StatusIB(status).ToChipError()); + + float speed = speedSetting.Value(); + Percent percentSetting = static_cast(speed / speedMax * 100); + + if (currentPercentSetting != percentSetting) + { + status = PercentSetting::Set(aPath.mEndpointId, percentSetting); + ReturnLogErrorOnFailure(StatusIB(status).ToChipError()); + } } } break; @@ -440,6 +482,7 @@ void MatterFanControlClusterServerAttributeChangedCallback(const app::ConcreteAt default: break; } + return CHIP_NO_ERROR; } bool emberAfFanControlClusterStepCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, diff --git a/src/app/clusters/fan-control-server/fan-control-server.h b/src/app/clusters/fan-control-server/fan-control-server.h index 5721e34b4eba90..99967492dd021b 100644 --- a/src/app/clusters/fan-control-server/fan-control-server.h +++ b/src/app/clusters/fan-control-server/fan-control-server.h @@ -19,6 +19,7 @@ #include "fan-control-delegate.h" #include +#include #include namespace chip { @@ -26,6 +27,15 @@ namespace app { namespace Clusters { namespace FanControl { +class FanControlAttributeAccessInterface : public AttributeAccessInterface +{ +public: + FanControlAttributeAccessInterface(EndpointId aEndpoint) : AttributeAccessInterface(Optional(aEndpoint), Id) {} + + CHIP_ERROR Write(const ConcreteDataAttributePath & aPath, AttributeValueDecoder & aDecoder) override; + CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override { return CHIP_NO_ERROR; } +}; + void SetDefaultDelegate(EndpointId aEndpoint, Delegate * aDelegate); Delegate * GetDelegate(EndpointId aEndpoint); diff --git a/src/app/util/util.cpp b/src/app/util/util.cpp index 3072e8aafd2a7f..3c6acab8a07cb3 100644 --- a/src/app/util/util.cpp +++ b/src/app/util/util.cpp @@ -107,10 +107,10 @@ void MatterUnitLocalizationPluginServerInitCallback() {} void MatterProxyValidPluginServerInitCallback() {} void MatterProxyDiscoveryPluginServerInitCallback() {} void MatterProxyConfigurationPluginServerInitCallback() {} -void MatterFanControlPluginServerInitCallback() {} void MatterActivatedCarbonFilterMonitoringPluginServerInitCallback() {} void MatterHepaFilterMonitoringPluginServerInitCallback() {} void MatterAirQualityPluginServerInitCallback() {} +void MatterFanControlPluginServerInitCallback() {} void MatterCarbonMonoxideConcentrationMeasurementPluginServerInitCallback() {} void MatterCarbonDioxideConcentrationMeasurementPluginServerInitCallback() {} void MatterFormaldehydeConcentrationMeasurementPluginServerInitCallback() {} From 8797fa0df8d374d525649172b75bbd9f4e309513 Mon Sep 17 00:00:00 2001 From: dinabenamar <108664279+dinabenamar@users.noreply.github.com> Date: Thu, 7 Nov 2024 18:24:00 +0100 Subject: [PATCH 089/121] [NXP][platform][common] Updates to support CHIP configuration using generated macros (#36322) * [NXP][platform][common] Support to configure CHIP using generated macros Signed-off-by: Dina Benamar * [NXP] Remove unused macro from config header file Signed-off-by: Dina Benamar --------- Signed-off-by: Dina Benamar --- .../CHIPDeviceNXPPlatformDefaultConfig.h | 35 ++++++++++++++++--- .../nxp/common/CHIPNXPPlatformDefaultConfig.h | 9 +++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/platform/nxp/common/CHIPDeviceNXPPlatformDefaultConfig.h b/src/platform/nxp/common/CHIPDeviceNXPPlatformDefaultConfig.h index c4e77e87b4b9ad..1cdb0644590362 100644 --- a/src/platform/nxp/common/CHIPDeviceNXPPlatformDefaultConfig.h +++ b/src/platform/nxp/common/CHIPDeviceNXPPlatformDefaultConfig.h @@ -27,6 +27,29 @@ // ==================== Platform Adaptations ==================== +#ifdef CONFIG_CHIP_USE_GENERATED_CONFIG +#define CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID CONFIG_CHIP_DEVICE_VENDOR_ID +#define CHIP_DEVICE_CONFIG_DEVICE_VENDOR_NAME CONFIG_CHIP_DEVICE_VENDOR_NAME +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID CONFIG_CHIP_DEVICE_PRODUCT_ID +#define CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_NAME CONFIG_CHIP_DEVICE_PRODUCT_NAME +#define CHIP_DEVICE_CONFIG_DEVICE_HARDWARE_VERSION CONFIG_CHIP_DEVICE_HARDWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEFAULT_DEVICE_HARDWARE_VERSION_STRING CONFIG_CHIP_DEVICE_HARDWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION CONFIG_CHIP_DEVICE_SOFTWARE_VERSION +#define CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING CONFIG_CHIP_DEVICE_SOFTWARE_VERSION_STRING +#define CHIP_DEVICE_CONFIG_TEST_MANUFACTURING_DATE CONFIG_CHIP_DEVICE_MANUFACTURING_DATE +#define CHIP_DEVICE_CONFIG_DEVICE_TYPE CONFIG_CHIP_DEVICE_TYPE +#define CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_ITERATION_COUNT CONFIG_CHIP_DEVICE_SPAKE2_IT +#define CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_SALT CONFIG_CHIP_DEVICE_SPAKE2_SALT +#define CHIP_DEVICE_CONFIG_USE_TEST_SPAKE2P_VERIFIER CONFIG_CHIP_DEVICE_SPAKE2_TEST_VERIFIER + +#if !CONFIG_CHIP_PLAT_LOAD_REAL_FACTORY_DATA +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_DISCRIMINATOR CONFIG_CHIP_DEVICE_DISCRIMINATOR +#define CHIP_DEVICE_CONFIG_USE_TEST_SETUP_PIN_CODE CONFIG_CHIP_DEVICE_SPAKE2_PASSCODE +#define CHIP_DEVICE_CONFIG_USE_TEST_PAIRING_CODE CONFIG_CHIP_DEVICE_USE_TEST_PAIRING_CODE +#define CHIP_DEVICE_CONFIG_TEST_SERIAL_NUMBER CONFIG_CHIP_DEVICE_SERIAL_NUMBER +#endif // CONFIG_CHIP_PLAT_LOAD_REAL_FACTORY_DATA +#endif // CONFIG_CHIP_USE_GENERATED_CONFIG + #ifndef CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION #if CONFIG_CHIP_WIFI || CHIP_DEVICE_CONFIG_ENABLE_WPA #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_STATION 1 @@ -39,12 +62,16 @@ #define CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP 0 #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI_AP -#if !CHIP_DEVICE_CONFIG_ENABLE_THREAD -#define CHIP_DEVICE_CONFIG_ENABLE_UNPROVISIONED_MDNS 1 -#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD - #ifndef CHIP_DEVICE_CONFIG_ENABLE_THREAD +#ifdef CONFIG_NET_L2_OPENTHREAD +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD CONFIG_NET_L2_OPENTHREAD +#else #define CHIP_DEVICE_CONFIG_ENABLE_THREAD 0 +#endif // CONFIG_NET_L2_OPENTHREAD +#endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD + +#if !CHIP_DEVICE_CONFIG_ENABLE_THREAD +#define CHIP_DEVICE_CONFIG_ENABLE_UNPROVISIONED_MDNS 1 #endif // CHIP_DEVICE_CONFIG_ENABLE_THREAD #ifndef CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE diff --git a/src/platform/nxp/common/CHIPNXPPlatformDefaultConfig.h b/src/platform/nxp/common/CHIPNXPPlatformDefaultConfig.h index c90619bdddc040..5bbc7ef7c593b1 100644 --- a/src/platform/nxp/common/CHIPNXPPlatformDefaultConfig.h +++ b/src/platform/nxp/common/CHIPNXPPlatformDefaultConfig.h @@ -254,6 +254,15 @@ #define CHIP_CONFIG_RMP_DEFAULT_MAX_RETRANS 10 #endif +/* Increasing the retransmission interval of the MRP messages after subsequent failures */ +#ifndef CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL +#ifdef CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL +#define CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL +#else +#define CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL (2000_ms32) +#endif // CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL +#endif // CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL + #ifndef NXP_USE_MML /* Do not use Memory Manager Light for dynamic memory allocation by default. */ #define NXP_USE_MML 0 From c6d86b333444b1b0ccbb4f133ec54f666b92ad1d Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Thu, 7 Nov 2024 12:41:02 -0500 Subject: [PATCH 090/121] Clean up and unify HSV command handlers of the color control (#36378) * Clean up and unify HSV command handlers of the color control * Replace local variable usage by commandData. * Address comments --- .../color-control-server.cpp | 543 ++++++++---------- .../color-control-server.h | 65 ++- 2 files changed, 266 insertions(+), 342 deletions(-) diff --git a/src/app/clusters/color-control-server/color-control-server.cpp b/src/app/clusters/color-control-server/color-control-server.cpp index 2b7c7aa12a92d1..b43c95c7b23ddb 100644 --- a/src/app/clusters/color-control-server/color-control-server.cpp +++ b/src/app/clusters/color-control-server/color-control-server.cpp @@ -307,8 +307,8 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl { case EnhancedColorMode::kCurrentHueAndCurrentSaturation: #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV - ColorControlServer::Instance().moveToSaturation(static_cast(colorSaturationTransitionState->finalValue), - transitionTime10th, endpoint); + ColorControlServer::Instance().moveToSaturation( + endpoint, static_cast(colorSaturationTransitionState->finalValue), transitionTime10th); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV break; case EnhancedColorMode::kCurrentXAndCurrentY: @@ -326,8 +326,8 @@ class DefaultColorControlSceneHandler : public scenes::DefaultSceneHandlerImpl case EnhancedColorMode::kEnhancedCurrentHueAndCurrentSaturation: #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV ColorControlServer::Instance().moveToHueAndSaturation( - colorHueTransitionState->finalEnhancedHue, static_cast(colorSaturationTransitionState->finalValue), - transitionTime10th, true, endpoint); + endpoint, colorHueTransitionState->finalEnhancedHue, + static_cast(colorSaturationTransitionState->finalValue), transitionTime10th, true); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV break; default: @@ -1258,15 +1258,15 @@ EmberEventControl * ColorControlServer::configureHSVEventControl(EndpointId endp } /** - * @brief executes move to saturation command + * @brief Executes move to saturation command * - * @param saturation target saturation - * @param transitionTime transition time in 10th of seconds - * @param endpoint target endpoint where to execute move - * @return Status::Success if successful,Status::UnsupportedEndpoint if the saturation transition state doesn't exist, - * Status::ConstraintError if the saturation is above maximum + * @param endpoint Target endpoint where to execute move + * @param saturation Target saturation + * @param transitionTime Transition time in 10th of seconds + * @return Status::Success When successful, + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a saturation transition state. */ -Status ColorControlServer::moveToSaturation(uint8_t saturation, uint16_t transitionTime, EndpointId endpoint) +Status ColorControlServer::moveToSaturation(EndpointId endpoint, uint8_t saturation, uint16_t transitionTime) { Color16uTransitionState * colorSaturationTransitionState = getSaturationTransitionState(endpoint); VerifyOrReturnError(nullptr != colorSaturationTransitionState, Status::UnsupportedEndpoint); @@ -1297,19 +1297,19 @@ Status ColorControlServer::moveToSaturation(uint8_t saturation, uint16_t transit } /** - * @brief executes move to hue and saturatioan command + * @brief Executes move to hue and saturatioan command. * - * @param[in] hue target hue - * @param[in] saturation target saturation - * @param[in] transitionTime transition time in 10th of seconds + * @param[in] endpoint EndpointId of the recipient Color control cluster. + * @param[in] hue Target hue. + * @param[in] saturation Target saturation. + * @param[in] transitionTime Transition time in 10th of seconds. * @param[in] isEnhanced If True, function was called by EnhancedMoveHue command and rate is a uint16 value. If False function - * was called by MoveHue command and rate is a uint8 value - * @param[in] endpoint - * @return Status::Success if successful,Status::UnsupportedEndpoint if the saturation transition state doesn't exist, - * Status::ConstraintError if the saturation is above maximum + * was called by MoveHue command and rate is a uint8 value. + * @return Status::Success When successful, + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a saturation transition state, */ -Status ColorControlServer::moveToHueAndSaturation(uint16_t hue, uint8_t saturation, uint16_t transitionTime, bool isEnhanced, - EndpointId endpoint) +Status ColorControlServer::moveToHueAndSaturation(EndpointId endpoint, uint16_t hue, uint8_t saturation, uint16_t transitionTime, + bool isEnhanced) { uint16_t currentHue = 0; uint16_t halfWay = isEnhanced ? HALF_MAX_UINT16T : HALF_MAX_UINT8T; @@ -1386,44 +1386,35 @@ Status ColorControlServer::moveToHueAndSaturation(uint16_t hue, uint8_t saturati } /** - * @brief Executes move Hue Command + * @brief Executes move Hue Command. * - * @param[in] endpoint + * @param[in] endpoint EndpointId of the recipient Color control cluster. * @param[in] moveMode * @param[in] rate * @param[in] optionsMask * @param[in] optionsOverride * @param[in] isEnhanced If True, function was called by EnhancedMoveHue command and rate is a uint16 value. If False function - * was called by MoveHue command and rate is a uint8 value - * @return true Success - * @return false Failed + * was called by MoveHue command and rate is a uint8 value. + * @return Status::Success when successful, + * Status::InvalidCommand when Rate is 0 or an unknown moveMode is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a hue transition state, */ -bool ColorControlServer::moveHueCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - HueMoveMode moveMode, uint16_t rate, BitMask optionsMask, - BitMask optionsOverride, bool isEnhanced) +Status ColorControlServer::moveHueCommand(EndpointId endpoint, HueMoveMode moveMode, uint16_t rate, + BitMask optionsMask, BitMask optionsOverride, + bool isEnhanced) { MATTER_TRACE_SCOPE("moveHue", "ColorControl"); - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - - uint16_t epIndex = getEndpointIndex(endpoint); - ColorHueTransitionState * colorHueTransitionState = getColorHueTransitionStateByIndex(epIndex); - - VerifyOrExit(colorHueTransitionState != nullptr, status = Status::UnsupportedEndpoint); // check moveMode and rate before any operation is done on the transition states // rate value is ignored if the MoveMode is stop - if (moveMode == HueMoveMode::kUnknownEnumValue || (rate == 0 && moveMode != HueMoveMode::kStop)) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } + VerifyOrReturnValue(moveMode != HueMoveMode::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue((rate != 0 || moveMode == HueMoveMode::kStop), Status::InvalidCommand); - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + uint16_t epIndex = getEndpointIndex(endpoint); + ColorHueTransitionState * colorHueTransitionState = getColorHueTransitionStateByIndex(epIndex); + VerifyOrReturnValue(colorHueTransitionState != nullptr, Status::UnsupportedEndpoint); + + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, optionsMask, optionsOverride), Status::Success); // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); @@ -1435,8 +1426,7 @@ bool ColorControlServer::moveHueCommand(app::CommandHandler * commandObj, const // Per spec any saturation transition must also be cancelled. Color16uTransitionState * saturationState = getSaturationTransitionStateByIndex(epIndex); initSaturationTransitionState(endpoint, saturationState); - commandObj->AddStatus(commandPath, Status::Success); - return true; + return Status::Success; } // Handle color mode transition, if necessary. @@ -1488,50 +1478,42 @@ bool ColorControlServer::moveHueCommand(app::CommandHandler * commandObj, const // kick off the state machine: scheduleTimerCallbackMs(configureHSVEventControl(endpoint), TRANSITION_UPDATE_TIME_MS.count()); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } /** - * @brief Executes move to hue command + * @brief Executes move to hue command. * - * @param[in] endpoint + * @param[in] endpoint EndpointId of the recipient Color control cluster. * @param[in] hue - * @param[in] hueMoveMode + * @param[in] moveDirection * @param[in] transitionTime * @param[in] optionsMask * @param[in] optionsOverride * @param[in] isEnhanced If True, function was called by EnhancedMoveHue command and rate is a uint16 value. If False function - * was called by MoveHue command and rate is a uint8 value - * @return true Success - * @return false Failed + * was called by MoveHue command and rate is a uint8 value. + * @return Status::Success when successful, + * Status::InvalidCommand when Rate is 0 or an unknown moveDirection is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a hue transition state, + * Status::ConstraintError when the other parameters are outside their defined value range. */ -bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - uint16_t hue, DirectionEnum moveDirection, uint16_t transitionTime, - BitMask optionsMask, BitMask optionsOverride, - bool isEnhanced) +Status ColorControlServer::moveToHueCommand(EndpointId endpoint, uint16_t hue, DirectionEnum moveDirection, uint16_t transitionTime, + BitMask optionsMask, BitMask optionsOverride, + bool isEnhanced) { MATTER_TRACE_SCOPE("moveToHue", "ColorControl"); - EndpointId endpoint = commandPath.mEndpointId; + VerifyOrReturnValue(moveDirection != DirectionEnum::kUnknownEnumValue, Status::InvalidCommand); - Status status = Status::Success; - uint16_t currentHue = 0; - DirectionEnum direction; + // Command Parameters constraint checks: + VerifyOrReturnValue((isEnhanced || hue <= MAX_HUE_VALUE), Status::ConstraintError); ColorHueTransitionState * colorHueTransitionState = getColorHueTransitionState(endpoint); + VerifyOrReturnValue(colorHueTransitionState != nullptr, Status::UnsupportedEndpoint); - VerifyOrExit(colorHueTransitionState != nullptr, status = Status::UnsupportedEndpoint); - - // Standard Hue limit checking: hue is 0..254. Spec dictates we ignore - // this and report a constraint error. - if (!isEnhanced && (hue > MAX_HUE_VALUE)) - { - commandObj->AddStatus(commandPath, Status::ConstraintError); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, optionsMask, optionsOverride), Status::Success); + uint16_t currentHue = 0; + DirectionEnum direction; if (isEnhanced) { Attributes::EnhancedCurrentHue::Get(endpoint, ¤tHue); @@ -1540,7 +1522,6 @@ bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, cons { uint8_t current8bitHue = 0; Attributes::CurrentHue::Get(endpoint, ¤t8bitHue); - currentHue = static_cast(current8bitHue); } @@ -1574,18 +1555,11 @@ bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, cons direction = moveDirection; break; case DirectionEnum::kUnknownEnumValue: - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; + return Status::InvalidCommand; /* No default case, so if a new direction value gets added we will just fail to compile until we handle it correctly. */ } - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } - // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); @@ -1623,57 +1597,43 @@ bool ColorControlServer::moveToHueCommand(app::CommandHandler * commandObj, cons // kick off the state machine: scheduleTimerCallbackMs(configureHSVEventControl(endpoint), transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } /** - * @brief executes move to hue and saturatioan command - * - * @param[in] commandObj - * @param[in] commandPath + * @brief Executes move to hue and saturatioan command. + * @param[in] endpoint EndpointId of the recipient Color control cluster. * @param[in] hue * @param[in] saturation * @param[in] transitionTime * @param[in] optionsMask * @param[in] optionsOverride * @param[in] isEnhanced If True, function was called by EnhancedMoveHue command and rate is a uint16 value. If False function - * was called by MoveHue command and rate is a uint8 value - * @return true Success - * @return false Failed + * was called by MoveHue command and rate is a uint8 value. + * @return Status::Success when successful, + * Status::ConstraintError when the other parameters are outside their defined value range. + */ -bool ColorControlServer::moveToHueAndSaturationCommand(app::CommandHandler * commandObj, - const app::ConcreteCommandPath & commandPath, uint16_t hue, - uint8_t saturation, uint16_t transitionTime, - BitMask optionsMask, BitMask optionsOverride, - bool isEnhanced) +Status ColorControlServer::moveToHueAndSaturationCommand(EndpointId endpoint, uint16_t hue, uint8_t saturation, + uint16_t transitionTime, BitMask optionsMask, + BitMask optionsOverride, bool isEnhanced) { MATTER_TRACE_SCOPE("moveToHueAndSaturation", "ColorControl"); - // limit checking: hue and saturation are 0..254. Spec dictates we ignore - // this and report a constraint error. - if ((!isEnhanced && hue > MAX_HUE_VALUE) || saturation > MAX_SATURATION_VALUE) - { - commandObj->AddStatus(commandPath, Status::ConstraintError); - return true; - } + // Command Parameters constraint checks: + VerifyOrReturnValue((isEnhanced || hue <= MAX_HUE_VALUE), Status::ConstraintError); + VerifyOrReturnValue(saturation <= MAX_SATURATION_VALUE, Status::ConstraintError); - if (!shouldExecuteIfOff(commandPath.mEndpointId, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } - Status status = moveToHueAndSaturation(hue, saturation, transitionTime, isEnhanced, commandPath.mEndpointId); + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, optionsMask, optionsOverride), Status::Success); + + Status status = moveToHueAndSaturation(endpoint, hue, saturation, transitionTime, isEnhanced); #ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT - ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(commandPath.mEndpointId); + ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); #endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT - commandObj->AddStatus(commandPath, status); - return true; + return status; } /** - * @brief Executes step hue command + * @brief Executes step hue command. * * @param[in] endpoint * @param[in] stepMode @@ -1682,34 +1642,24 @@ bool ColorControlServer::moveToHueAndSaturationCommand(app::CommandHandler * com * @param[in] optionsMask * @param[in] optionsOverride * @param[in] isEnhanced If True, function was called by EnhancedMoveHue command and rate is a uint16 value. If False function - * was called by MoveHue command and rate is a uint8 value - * @return true Success - * @return false Failed + * was called by MoveHue command and rate is a uint8 value. + * @return Status::Success when successful, + * Status::InvalidCommand when StepSize is 0 or an unknown HueStepMode is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a hue transition state. */ -bool ColorControlServer::stepHueCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - HueStepMode stepMode, uint16_t stepSize, uint16_t transitionTime, - BitMask optionsMask, BitMask optionsOverride, bool isEnhanced) +Status ColorControlServer::stepHueCommand(EndpointId endpoint, HueStepMode stepMode, uint16_t stepSize, uint16_t transitionTime, + BitMask optionsMask, BitMask optionsOverride, + bool isEnhanced) { MATTER_TRACE_SCOPE("stepHue", "ColorControl"); - EndpointId endpoint = commandPath.mEndpointId; - - Status status = Status::Success; + // Confirm validity of the step mode and step size received + VerifyOrReturnValue(stepMode != HueStepMode::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue(stepSize != 0, Status::InvalidCommand); ColorHueTransitionState * colorHueTransitionState = getColorHueTransitionState(endpoint); - VerifyOrExit(colorHueTransitionState != nullptr, status = Status::UnsupportedEndpoint); + VerifyOrReturnValue(colorHueTransitionState != nullptr, Status::UnsupportedEndpoint); - // Confirm validity of the step mode and step size received - if (stepMode == HueStepMode::kUnknownEnumValue || stepSize == 0) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } - - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, optionsMask, optionsOverride), Status::Success); // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); @@ -1767,71 +1717,55 @@ bool ColorControlServer::stepHueCommand(app::CommandHandler * commandObj, const // kick off the state machine: scheduleTimerCallbackMs(configureHSVEventControl(endpoint), transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); -exit: - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } -bool ColorControlServer::moveSaturationCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::MoveSaturation::DecodableType & commandData) +/** + * @brief Executes moveSaturation command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command. + * @return Status::Success when successful, + * Status::InvalidCommand when a rate of 0 for a non-stop move or an unknown SaturationMoveMode is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a saturation transition state. + */ +Status ColorControlServer::moveSaturationCommand(EndpointId endpoint, const Commands::MoveSaturation::DecodableType & commandData) { MATTER_TRACE_SCOPE("moveSaturation", "ColorControl"); - auto & moveMode = commandData.moveMode; - auto & rate = commandData.rate; - auto & optionsMask = commandData.optionsMask; - auto & optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - - uint16_t epIndex = getEndpointIndex(endpoint); - Color16uTransitionState * colorSaturationTransitionState = getSaturationTransitionStateByIndex(epIndex); - VerifyOrExit(colorSaturationTransitionState != nullptr, status = Status::UnsupportedEndpoint); - // check moveMode and rate before any operation is done on the transition states // rate value is ignored if the MoveMode is stop - if (moveMode == SaturationMoveMode::kUnknownEnumValue || (rate == 0 && moveMode != SaturationMoveMode::kStop)) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } + VerifyOrReturnValue(commandData.moveMode != SaturationMoveMode::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue(commandData.rate != 0 || commandData.moveMode == SaturationMoveMode::kStop, Status::InvalidCommand); - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } - - uint16_t transitionTime; + uint16_t epIndex = getEndpointIndex(endpoint); + Color16uTransitionState * colorSaturationTransitionState = getSaturationTransitionStateByIndex(epIndex); + VerifyOrReturnValue(colorSaturationTransitionState != nullptr, Status::UnsupportedEndpoint); + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); - // now, kick off the state machine. initSaturationTransitionState(endpoint, colorSaturationTransitionState); - - if (moveMode == SaturationMoveMode::kStop) + if (commandData.moveMode == SaturationMoveMode::kStop) { // Per spec any hue transition must also be cancelled. ColorHueTransitionState * hueState = getColorHueTransitionStateByIndex(epIndex); initHueTransitionState(endpoint, hueState, false /*isEnhancedHue don't care*/); - commandObj->AddStatus(commandPath, Status::Success); - return true; + return Status::Success; } // Handle color mode transition, if necessary. handleModeSwitch(endpoint, EnhancedColorMode::kCurrentHueAndCurrentSaturation); - if (moveMode == SaturationMoveMode::kUp) + if (commandData.moveMode == SaturationMoveMode::kUp) { colorSaturationTransitionState->finalValue = MAX_SATURATION_VALUE; } - else if (moveMode == SaturationMoveMode::kDown) + else if (commandData.moveMode == SaturationMoveMode::kDown) { colorSaturationTransitionState->finalValue = MIN_SATURATION_VALUE; } - transitionTime = computeTransitionTimeFromStateAndRate(colorSaturationTransitionState, rate); - + uint16_t transitionTime = computeTransitionTimeFromStateAndRate(colorSaturationTransitionState, commandData.rate); colorSaturationTransitionState->stepsRemaining = transitionTime; colorSaturationTransitionState->stepsTotal = transitionTime; colorSaturationTransitionState->timeRemaining = transitionTime; @@ -1844,97 +1778,72 @@ bool ColorControlServer::moveSaturationCommand(app::CommandHandler * commandObj, // kick off the state machine: scheduleTimerCallbackMs(configureHSVEventControl(endpoint), TRANSITION_UPDATE_TIME_MS.count()); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } /** - * @brief executes move to saturation command - * - * @param commandObj - * @param commandPath - * @param commandData - * @return true - * @return false + * @brief Executes move to saturation command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command. + * @return Status::Success when successful, + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a saturation transition state (verified in + * moveToSaturation function) Status::ConstraintError when a command parameters is outside its defined value range. */ -bool ColorControlServer::moveToSaturationCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::MoveToSaturation::DecodableType & commandData) +Status ColorControlServer::moveToSaturationCommand(EndpointId endpoint, + const Commands::MoveToSaturation::DecodableType & commandData) { MATTER_TRACE_SCOPE("moveToSaturation", "ColorControl"); - // limit checking: saturation is 0..254. Spec dictates we ignore - // this and report a malformed packet. - if (commandData.saturation > MAX_SATURATION_VALUE) - { - commandObj->AddStatus(commandPath, Status::ConstraintError); - return true; - } + // Command Parameters constraint checks: + VerifyOrReturnValue(commandData.saturation <= MAX_SATURATION_VALUE, Status::ConstraintError); - if (!shouldExecuteIfOff(commandPath.mEndpointId, commandData.optionsMask, commandData.optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } - Status status = moveToSaturation(commandData.saturation, commandData.transitionTime, commandPath.mEndpointId); + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); + Status status = moveToSaturation(endpoint, commandData.saturation, commandData.transitionTime); #ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT - ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(commandPath.mEndpointId); + ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); #endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT - commandObj->AddStatus(commandPath, status); - return true; + return status; } -bool ColorControlServer::stepSaturationCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::StepSaturation::DecodableType & commandData) +/** + * @brief Executes step saturation command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command. + * @return Status::Success when successful, + * Status::InvalidCommand when a step size of 0 or an unknown SaturationStepMode is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a saturation transition state. + */ +Status ColorControlServer::stepSaturationCommand(EndpointId endpoint, const Commands::StepSaturation::DecodableType & commandData) { MATTER_TRACE_SCOPE("stepSaturation", "ColorControl"); - auto stepMode = commandData.stepMode; - uint8_t stepSize = commandData.stepSize; - uint8_t transitionTime = commandData.transitionTime; - BitMask optionsMask = commandData.optionsMask; - BitMask optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint8_t currentSaturation = 0; + // Confirm validity of the step mode and step size received + VerifyOrReturnValue(commandData.stepMode != SaturationStepMode::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue(commandData.stepSize != 0, Status::InvalidCommand); Color16uTransitionState * colorSaturationTransitionState = getSaturationTransitionState(endpoint); - VerifyOrExit(colorSaturationTransitionState != nullptr, status = Status::UnsupportedEndpoint); - - // Confirm validity of the step mode and step size received - if (stepMode == SaturationStepMode::kUnknownEnumValue || stepSize == 0) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } + VerifyOrReturnValue(colorSaturationTransitionState != nullptr, Status::UnsupportedEndpoint); - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); - // Handle color mode transition, if necessary. handleModeSwitch(endpoint, EnhancedColorMode::kCurrentHueAndCurrentSaturation); - // now, kick off the state machine. initSaturationTransitionState(endpoint, colorSaturationTransitionState); - currentSaturation = static_cast(colorSaturationTransitionState->currentValue); + uint8_t currentSaturation = static_cast(colorSaturationTransitionState->currentValue); - if (stepMode == SaturationStepMode::kUp) + if (commandData.stepMode == SaturationStepMode::kUp) { - colorSaturationTransitionState->finalValue = addSaturation(currentSaturation, stepSize); + colorSaturationTransitionState->finalValue = addSaturation(currentSaturation, commandData.stepSize); } - else if (stepMode == SaturationStepMode::kDown) + else if (commandData.stepMode == SaturationStepMode::kDown) { - colorSaturationTransitionState->finalValue = subtractSaturation(currentSaturation, stepSize); + colorSaturationTransitionState->finalValue = subtractSaturation(currentSaturation, commandData.stepSize); } - colorSaturationTransitionState->stepsRemaining = std::max(transitionTime, 1); + colorSaturationTransitionState->stepsRemaining = std::max(commandData.transitionTime, 1); colorSaturationTransitionState->stepsTotal = colorSaturationTransitionState->stepsRemaining; - colorSaturationTransitionState->timeRemaining = transitionTime; - colorSaturationTransitionState->transitionTime = transitionTime; + colorSaturationTransitionState->timeRemaining = commandData.transitionTime; + colorSaturationTransitionState->transitionTime = commandData.transitionTime; colorSaturationTransitionState->endpoint = endpoint; colorSaturationTransitionState->lowLimit = MIN_SATURATION_VALUE; colorSaturationTransitionState->highLimit = MAX_SATURATION_VALUE; @@ -1942,65 +1851,52 @@ bool ColorControlServer::stepSaturationCommand(app::CommandHandler * commandObj, SetHSVRemainingTime(endpoint); // kick off the state machine: - scheduleTimerCallbackMs(configureHSVEventControl(endpoint), transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + scheduleTimerCallbackMs(configureHSVEventControl(endpoint), commandData.transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); + return Status::Success; } -bool ColorControlServer::colorLoopCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::ColorLoopSet::DecodableType & commandData) +/** + * @brief Executes ColorLoop command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command. + * @return Status::Success when successful, + * Status::InvalidCommand when an unknown action or direction is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a hue transition state. + */ +Status ColorControlServer::colorLoopCommand(EndpointId endpoint, const Commands::ColorLoopSet::DecodableType & commandData) { MATTER_TRACE_SCOPE("colorLoop", "ColorControl"); - auto updateFlags = commandData.updateFlags; - auto action = commandData.action; - auto direction = commandData.direction; - uint16_t time = commandData.time; - uint16_t startHue = commandData.startHue; - BitMask optionsMask = commandData.optionsMask; - BitMask optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint8_t isColorLoopActive = 0; - uint8_t deactiveColorLoop = 0; + // Validate the action and direction parameters of the command + VerifyOrReturnValue(commandData.action != ColorLoopActionEnum::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue(commandData.direction != ColorLoopDirectionEnum::kUnknownEnumValue, Status::InvalidCommand); uint16_t epIndex = getEndpointIndex(endpoint); ColorHueTransitionState * colorHueTransitionState = getColorHueTransitionStateByIndex(epIndex); - VerifyOrExit(colorHueTransitionState != nullptr, status = Status::UnsupportedEndpoint); + VerifyOrReturnValue(colorHueTransitionState != nullptr, Status::UnsupportedEndpoint); - // Validate the action and direction parameters of the command - if (action == ColorLoopActionEnum::kUnknownEnumValue || direction == ColorLoopDirectionEnum::kUnknownEnumValue) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } - - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); + uint8_t isColorLoopActive = 0; // In case of get failure, isColorLoopActive will remain at the init value 0 (not active) if (Attributes::ColorLoopActive::Get(endpoint, &isColorLoopActive) != Status::Success) { ChipLogError(Zcl, "Failed to retrieve ColorLoopActive value"); } - deactiveColorLoop = updateFlags.Has(ColorLoopUpdateFlags::kUpdateAction) && (action == ColorLoopAction::kDeactivate); + uint8_t deactiveColorLoop = + commandData.updateFlags.Has(ColorLoopUpdateFlags::kUpdateAction) && (commandData.action == ColorLoopAction::kDeactivate); - if (updateFlags.Has(ColorLoopUpdateFlags::kUpdateDirection)) + if (commandData.updateFlags.Has(ColorLoopUpdateFlags::kUpdateDirection)) { - Attributes::ColorLoopDirection::Set(endpoint, to_underlying(direction)); + Attributes::ColorLoopDirection::Set(endpoint, to_underlying(commandData.direction)); // Checks if color loop is active and stays active if (isColorLoopActive && !deactiveColorLoop) { - colorHueTransitionState->up = (direction == ColorLoopDirectionEnum::kIncrement); + colorHueTransitionState->up = (commandData.direction == ColorLoopDirectionEnum::kIncrement); colorHueTransitionState->initialEnhancedHue = colorHueTransitionState->currentEnhancedHue; - if (direction == ColorLoopDirectionEnum::kIncrement) + if (commandData.direction == ColorLoopDirectionEnum::kIncrement) { colorHueTransitionState->finalEnhancedHue = static_cast(colorHueTransitionState->initialEnhancedHue - 1); } @@ -2012,14 +1908,14 @@ bool ColorControlServer::colorLoopCommand(app::CommandHandler * commandObj, cons } } - if (updateFlags.Has(ColorLoopUpdateFlags::kUpdateTime)) + if (commandData.updateFlags.Has(ColorLoopUpdateFlags::kUpdateTime)) { - Attributes::ColorLoopTime::Set(endpoint, time); + Attributes::ColorLoopTime::Set(endpoint, commandData.time); // Checks if color loop is active and stays active if (isColorLoopActive && !deactiveColorLoop) { - colorHueTransitionState->stepsTotal = static_cast(time * TRANSITION_STEPS_PER_1S); + colorHueTransitionState->stepsTotal = static_cast(commandData.time * TRANSITION_STEPS_PER_1S); colorHueTransitionState->initialEnhancedHue = colorHueTransitionState->currentEnhancedHue; if (colorHueTransitionState->up) @@ -2034,14 +1930,14 @@ bool ColorControlServer::colorLoopCommand(app::CommandHandler * commandObj, cons } } - if (updateFlags.Has(ColorLoopUpdateFlags::kUpdateStartHue)) + if (commandData.updateFlags.Has(ColorLoopUpdateFlags::kUpdateStartHue)) { - Attributes::ColorLoopStartEnhancedHue::Set(endpoint, startHue); + Attributes::ColorLoopStartEnhancedHue::Set(endpoint, commandData.startHue); } - if (updateFlags.Has(ColorLoopUpdateFlags::kUpdateAction)) + if (commandData.updateFlags.Has(ColorLoopUpdateFlags::kUpdateAction)) { - if (action == ColorLoopAction::kDeactivate) + if (commandData.action == ColorLoopAction::kDeactivate) { if (isColorLoopActive) { @@ -2060,26 +1956,24 @@ bool ColorControlServer::colorLoopCommand(app::CommandHandler * commandObj, cons // Do Nothing since it's not on } } - else if (action == ColorLoopAction::kActivateFromColorLoopStartEnhancedHue) + else if (commandData.action == ColorLoopAction::kActivateFromColorLoopStartEnhancedHue) { startColorLoop(endpoint, true); } - else if (action == ColorLoopAction::kActivateFromEnhancedCurrentHue) + else if (commandData.action == ColorLoopAction::kActivateFromEnhancedCurrentHue) { startColorLoop(endpoint, false); } } -exit: #ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); #endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } /** - * @brief updates Hue and saturation after timer is finished + * @brief Updates Hue and saturation after timer is finished. * * @param endpoint */ @@ -3175,96 +3069,119 @@ Status ColorControlServer::SetQuietReportRemainingTime(EndpointId endpoint, uint bool emberAfColorControlClusterMoveHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveHue::DecodableType & commandData) { - return ColorControlServer::Instance().moveHueCommand(commandObj, commandPath, commandData.moveMode, commandData.rate, - commandData.optionsMask, commandData.optionsOverride, false); + Status status = ColorControlServer::Instance().moveHueCommand(commandPath.mEndpointId, commandData.moveMode, commandData.rate, + commandData.optionsMask, commandData.optionsOverride, false); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterMoveSaturationCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveSaturation::DecodableType & commandData) { - - return ColorControlServer::Instance().moveSaturationCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().moveSaturationCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterMoveToHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveToHue::DecodableType & commandData) { - return ColorControlServer::Instance().moveToHueCommand(commandObj, commandPath, commandData.hue, commandData.direction, - commandData.transitionTime, commandData.optionsMask, - commandData.optionsOverride, false); + Status status = ColorControlServer::Instance().moveToHueCommand(commandPath.mEndpointId, commandData.hue, commandData.direction, + commandData.transitionTime, commandData.optionsMask, + commandData.optionsOverride, false); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterMoveToSaturationCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveToSaturation::DecodableType & commandData) { - return ColorControlServer::Instance().moveToSaturationCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().moveToSaturationCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterMoveToHueAndSaturationCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveToHueAndSaturation::DecodableType & commandData) { - return ColorControlServer::Instance().moveToHueAndSaturationCommand( - commandObj, commandPath, commandData.hue, commandData.saturation, commandData.transitionTime, commandData.optionsMask, + Status status = ColorControlServer::Instance().moveToHueAndSaturationCommand( + commandPath.mEndpointId, commandData.hue, commandData.saturation, commandData.transitionTime, commandData.optionsMask, commandData.optionsOverride, false); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterStepHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::StepHue::DecodableType & commandData) { - return ColorControlServer::Instance().stepHueCommand(commandObj, commandPath, commandData.stepMode, commandData.stepSize, - commandData.transitionTime, commandData.optionsMask, - commandData.optionsOverride, false); + Status status = ColorControlServer::Instance().stepHueCommand(commandPath.mEndpointId, commandData.stepMode, + commandData.stepSize, commandData.transitionTime, + commandData.optionsMask, commandData.optionsOverride, false); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterStepSaturationCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::StepSaturation::DecodableType & commandData) { - return ColorControlServer::Instance().stepSaturationCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().stepSaturationCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterEnhancedMoveHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::EnhancedMoveHue::DecodableType & commandData) { - return ColorControlServer::Instance().moveHueCommand(commandObj, commandPath, commandData.moveMode, commandData.rate, - commandData.optionsMask, commandData.optionsOverride, true); + Status status = ColorControlServer::Instance().moveHueCommand(commandPath.mEndpointId, commandData.moveMode, commandData.rate, + commandData.optionsMask, commandData.optionsOverride, true); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterEnhancedMoveToHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::EnhancedMoveToHue::DecodableType & commandData) { - return ColorControlServer::Instance().moveToHueCommand(commandObj, commandPath, commandData.enhancedHue, commandData.direction, - commandData.transitionTime, commandData.optionsMask, - commandData.optionsOverride, true); + Status status = ColorControlServer::Instance().moveToHueCommand(commandPath.mEndpointId, commandData.enhancedHue, + commandData.direction, commandData.transitionTime, + commandData.optionsMask, commandData.optionsOverride, true); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterEnhancedMoveToHueAndSaturationCallback( app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::EnhancedMoveToHueAndSaturation::DecodableType & commandData) { - return ColorControlServer::Instance().moveToHueAndSaturationCommand(commandObj, commandPath, commandData.enhancedHue, - commandData.saturation, commandData.transitionTime, - commandData.optionsMask, commandData.optionsOverride, true); + Status status = ColorControlServer::Instance().moveToHueAndSaturationCommand( + commandPath.mEndpointId, commandData.enhancedHue, commandData.saturation, commandData.transitionTime, + commandData.optionsMask, commandData.optionsOverride, true); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterEnhancedStepHueCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::EnhancedStepHue::DecodableType & commandData) { - return ColorControlServer::Instance().stepHueCommand(commandObj, commandPath, commandData.stepMode, commandData.stepSize, - commandData.transitionTime, commandData.optionsMask, - commandData.optionsOverride, true); + Status status = ColorControlServer::Instance().stepHueCommand(commandPath.mEndpointId, commandData.stepMode, + commandData.stepSize, commandData.transitionTime, + commandData.optionsMask, commandData.optionsOverride, true); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterColorLoopSetCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::ColorLoopSet::DecodableType & commandData) { - return ColorControlServer::Instance().colorLoopCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().colorLoopCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV diff --git a/src/app/clusters/color-control-server/color-control-server.h b/src/app/clusters/color-control-server/color-control-server.h index aab7c270d14858..210df4c16635f0 100644 --- a/src/app/clusters/color-control-server/color-control-server.h +++ b/src/app/clusters/color-control-server/color-control-server.h @@ -148,31 +148,38 @@ class ColorControlServer const chip::app::Clusters::ColorControl::Commands::StopMoveStep::DecodableType & commandData); #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV - bool moveHueCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - MoveModeEnum moveMode, uint16_t rate, - chip::BitMask optionsMask, - chip::BitMask optionsOverride, bool isEnhanced); - bool moveToHueCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, uint16_t hue, - DirectionEnum moveDirection, uint16_t transitionTime, - chip::BitMask optionsMask, - chip::BitMask optionsOverride, bool isEnhanced); - bool moveToHueAndSaturationCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - uint16_t hue, uint8_t saturation, uint16_t transitionTime, - chip::BitMask optionsMask, - chip::BitMask optionsOverride, - bool isEnhanced); - bool stepHueCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - StepModeEnum stepMode, uint16_t stepSize, uint16_t transitionTime, - chip::BitMask optionsMask, - chip::BitMask optionsOverride, bool isEnhanced); - bool moveSaturationCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::MoveSaturation::DecodableType & commandData); - bool moveToSaturationCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::MoveToSaturation::DecodableType & commandData); - bool stepSaturationCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::StepSaturation::DecodableType & commandData); - bool colorLoopCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::ColorLoopSet::DecodableType & commandData); + // The Command's DecodableType are not used to pass arguments in the following HSV handlers, + // as they handle both standard and Enhanced HSV commands. + // The command arguments are decoupled in the command callback. + chip::Protocols::InteractionModel::Status + moveHueCommand(const chip::EndpointId endpoint, MoveModeEnum moveMode, uint16_t rate, + chip::BitMask optionsMask, + chip::BitMask optionsOverride, bool isEnhanced); + chip::Protocols::InteractionModel::Status + moveToHueCommand(const chip::EndpointId endpoint, uint16_t hue, DirectionEnum moveDirection, uint16_t transitionTime, + chip::BitMask optionsMask, + chip::BitMask optionsOverride, bool isEnhanced); + chip::Protocols::InteractionModel::Status + moveToHueAndSaturationCommand(const chip::EndpointId endpoint, uint16_t hue, uint8_t saturation, uint16_t transitionTime, + chip::BitMask optionsMask, + chip::BitMask optionsOverride, bool isEnhanced); + chip::Protocols::InteractionModel::Status + stepHueCommand(const chip::EndpointId endpoint, StepModeEnum stepMode, uint16_t stepSize, uint16_t transitionTime, + chip::BitMask optionsMask, + chip::BitMask optionsOverride, bool isEnhanced); + + chip::Protocols::InteractionModel::Status + moveSaturationCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::MoveSaturation::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + moveToSaturationCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::MoveToSaturation::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + stepSaturationCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::StepSaturation::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + colorLoopCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::ColorLoopSet::DecodableType & commandData); void updateHueSatCommand(chip::EndpointId endpoint); #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV @@ -234,10 +241,10 @@ class ColorControlServer uint16_t getEndpointIndex(chip::EndpointId); #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_HSV - chip::Protocols::InteractionModel::Status moveToSaturation(uint8_t saturation, uint16_t transitionTime, - chip::EndpointId endpoint); - chip::Protocols::InteractionModel::Status moveToHueAndSaturation(uint16_t hue, uint8_t saturation, uint16_t transitionTime, - bool isEnhanced, chip::EndpointId endpoint); + chip::Protocols::InteractionModel::Status moveToSaturation(chip::EndpointId endpoint, uint8_t saturation, + uint16_t transitionTime); + chip::Protocols::InteractionModel::Status moveToHueAndSaturation(chip::EndpointId endpoint, uint16_t hue, uint8_t saturation, + uint16_t transitionTime, bool isEnhanced); ColorHueTransitionState * getColorHueTransitionState(chip::EndpointId endpoint); Color16uTransitionState * getSaturationTransitionState(chip::EndpointId endpoint); ColorHueTransitionState * getColorHueTransitionStateByIndex(uint16_t index); From 097b47715136d6465fe5930486dbc0c9faa76e54 Mon Sep 17 00:00:00 2001 From: Dmytro Huz <75682372+interfer@users.noreply.github.com> Date: Thu, 7 Nov 2024 19:59:30 +0200 Subject: [PATCH 091/121] [Telink] build info log prints (#36371) Added prints of git info for Matter, Zephyr and HAL repos for all Telink apps --- config/telink/chip-module/CMakeLists.txt | 4 + examples/platform/telink/build_info.cmake | 148 ++++++++++++++++++ .../telink/common/include/AppTaskCommon.h | 1 + .../telink/common/src/AppTaskCommon.cpp | 19 ++- 4 files changed, 171 insertions(+), 1 deletion(-) create mode 100644 examples/platform/telink/build_info.cmake diff --git a/config/telink/chip-module/CMakeLists.txt b/config/telink/chip-module/CMakeLists.txt index 1b148476f3e0d8..ade2bd310f8a02 100644 --- a/config/telink/chip-module/CMakeLists.txt +++ b/config/telink/chip-module/CMakeLists.txt @@ -155,6 +155,10 @@ set_property(GLOBAL APPEND PROPERTY ZEPHYR_INTERFACE_LIBS chip) include(${TELINK_COMMON}/common.cmake) +if (CONFIG_CHIP_APP_LOG_LEVEL GREATER_EQUAL 4) + include(${TELINK_COMMON}/build_info.cmake) +endif() + # ============================================================================== # Define 'process_binaries' target for collecting final binary to flash # ============================================================================== diff --git a/examples/platform/telink/build_info.cmake b/examples/platform/telink/build_info.cmake new file mode 100644 index 00000000000000..f6a7ccfaee34f3 --- /dev/null +++ b/examples/platform/telink/build_info.cmake @@ -0,0 +1,148 @@ +# +# Copyright (c) 2024 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. + +# Matter git info +execute_process( + COMMAND git rev-parse HEAD + OUTPUT_VARIABLE MATTER_COMMIT_HASH + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git diff --quiet + RESULT_VARIABLE MATTER_LOCAL_STATUS +) + +if(MATTER_LOCAL_STATUS) + set(MATTER_LOCAL_STATUS "-dirty") +else() + set(MATTER_LOCAL_STATUS "") +endif() + +execute_process( + COMMAND git rev-parse --abbrev-ref HEAD + OUTPUT_VARIABLE MATTER_BRANCH_NAME + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND python3 -c "from datetime import datetime; print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))" + OUTPUT_VARIABLE BUILD_TIMESTAMP + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git show -s --format=%cd --date=format:%Y-%m-%d + OUTPUT_VARIABLE MATTER_COMMIT_DATE + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git remote get-url origin + OUTPUT_VARIABLE MATTER_REMOTE_URL + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +# Zephyr git info +execute_process( + COMMAND git -C ${ZEPHYR_BASE} rev-parse HEAD + OUTPUT_VARIABLE ZEPHYR_COMMIT_HASH + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git -C ${ZEPHYR_BASE} rev-parse --abbrev-ref HEAD + OUTPUT_VARIABLE ZEPHYR_BRANCH_NAME + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git -C ${ZEPHYR_BASE} show -s --format=%cd --date=format:%Y-%m-%d HEAD + OUTPUT_VARIABLE ZEPHYR_COMMIT_DATE + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND bash -c "git -C ${ZEPHYR_BASE} remote get-url \$(git -C ${ZEPHYR_BASE} remote | head -n 1)" + OUTPUT_VARIABLE ZEPHYR_REMOTE_URL + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git -C ${ZEPHYR_BASE} diff --quiet + RESULT_VARIABLE ZEPHYR_LOCAL_STATUS +) + +if(ZEPHYR_LOCAL_STATUS) + set(ZEPHYR_LOCAL_STATUS "-dirty") +else() + set(ZEPHYR_LOCAL_STATUS "") +endif() + +# Telink HAL info +execute_process( + COMMAND git -C ${ZEPHYR_BASE}/../modules/hal/telink rev-parse HEAD + OUTPUT_VARIABLE TELINK_HAL_COMMIT_HASH + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +execute_process( + COMMAND git -C ${ZEPHYR_BASE}/../modules/hal/telink diff --quiet + RESULT_VARIABLE HAL_LOCAL_STATUS +) + +if(TELINK_HAL_LOCAL_STATUS) + set(TELINK_HAL_LOCAL_STATUS "-dirty") +else() + set(TELINK_HAL_LOCAL_STATUS "") +endif() + +execute_process( + COMMAND git -C ${ZEPHYR_BASE}/../modules/hal/telink show -s --format=%cd --date=format:%Y-%m-%d + OUTPUT_VARIABLE TELINK_HAL_COMMIT_DATE + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +target_compile_definitions(app PRIVATE + MATTER_COMMIT_HASH="${MATTER_COMMIT_HASH}" + MATTER_BRANCH="${MATTER_BRANCH_NAME}" + BUILD_TIMESTAMP="${BUILD_TIMESTAMP}" + MATTER_COMMIT_DATE="${MATTER_COMMIT_DATE}" + MATTER_REMOTE_URL="${MATTER_REMOTE_URL}" + MATTER_LOCAL_STATUS="${MATTER_LOCAL_STATUS}" + + ZEPHYR_COMMIT_HASH="${ZEPHYR_COMMIT_HASH}" + ZEPHYR_BRANCH="${ZEPHYR_BRANCH_NAME}" + ZEPHYR_COMMIT_DATE="${ZEPHYR_COMMIT_DATE}" + ZEPHYR_REMOTE_URL="${ZEPHYR_REMOTE_URL}" + ZEPHYR_LOCAL_STATUS="${ZEPHYR_LOCAL_STATUS}" + + TELINK_HAL_COMMIT_HASH="${TELINK_HAL_COMMIT_HASH}" + TELINK_HAL_LOCAL_STATUS="${TELINK_HAL_LOCAL_STATUS}" + TELINK_HAL_COMMIT_DATE="${TELINK_HAL_COMMIT_DATE}" +) + +message(STATUS "Matter revision:") +message(STATUS " board: ${CONFIG_BOARD}") +message(STATUS " branch: ${MATTER_BRANCH_NAME} ${MATTER_COMMIT_HASH} ${MATTER_COMMIT_DATE}") +message(STATUS " remote: ${MATTER_REMOTE_URL}") +message(STATUS " build timestamp: ${BUILD_TIMESTAMP}") + +message(STATUS "Zephyr revision:") +message(STATUS " branch: ${ZEPHYR_BRANCH_NAME} ${ZEPHYR_COMMIT_HASH} ${ZEPHYR_COMMIT_DATE}") +message(STATUS " remote: ${ZEPHYR_REMOTE_URL}") + +message(STATUS "HAL revision:") +message(STATUS " commit: ${TELINK_HAL_COMMIT_HASH} ${TELINK_HAL_COMMIT_DATE}") diff --git a/examples/platform/telink/common/include/AppTaskCommon.h b/examples/platform/telink/common/include/AppTaskCommon.h index 22c5f51a937dcc..ac10ef587d2be9 100644 --- a/examples/platform/telink/common/include/AppTaskCommon.h +++ b/examples/platform/telink/common/include/AppTaskCommon.h @@ -84,6 +84,7 @@ class AppTaskCommon protected: CHIP_ERROR InitCommonParts(void); + void PrintFirmwareInfo(void); void DispatchEvent(AppEvent * event); void GetEvent(AppEvent * aEvent); diff --git a/examples/platform/telink/common/src/AppTaskCommon.cpp b/examples/platform/telink/common/src/AppTaskCommon.cpp index 858334aaa72dd7..de5faa974a4847 100644 --- a/examples/platform/telink/common/src/AppTaskCommon.cpp +++ b/examples/platform/telink/common/src/AppTaskCommon.cpp @@ -240,11 +240,28 @@ CHIP_ERROR AppTaskCommon::StartApp(void) DispatchEvent(&event); } } +void AppTaskCommon::PrintFirmwareInfo(void) +{ + LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); +#if CONFIG_CHIP_APP_LOG_LEVEL > 3 + LOG_DBG("Matter revision: "); + LOG_DBG("\t board: %s", CONFIG_BOARD); + LOG_DBG("\t branch: %s %.8s%s %s", MATTER_BRANCH, MATTER_COMMIT_HASH, MATTER_LOCAL_STATUS, MATTER_COMMIT_DATE); + LOG_DBG("\t remote: %s", MATTER_REMOTE_URL); + LOG_DBG("\t build timestamp: %s", BUILD_TIMESTAMP); + + LOG_DBG("Zephyr revision: "); + LOG_DBG("\t branch: %s %.8s%s %s", ZEPHYR_BRANCH, ZEPHYR_COMMIT_HASH, ZEPHYR_LOCAL_STATUS, ZEPHYR_COMMIT_DATE); + LOG_DBG("\t remote: %s", ZEPHYR_REMOTE_URL); + LOG_DBG("\t HAL commit: %.8s%s %s", TELINK_HAL_COMMIT_HASH, TELINK_HAL_LOCAL_STATUS, TELINK_HAL_COMMIT_DATE); +#endif +} CHIP_ERROR AppTaskCommon::InitCommonParts(void) { CHIP_ERROR err; - LOG_INF("SW Version: %u, %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION, CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING); + + PrintFirmwareInfo(); InitLeds(); UpdateStatusLED(); From 2a268411916e86fd91f2ecccccd80e78d20b995e Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Thu, 7 Nov 2024 13:04:13 -0500 Subject: [PATCH 092/121] Clean up and unify ColorTemp command handlers of the color control (#36377) * Clean up and unify ColorTemp command handlers of the color control * Fix tien build by updating api call * Replace auto by type * Replace local variable usage by commandData. * Address comments --- .../lighting-app/tizen/src/DBusInterface.cpp | 3 +- .../color-control-server.cpp | 187 ++++++++---------- .../color-control-server.h | 14 +- 3 files changed, 92 insertions(+), 112 deletions(-) diff --git a/examples/lighting-app/tizen/src/DBusInterface.cpp b/examples/lighting-app/tizen/src/DBusInterface.cpp index 5484c7daff3793..4a2aa18122c39c 100644 --- a/examples/lighting-app/tizen/src/DBusInterface.cpp +++ b/examples/lighting-app/tizen/src/DBusInterface.cpp @@ -203,7 +203,8 @@ gboolean DBusInterface::OnColorTemperatureChanged(LightAppColorControl * colorCo data.colorTemperatureMireds = light_app_color_control_get_color_temperature_mireds(colorControl); chip::DeviceLayer::StackLock lock; - ColorControlServer::Instance().moveToColorTempCommand(&handler, path, data); + auto status = ColorControlServer::Instance().moveToColorTempCommand(self->mEndpointId, data); + handler.AddStatus(path, status); return G_DBUS_METHOD_INVOCATION_HANDLED; } diff --git a/src/app/clusters/color-control-server/color-control-server.cpp b/src/app/clusters/color-control-server/color-control-server.cpp index b43c95c7b23ddb..a01de7fad22dcb 100644 --- a/src/app/clusters/color-control-server/color-control-server.cpp +++ b/src/app/clusters/color-control-server/color-control-server.cpp @@ -2431,12 +2431,12 @@ ColorControlServer::Color16uTransitionState * ColorControlServer::getTempTransit } /** - * @brief executes move to color temp logic + * @brief Executes move to color temp logic. * * @param aEndpoint * @param colorTemperature * @param transitionTime - * @return Status::Success if successful, Status::UnsupportedEndpoint if the endpoint doesn't support color temperature + * @return Status::Success if successful, Status::UnsupportedEndpoint if the endpoint doesn't support color temperature. */ Status ColorControlServer::moveToColorTemp(EndpointId aEndpoint, uint16_t colorTemperature, uint16_t transitionTime) { @@ -2632,49 +2632,28 @@ void ColorControlServer::updateTempCommand(EndpointId endpoint) } /** - * @brief move color temp command - * - * @param moveMode - * @param rate - * @param colorTemperatureMinimum - * @param colorTemperatureMaximum - * @param optionsMask - * @param optionsOverride - * @return true - * @return false + * @brief Executes move color temp command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command. + * @return Status::Success when successful, + * Status::InvalidCommand when a rate of 0 for a non-stop move or an unknown HueMoveMode is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a color temp transition state. */ -bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::MoveColorTemperature::DecodableType & commandData) -{ - auto moveMode = commandData.moveMode; - uint16_t rate = commandData.rate; - uint16_t colorTemperatureMinimum = commandData.colorTemperatureMinimumMireds; - uint16_t colorTemperatureMaximum = commandData.colorTemperatureMaximumMireds; - BitMask optionsMask = commandData.optionsMask; - BitMask optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint16_t tempPhysicalMin = MIN_TEMPERATURE_VALUE; - uint16_t tempPhysicalMax = MAX_TEMPERATURE_VALUE; - uint16_t transitionTime; - - Color16uTransitionState * colorTempTransitionState = getTempTransitionState(endpoint); - VerifyOrExit(colorTempTransitionState != nullptr, status = Status::UnsupportedEndpoint); - +Status ColorControlServer::moveColorTempCommand(EndpointId endpoint, + const Commands::MoveColorTemperature::DecodableType & commandData) +{ // check moveMode and rate before any operation is done on the transition states // rate value is ignored if the MoveMode is stop - if (moveMode == HueMoveMode::kUnknownEnumValue || (rate == 0 && moveMode != HueMoveMode::kStop)) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } + VerifyOrReturnValue(commandData.moveMode != HueMoveMode::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue((commandData.rate != 0 || commandData.moveMode == HueMoveMode::kStop), Status::InvalidCommand); - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + Color16uTransitionState * colorTempTransitionState = getTempTransitionState(endpoint); + VerifyOrReturnValue(colorTempTransitionState != nullptr, Status::UnsupportedEndpoint); + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); + + uint16_t tempPhysicalMin = MIN_TEMPERATURE_VALUE; + uint16_t tempPhysicalMax = MAX_TEMPERATURE_VALUE; Attributes::ColorTempPhysicalMinMireds::Get(endpoint, &tempPhysicalMin); Attributes::ColorTempPhysicalMaxMireds::Get(endpoint, &tempPhysicalMax); @@ -2683,15 +2662,12 @@ bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); - - if (moveMode == HueMoveMode::kStop) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + // For HueMoveMode::kStop we are done here. + VerifyOrReturnValue(commandData.moveMode != HueMoveMode::kStop, Status::Success); // Per spec, colorTemperatureMinimumMireds field is limited to ColorTempPhysicalMinMireds and // when colorTemperatureMinimumMireds field is 0, ColorTempPhysicalMinMireds shall be used (always > 0) + uint16_t colorTemperatureMinimum = commandData.colorTemperatureMinimumMireds; if (colorTemperatureMinimum < tempPhysicalMin) { colorTemperatureMinimum = tempPhysicalMin; @@ -2699,6 +2675,7 @@ bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, // Per spec, colorTemperatureMaximumMireds field is limited to ColorTempPhysicalMaxMireds and // when colorTemperatureMaximumMireds field is 0, ColorTempPhysicalMaxMireds shall be used + uint16_t colorTemperatureMaximum = commandData.colorTemperatureMaximumMireds; if ((colorTemperatureMaximum == 0) || (colorTemperatureMaximum > tempPhysicalMax)) { colorTemperatureMaximum = tempPhysicalMax; @@ -2712,7 +2689,7 @@ bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, Attributes::ColorTemperatureMireds::Get(endpoint, &colorTempTransitionState->initialValue); colorTempTransitionState->currentValue = colorTempTransitionState->initialValue; - if (moveMode == HueMoveMode::kUp) + if (commandData.moveMode == HueMoveMode::kUp) { if (tempPhysicalMax > colorTemperatureMaximum) { @@ -2734,7 +2711,8 @@ bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, colorTempTransitionState->finalValue = tempPhysicalMin; } } - transitionTime = computeTransitionTimeFromStateAndRate(colorTempTransitionState, rate); + + uint16_t transitionTime = computeTransitionTimeFromStateAndRate(colorTempTransitionState, commandData.rate); colorTempTransitionState->stepsRemaining = transitionTime; colorTempTransitionState->stepsTotal = transitionTime; colorTempTransitionState->timeRemaining = transitionTime; @@ -2747,63 +2725,54 @@ bool ColorControlServer::moveColorTempCommand(app::CommandHandler * commandObj, // kick off the state machine: scheduleTimerCallbackMs(configureTempEventControl(endpoint), TRANSITION_UPDATE_TIME_MS.count()); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + return Status::Success; } -bool ColorControlServer::moveToColorTempCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::MoveToColorTemperature::DecodableType & commandData) +/** + * @brief Executes move to color temp command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command. + * @return Status::Success when successful, + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a color XY transition state (verified in + * moveToColorTemp function). + */ +Status ColorControlServer::moveToColorTempCommand(EndpointId endpoint, + const Commands::MoveToColorTemperature::DecodableType & commandData) { - if (!shouldExecuteIfOff(commandPath.mEndpointId, commandData.optionsMask, commandData.optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); - Status status = moveToColorTemp(commandPath.mEndpointId, commandData.colorTemperatureMireds, commandData.transitionTime); + Status status = moveToColorTemp(endpoint, commandData.colorTemperatureMireds, commandData.transitionTime); #ifdef MATTER_DM_PLUGIN_SCENES_MANAGEMENT - ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(commandPath.mEndpointId); + ScenesManagement::ScenesServer::Instance().MakeSceneInvalidForAllFabrics(endpoint); #endif // MATTER_DM_PLUGIN_SCENES_MANAGEMENT - commandObj->AddStatus(commandPath, status); - return true; + return status; } -bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, - const Commands::StepColorTemperature::DecodableType & commandData) +/** + * @brief Executes step color temp command. + * @param endpoint EndpointId of the recipient Color control cluster. + * @param commandData Struct containing the parameters of the command + * @return Status::Success when successful, + * Status::InvalidCommand when stepSize is 0 or an unknown stepMode is provided + * Status::UnsupportedEndpoint when the provided endpoint doesn't correspond with a color temp transition state. + */ +Status ColorControlServer::stepColorTempCommand(EndpointId endpoint, + const Commands::StepColorTemperature::DecodableType & commandData) { - auto stepMode = commandData.stepMode; - uint16_t stepSize = commandData.stepSize; - uint16_t transitionTime = commandData.transitionTime; - uint16_t colorTemperatureMinimum = commandData.colorTemperatureMinimumMireds; - uint16_t colorTemperatureMaximum = commandData.colorTemperatureMaximumMireds; - BitMask optionsMask = commandData.optionsMask; - BitMask optionsOverride = commandData.optionsOverride; - EndpointId endpoint = commandPath.mEndpointId; - Status status = Status::Success; - uint16_t tempPhysicalMin = MIN_TEMPERATURE_VALUE; - uint16_t tempPhysicalMax = MAX_TEMPERATURE_VALUE; + // Confirm validity of the step mode and step size received + VerifyOrReturnValue(commandData.stepMode != HueStepMode::kUnknownEnumValue, Status::InvalidCommand); + VerifyOrReturnValue(commandData.stepSize != 0, Status::InvalidCommand); Color16uTransitionState * colorTempTransitionState = getTempTransitionState(endpoint); - VerifyOrExit(colorTempTransitionState != nullptr, status = Status::UnsupportedEndpoint); + VerifyOrReturnValue(colorTempTransitionState != nullptr, Status::UnsupportedEndpoint); - // Confirm validity of the step mode and step size received - if (stepMode == HueStepMode::kUnknownEnumValue || stepSize == 0) - { - commandObj->AddStatus(commandPath, Status::InvalidCommand); - return true; - } - - if (!shouldExecuteIfOff(endpoint, optionsMask, optionsOverride)) - { - commandObj->AddStatus(commandPath, Status::Success); - return true; - } + VerifyOrReturnValue(shouldExecuteIfOff(endpoint, commandData.optionsMask, commandData.optionsOverride), Status::Success); // New command. Need to stop any active transitions. stopAllColorTransitions(endpoint); + uint16_t tempPhysicalMin = MIN_TEMPERATURE_VALUE; + uint16_t tempPhysicalMax = MAX_TEMPERATURE_VALUE; Attributes::ColorTempPhysicalMinMireds::Get(endpoint, &tempPhysicalMin); Attributes::ColorTempPhysicalMaxMireds::Get(endpoint, &tempPhysicalMax); @@ -2812,6 +2781,7 @@ bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, // Per spec, colorTemperatureMinimumMireds field is limited to ColorTempPhysicalMinMireds and // when colorTemperatureMinimumMireds field is 0, ColorTempPhysicalMinMireds shall be used (always > 0) + uint16_t colorTemperatureMinimum = commandData.colorTemperatureMinimumMireds; if (colorTemperatureMinimum < tempPhysicalMin) { colorTemperatureMinimum = tempPhysicalMin; @@ -2819,6 +2789,7 @@ bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, // Per spec, colorTemperatureMaximumMireds field is limited to ColorTempPhysicalMaxMireds and // when colorTemperatureMaximumMireds field is 0, ColorTempPhysicalMaxMireds shall be used + uint16_t colorTemperatureMaximum = commandData.colorTemperatureMaximumMireds; if ((colorTemperatureMaximum == 0) || (colorTemperatureMaximum > tempPhysicalMax)) { colorTemperatureMaximum = tempPhysicalMax; @@ -2834,9 +2805,10 @@ bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, colorTempTransitionState->currentValue = colorTempTransitionState->initialValue; - if (stepMode == HueStepMode::kUp) + if (commandData.stepMode == HueStepMode::kUp) { - uint32_t finalValue32u = static_cast(colorTempTransitionState->initialValue) + static_cast(stepSize); + uint32_t finalValue32u = + static_cast(colorTempTransitionState->initialValue) + static_cast(commandData.stepSize); if (finalValue32u > UINT16_MAX) { colorTempTransitionState->finalValue = UINT16_MAX; @@ -2846,9 +2818,10 @@ bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, colorTempTransitionState->finalValue = static_cast(finalValue32u); } } - else if (stepMode == HueStepMode::kDown) + else if (commandData.stepMode == HueStepMode::kDown) { - uint32_t finalValue32u = static_cast(colorTempTransitionState->initialValue) - static_cast(stepSize); + uint32_t finalValue32u = + static_cast(colorTempTransitionState->initialValue) - static_cast(commandData.stepSize); if (finalValue32u > UINT16_MAX) { colorTempTransitionState->finalValue = 0; @@ -2858,22 +2831,20 @@ bool ColorControlServer::stepColorTempCommand(app::CommandHandler * commandObj, colorTempTransitionState->finalValue = static_cast(finalValue32u); } } - colorTempTransitionState->stepsRemaining = std::max(transitionTime, 1); + colorTempTransitionState->stepsRemaining = std::max(commandData.transitionTime, 1); colorTempTransitionState->stepsTotal = colorTempTransitionState->stepsRemaining; - colorTempTransitionState->timeRemaining = transitionTime; - colorTempTransitionState->transitionTime = transitionTime; + colorTempTransitionState->timeRemaining = commandData.transitionTime; + colorTempTransitionState->transitionTime = commandData.transitionTime; colorTempTransitionState->endpoint = endpoint; colorTempTransitionState->lowLimit = colorTemperatureMinimum; colorTempTransitionState->highLimit = colorTemperatureMaximum; - SetQuietReportRemainingTime(endpoint, transitionTime, true /* isNewTransition */); + SetQuietReportRemainingTime(endpoint, commandData.transitionTime, true /* isNewTransition */); // kick off the state machine: - scheduleTimerCallbackMs(configureTempEventControl(endpoint), transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); - -exit: - commandObj->AddStatus(commandPath, status); - return true; + scheduleTimerCallbackMs(configureTempEventControl(endpoint), + commandData.transitionTime ? TRANSITION_UPDATE_TIME_MS.count() : 0); + return Status::Success; } void ColorControlServer::levelControlColorTempChangeCommand(EndpointId endpoint) @@ -3220,21 +3191,27 @@ bool emberAfColorControlClusterMoveToColorTemperatureCallback(app::CommandHandle const app::ConcreteCommandPath & commandPath, const Commands::MoveToColorTemperature::DecodableType & commandData) { - return ColorControlServer::Instance().moveToColorTempCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().moveToColorTempCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterMoveColorTemperatureCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::MoveColorTemperature::DecodableType & commandData) { - return ColorControlServer::Instance().moveColorTempCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().moveColorTempCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } bool emberAfColorControlClusterStepColorTemperatureCallback(app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath, const Commands::StepColorTemperature::DecodableType & commandData) { - return ColorControlServer::Instance().stepColorTempCommand(commandObj, commandPath, commandData); + Status status = ColorControlServer::Instance().stepColorTempCommand(commandPath.mEndpointId, commandData); + commandObj->AddStatus(commandPath, status); + return true; } void emberAfPluginLevelControlCoupledColorTempChangeCallback(EndpointId endpoint) diff --git a/src/app/clusters/color-control-server/color-control-server.h b/src/app/clusters/color-control-server/color-control-server.h index 210df4c16635f0..40ae30aeb2224f 100644 --- a/src/app/clusters/color-control-server/color-control-server.h +++ b/src/app/clusters/color-control-server/color-control-server.h @@ -197,13 +197,15 @@ class ColorControlServer #endif // MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_XY #ifdef MATTER_DM_PLUGIN_COLOR_CONTROL_SERVER_TEMP - bool moveColorTempCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::MoveColorTemperature::DecodableType & commandData); - bool - moveToColorTempCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, + chip::Protocols::InteractionModel::Status + moveColorTempCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::MoveColorTemperature::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + moveToColorTempCommand(const chip::EndpointId endpoint, const chip::app::Clusters::ColorControl::Commands::MoveToColorTemperature::DecodableType & commandData); - bool stepColorTempCommand(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::ColorControl::Commands::StepColorTemperature::DecodableType & commandData); + chip::Protocols::InteractionModel::Status + stepColorTempCommand(const chip::EndpointId endpoint, + const chip::app::Clusters::ColorControl::Commands::StepColorTemperature::DecodableType & commandData); void levelControlColorTempChangeCommand(chip::EndpointId endpoint); void startUpColorTempCommand(chip::EndpointId endpoint); void updateTempCommand(chip::EndpointId endpoint); From 04545045ae8d1d7aee7842df8fc75b7b950c666a Mon Sep 17 00:00:00 2001 From: lpbeliveau-silabs <112982107+lpbeliveau-silabs@users.noreply.github.com> Date: Thu, 7 Nov 2024 14:29:09 -0500 Subject: [PATCH 093/121] Pull request #2067: Provision SPAM (#36404) Merge in WMN_TOOLS/matter from provision_SPAM to dev/provision_source_code Squashed commit of the following: commit ae6d6bd09b963838fa8ae70efefa0770c33c5b73 Author: lpbeliveau-silabs Date: Wed Sep 25 11:08:23 2024 -0400 Updated the GsdkSpam for series 3 now that provisioning relies on it commit fb0cb797ca3eea51856e2b62e5b2c0a4dfb8cac3 Author: lpbeliveau-silabs Date: Tue Sep 24 17:53:54 2024 -0400 Updated provisioning to use Silabs Platform Abstraction Manager Co-authored-by: Andrei Litvin --- .../provision/ProvisionStorageDefault.cpp | 67 ++--------------- .../silabs/platformAbstraction/GsdkSpam.cpp | 71 ++++++++++++++++++- .../platformAbstraction/SilabsPlatform.h | 4 ++ .../platformAbstraction/SilabsPlatformBase.h | 5 ++ .../platformAbstraction/WiseMcuSpam.cpp | 19 +++++ 5 files changed, 102 insertions(+), 64 deletions(-) diff --git a/examples/platform/silabs/provision/ProvisionStorageDefault.cpp b/examples/platform/silabs/provision/ProvisionStorageDefault.cpp index bc0bfbd8f06918..c6071094480363 100644 --- a/examples/platform/silabs/provision/ProvisionStorageDefault.cpp +++ b/examples/platform/silabs/provision/ProvisionStorageDefault.cpp @@ -17,7 +17,6 @@ #include "AttestationKey.h" #include "ProvisionStorage.h" #include -#include #include #include #include @@ -28,6 +27,7 @@ #include #include #include +#include #include #ifndef NDEBUG #if defined(SL_MATTER_TEST_EVENT_TRIGGER_ENABLED) && (SL_MATTER_GN_BUILD == 0) @@ -37,16 +37,7 @@ #ifdef OTA_ENCRYPTION_ENABLE #include #endif // OTA_ENCRYPTION_ENABLE -#ifdef SLI_SI91X_MCU_INTERFACE -#include -#else -#ifdef _SILICON_LABS_32B_SERIES_2 -#include -#elif defined(_SILICON_LABS_32B_SERIES_3) -#include "sl_se_manager.h" -#include "sl_se_manager_types.h" -#include -#endif // _SILICON_LABS_32B_SERIES_2 +#ifndef SLI_SI91X_MCU_INTERFACE #include #endif @@ -56,16 +47,6 @@ extern void setNvm3End(uint32_t addr); #include #endif -#if defined(_SILICON_LABS_32B_SERIES_3) -// To remove any ambiguities regarding the Flash aliases, use the below macro to ignore the 8 MSB. -#define FLASH_GENERIC_MASK 0x00FFFFFF -#define GENERIC_ADDRESS(addr) ((addr) &FLASH_GENERIC_MASK) - -// Transforms any address into an address using the same alias as FLASH_BASE from the CMSIS. -#define CMSIS_CONVERTED_ADDRESS(addr) (GENERIC_ADDRESS(addr) | FLASH_BASE) -sl_se_command_context_t cmd_ctx; -#endif // _SILICON_LABS_32B_SERIES_3 - extern uint8_t linker_nvm_end[]; using namespace chip::Credentials; @@ -86,42 +67,12 @@ size_t sCredentialsOffset = 0; CHIP_ERROR ErasePage(uint32_t addr) { -#ifdef SLI_SI91X_MCU_INTERFACE - rsi_flash_erase_sector((uint32_t *) addr); -#elif defined(_SILICON_LABS_32B_SERIES_2) - MSC_ErasePage((uint32_t *) addr); -#elif defined(_SILICON_LABS_32B_SERIES_3) - sl_status_t status; - uint32_t * data_start = NULL; - size_t data_size; - - status = sl_se_data_region_get_location(&cmd_ctx, (void **) &data_start, &data_size); - VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); - VerifyOrReturnError(GENERIC_ADDRESS(addr) > GENERIC_ADDRESS((uint32_t) data_start), CHIP_ERROR_INVALID_ADDRESS); - status = sl_se_data_region_erase(&cmd_ctx, (void *) addr, 1); // Erase one page - VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); -#endif - return CHIP_NO_ERROR; + return chip::DeviceLayer::Silabs::GetPlatform().FlashErasePage(addr); } CHIP_ERROR WritePage(uint32_t addr, const uint8_t * data, size_t size) { -#ifdef SLI_SI91X_MCU_INTERFACE - rsi_flash_write((uint32_t *) addr, (unsigned char *) data, size); -#elif defined(_SILICON_LABS_32B_SERIES_2) - MSC_WriteWord((uint32_t *) addr, data, size); -#elif defined(_SILICON_LABS_32B_SERIES_3) - sl_status_t status; - uint32_t * data_start = NULL; - size_t data_size; - - status = sl_se_data_region_get_location(&cmd_ctx, (void **) &data_start, &data_size); - VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); - VerifyOrReturnError(GENERIC_ADDRESS(addr) > GENERIC_ADDRESS((uint32_t) data_start), CHIP_ERROR_INVALID_ADDRESS); - status = sl_se_data_region_write(&cmd_ctx, (void *) addr, data, size); - VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); -#endif - return CHIP_NO_ERROR; + return chip::DeviceLayer::Silabs::GetPlatform().FlashWritePage(addr, data, size); } size_t RoundNearest(size_t n, size_t multiple) @@ -203,16 +154,8 @@ CHIP_ERROR Storage::Initialize(uint32_t flash_addr, uint32_t flash_size) { #ifndef SLI_SI91X_MCU_INTERFACE base_addr = (flash_addr + flash_size - FLASH_PAGE_SIZE); - -#ifdef _SILICON_LABS_32B_SERIES_2 - MSC_Init(); -#elif defined(_SILICON_LABS_32B_SERIES_3) - sl_status_t status; - status = sl_se_init(); - VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR_INTERNAL); - status = sl_se_init_command_context(&cmd_ctx); -#endif // _SILICON_LABS_32B_SERIES #endif // SLI_SI91X_MCU_INTERFACE + chip::DeviceLayer::Silabs::GetPlatform().FlashInit(); #ifdef SL_PROVISION_GENERATOR setNvm3End(base_addr); #endif diff --git a/src/platform/silabs/platformAbstraction/GsdkSpam.cpp b/src/platform/silabs/platformAbstraction/GsdkSpam.cpp index 92ddd281f8fe55..2e0ab6b811f160 100644 --- a/src/platform/silabs/platformAbstraction/GsdkSpam.cpp +++ b/src/platform/silabs/platformAbstraction/GsdkSpam.cpp @@ -15,12 +15,17 @@ * limitations under the License. */ +#include +#include #include - #if defined(_SILICON_LABS_32B_SERIES_2) +#include "em_msc.h" #include "em_rmu.h" -#else +#elif defined(_SILICON_LABS_32B_SERIES_3) #include "sl_hal_emu.h" +#include "sl_se_manager.h" +#include "sl_se_manager_types.h" +#include #endif // _SILICON_LABS_32B_SERIES_2 #include "sl_system_kernel.h" @@ -65,6 +70,18 @@ extern "C" { #include "silabs_utils.h" #endif +#if defined(_SILICON_LABS_32B_SERIES_3) +// To remove any ambiguities regarding the Flash aliases, use the below macro to ignore the 8 MSB. +#define FLASH_GENERIC_MASK 0x00FFFFFF +#define GENERIC_ADDRESS(addr) ((addr) &FLASH_GENERIC_MASK) + +// Transforms any address into an address using the same alias as FLASH_BASE from the CMSIS. +#define CMSIS_CONVERTED_ADDRESS(addr) (GENERIC_ADDRESS(addr) | FLASH_BASE) +namespace { +sl_se_command_context_t cmd_ctx; +} +#endif // _SILICON_LABS_32B_SERIES_3 + namespace chip { namespace DeviceLayer { namespace Silabs { @@ -107,6 +124,56 @@ CHIP_ERROR SilabsPlatform::Init(void) return CHIP_NO_ERROR; } +CHIP_ERROR SilabsPlatform::FlashInit() +{ +#if defined(_SILICON_LABS_32B_SERIES_2) + MSC_Init(); +#elif defined(_SILICON_LABS_32B_SERIES_3) + sl_status_t status; + status = sl_se_init(); + VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); + status = sl_se_init_command_context(&cmd_ctx); + VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); +#endif + return CHIP_NO_ERROR; +} + +CHIP_ERROR SilabsPlatform::FlashErasePage(uint32_t addr) +{ +#if defined(_SILICON_LABS_32B_SERIES_2) + MSC_ErasePage((uint32_t *) addr); +#elif defined(_SILICON_LABS_32B_SERIES_3) + sl_status_t status; + uint32_t * data_start = NULL; + size_t data_size; + + status = sl_se_data_region_get_location(&cmd_ctx, (void **) &data_start, &data_size); + VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); + VerifyOrReturnError(GENERIC_ADDRESS(addr) > GENERIC_ADDRESS((uint32_t) data_start), CHIP_ERROR_INVALID_ADDRESS); + status = sl_se_data_region_erase(&cmd_ctx, (void *) addr, 1); // Erase one page + VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); +#endif + return CHIP_NO_ERROR; +} + +CHIP_ERROR SilabsPlatform::FlashWritePage(uint32_t addr, const uint8_t * data, size_t size) +{ +#if defined(_SILICON_LABS_32B_SERIES_2) + MSC_WriteWord((uint32_t *) addr, data, size); +#elif defined(_SILICON_LABS_32B_SERIES_3) + sl_status_t status; + uint32_t * data_start = NULL; + size_t data_size; + + status = sl_se_data_region_get_location(&cmd_ctx, (void **) &data_start, &data_size); + VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); + VerifyOrReturnError(GENERIC_ADDRESS(addr) > GENERIC_ADDRESS((uint32_t) data_start), CHIP_ERROR_INVALID_ADDRESS); + status = sl_se_data_region_write(&cmd_ctx, (void *) addr, data, size); + VerifyOrReturnError(status == SL_STATUS_OK, CHIP_ERROR(status)); +#endif + return CHIP_NO_ERROR; +} + #ifdef ENABLE_WSTK_LEDS void SilabsPlatform::InitLed(void) { diff --git a/src/platform/silabs/platformAbstraction/SilabsPlatform.h b/src/platform/silabs/platformAbstraction/SilabsPlatform.h index 49f5264cac0550..df84224c50da35 100644 --- a/src/platform/silabs/platformAbstraction/SilabsPlatform.h +++ b/src/platform/silabs/platformAbstraction/SilabsPlatform.h @@ -57,6 +57,10 @@ class SilabsPlatform : virtual public SilabsPlatformAbstractionBase void StartScheduler(void) override; + CHIP_ERROR FlashInit() override; + CHIP_ERROR FlashErasePage(uint32_t addr) override; + CHIP_ERROR FlashWritePage(uint32_t addr, const uint8_t * data, size_t size) override; + private: friend SilabsPlatform & GetPlatform(void); diff --git a/src/platform/silabs/platformAbstraction/SilabsPlatformBase.h b/src/platform/silabs/platformAbstraction/SilabsPlatformBase.h index 12f87c07ea7e0d..818463ecfb9d12 100644 --- a/src/platform/silabs/platformAbstraction/SilabsPlatformBase.h +++ b/src/platform/silabs/platformAbstraction/SilabsPlatformBase.h @@ -51,6 +51,11 @@ class SilabsPlatformAbstractionBase virtual bool GetLedState(uint8_t led) { return 0; } virtual CHIP_ERROR ToggleLed(uint8_t led) { return CHIP_ERROR_NOT_IMPLEMENTED; } + // Flash + virtual CHIP_ERROR FlashInit() { return CHIP_ERROR_NOT_IMPLEMENTED; } + virtual CHIP_ERROR FlashErasePage(uint32_t addr) { return CHIP_ERROR_NOT_IMPLEMENTED; } + virtual CHIP_ERROR FlashWritePage(uint32_t addr, const uint8_t * data, size_t size) { return CHIP_ERROR_NOT_IMPLEMENTED; } + // BLE Specific Method protected: diff --git a/src/platform/silabs/platformAbstraction/WiseMcuSpam.cpp b/src/platform/silabs/platformAbstraction/WiseMcuSpam.cpp index 317d59074af323..7992b406ada4fd 100644 --- a/src/platform/silabs/platformAbstraction/WiseMcuSpam.cpp +++ b/src/platform/silabs/platformAbstraction/WiseMcuSpam.cpp @@ -17,11 +17,13 @@ #include #include +#include #include #include #include +#include #include #if SILABS_LOG_ENABLED @@ -192,6 +194,23 @@ uint8_t SilabsPlatform::GetButtonState(uint8_t button) return (button < SL_SI91x_BUTTON_COUNT) ? sButtonStates[button] : 0; } +CHIP_ERROR SilabsPlatform::FlashInit() +{ + return CHIP_NO_ERROR; +} + +CHIP_ERROR SilabsPlatform::FlashErasePage(uint32_t addr) +{ + rsi_flash_erase_sector((uint32_t *) addr); + return CHIP_NO_ERROR; +} + +CHIP_ERROR SilabsPlatform::FlashWritePage(uint32_t addr, const uint8_t * data, size_t size) +{ + rsi_flash_write((uint32_t *) addr, (unsigned char *) data, size); + return CHIP_NO_ERROR; +} + } // namespace Silabs } // namespace DeviceLayer } // namespace chip From e6323e3a0c0b56ac990678428c30d0653d5379e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ludovic=20BOU=C3=89?= Date: Thu, 7 Nov 2024 22:00:02 +0100 Subject: [PATCH 094/121] energy-management-app: Add Python CHIP Controller link in README (#36345) * Update README.md Add link to Working with Python CHIP Controller * Format --- examples/energy-management-app/linux/README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/examples/energy-management-app/linux/README.md b/examples/energy-management-app/linux/README.md index 57df50bba575cf..87b6d9dd93db39 100644 --- a/examples/energy-management-app/linux/README.md +++ b/examples/energy-management-app/linux/README.md @@ -239,8 +239,9 @@ data (e.g. fabric info). ## CHIP-REPL Interaction -- See chip-repl documentation in - [Matter_REPL_Intro](../../../docs/development_controllers/chip-repl/Matter_REPL_Intro.ipynb) +- See chip-repl documentation in: + - [Working with Python CHIP Controller](../../../docs/development_controllers/chip-repl/python_chip_controller_building.md) + - [Matter_REPL_Intro](../../../docs/development_controllers/chip-repl/Matter_REPL_Intro.ipynb) ### Building chip-repl: From f83799483dbdc945f3fc19c07e9590fbece129c1 Mon Sep 17 00:00:00 2001 From: Raul Marquez <130402456+raul-marquez-csa@users.noreply.github.com> Date: Thu, 7 Nov 2024 13:01:40 -0800 Subject: [PATCH 095/121] Updates step1 (#36313) --- src/app/tests/suites/certification/Test_TC_DEMM_1_2.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app/tests/suites/certification/Test_TC_DEMM_1_2.yaml b/src/app/tests/suites/certification/Test_TC_DEMM_1_2.yaml index 900428998445ea..c03711c6bc4c8f 100644 --- a/src/app/tests/suites/certification/Test_TC_DEMM_1_2.yaml +++ b/src/app/tests/suites/certification/Test_TC_DEMM_1_2.yaml @@ -36,11 +36,11 @@ tests: - Verify that each ModeOptionsStruct entry’s ModeTags field has: at least one entry the values of the Value fields that are not larger than 16 bits - for each Value field: Is the mode tag value a defined common tag value (Auto(0x0000), Quick(0x0001), Quiet(0x0002), LowNoise(0x0003), LowEnergy(0x0004), Vacation(0x0005), Min(0x0006), Max(0x0007), Night(0x0008), Day(0x0009)) or a defined cluster-derived tag value (No Optimization, Device Optimization, Local Optimization, Grid Optimization) or in the MfgTags (0x8000 to 0xBFFF) range - - for at least one Value field: Is the mode tag value a defined common tag value (Auto(0x0000), Quick(0x0001), Quiet(0x0002), LowNoise(0x0003), LowEnergy(0x0004), Vacation(0x0005), Min(0x0006), Max(0x0007), Night(0x0008), Day(0x0009)) or a derived cluster value (RapidCool, RapidFreeze) - - Verify that at least one ModeOptionsStruct entry includes either the RapidCool semantic tag or the RapidFreeze semantic tag in the SemanticTags field + - for at least one Value field: Is the mode tag value a defined common tag value (Auto(0x0000), Quick(0x0001), Quiet(0x0002), LowNoise(0x0003), LowEnergy(0x0004), Vacation(0x0005), Min(0x0006), Max(0x0007), Night(0x0008), Day(0x0009)) or a derived cluster value (No Optimization, Device Optimization, Local Optimization, Grid Optimization) + - Verify that at least one SupportedModes entry includes the No Optimization mode tag or Local Optimization mode tag or Grid Optimization mode tag. + - Verify that an entry in the SupportedModes attribute that include one of Device Optimization, Local Optimization, Grid Optimization does not also include No Optimization mode tag. - Save the Mode field values as supported_modes_dut on the TH (Chip-tool) and below is the sample log provided for the raspi platform: - [1705923890.093456][23589:23591] CHIP:DMG: } [1705923890.094137][23589:23591] CHIP:TOO: Endpoint: 1 Cluster: 0x0000_009F Attribute 0x0000_0000 DataVersion: 2217281174 [1705923890.094312][23589:23591] CHIP:TOO: SupportedModes: 5 entries From 78f399d4e4bb4c84161ce87ab9139fefee14572e Mon Sep 17 00:00:00 2001 From: Sergio Soares Date: Thu, 7 Nov 2024 16:34:37 -0500 Subject: [PATCH 096/121] energy-management-app: Readme: fix instructions to build for silabs (#36341) --- examples/energy-management-app/silabs/README.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/examples/energy-management-app/silabs/README.md b/examples/energy-management-app/silabs/README.md index 09253afa55524c..2b565ec4b30e77 100644 --- a/examples/energy-management-app/silabs/README.md +++ b/examples/energy-management-app/silabs/README.md @@ -108,14 +108,14 @@ creating real products based on the Silicon Labs platform. To build the Water Heater example you can change the args to gn gen (see BUILD.gn for arg options) - $ gn gen out/debug --args='chip_enable_example_evse_device=false chip_enable_example_water_heater_device=true' + $ gn gen out/debug --args='sl_enable_example_evse_device=false sl_enable_example_water_heater_device=true' $ ninja -C out/debug To change Device Energy Management feature support (e.g. Power forecast or State forecast reporting), you can change the args to gn gen (see BUILD.gn for arg options) - $ gn gen out/debug --args='chip_dem_support_state_forecast_reporting=true chip_dem_support_power_forecast_reporting=false' + $ gn gen out/debug --args='sl_dem_support_state_forecast_reporting=true sl_dem_support_power_forecast_reporting=false' $ ninja -C out/debug - To delete generated executable, libraries and object files use: @@ -127,10 +127,6 @@ creating real products based on the Silicon Labs platform. $ ./scripts/examples/gn_silabs_example.sh ./examples/energy-management-app/silabs/ ./out/energy-management-app_ICD BRD4187C --icd - or use gn as previously mentioned but adding the following arguments: - - $ gn gen out/debug '--args=SILABS_BOARD="BRD4187C" enable_sleepy_device=true chip_openthread_ftd=false' - * Build the example with pigweed RPC $ ./scripts/examples/gn_silabs_example.sh examples/energy-management-app/silabs/ out/energy_management_app_rpc BRD4187C 'import("//with_pw_rpc.gni")' From e33840426da399ebc0cb96594bde22f2cfbf6584 Mon Sep 17 00:00:00 2001 From: Song GUO Date: Fri, 8 Nov 2024 06:56:54 +0800 Subject: [PATCH 097/121] [cirque] Add tests for re-registration for ICD devices (#36335) * Update Linux app main * [cirque] Add tests for re-registration for ICD devices * Fix test --------- Co-authored-by: Andrei Litvin --- examples/platform/linux/AppMain.cpp | 6 +++++ examples/platform/linux/BUILD.gn | 4 ++++ scripts/tests/cirque_tests.sh | 2 +- .../python/test/test_scripts/base.py | 6 ++--- ..._for_device_test.py => icd_device_test.py} | 24 ++++++++++++++++--- ...dWaitForActiveTest.py => IcdDeviceTest.py} | 12 ++++++---- 6 files changed, 42 insertions(+), 12 deletions(-) rename src/controller/python/test/test_scripts/{icd_wait_for_device_test.py => icd_device_test.py} (83%) rename src/test_driver/linux-cirque/{IcdWaitForActiveTest.py => IcdDeviceTest.py} (93%) diff --git a/examples/platform/linux/AppMain.cpp b/examples/platform/linux/AppMain.cpp index a2e341efbe7a0f..d18c3106cf5f20 100644 --- a/examples/platform/linux/AppMain.cpp +++ b/examples/platform/linux/AppMain.cpp @@ -96,6 +96,9 @@ #if CHIP_DEVICE_CONFIG_ENABLE_DEVICE_ENERGY_MANAGEMENT_TRIGGER #include #endif +#if CHIP_CONFIG_ENABLE_ICD_SERVER +#include +#endif #include #include @@ -593,6 +596,9 @@ void ChipLinuxAppMainLoop(AppMainLoopImplementation * impl) static DeviceEnergyManagementTestEventTriggerHandler sDeviceEnergyManagementTestEventTriggerHandler; sTestEventTriggerDelegate.AddHandler(&sDeviceEnergyManagementTestEventTriggerHandler); #endif +#if CHIP_CONFIG_ENABLE_ICD_SERVER + sTestEventTriggerDelegate.AddHandler(&Server::GetInstance().GetICDManager()); +#endif initParams.testEventTriggerDelegate = &sTestEventTriggerDelegate; diff --git a/examples/platform/linux/BUILD.gn b/examples/platform/linux/BUILD.gn index 336534aae65043..30583ce7d0e399 100644 --- a/examples/platform/linux/BUILD.gn +++ b/examples/platform/linux/BUILD.gn @@ -15,6 +15,7 @@ import("//build_overrides/chip.gni") import("${chip_root}/examples/common/pigweed/pigweed_rpcs.gni") import("${chip_root}/src/app/common_flags.gni") +import("${chip_root}/src/app/icd/icd.gni") import("${chip_root}/src/lib/core/core.gni") import("${chip_root}/src/lib/lib.gni") import("${chip_root}/src/tracing/tracing_args.gni") @@ -133,6 +134,9 @@ source_set("app-main") { "${chip_root}/src/tracing", ] } + if (chip_enable_icd_server) { + deps += [ "${chip_root}/src/app/icd/server:manager" ] + } defines += [ "CHIP_DEVICE_CONFIG_ENABLE_SMOKE_CO_TRIGGER=${chip_enable_smoke_co_trigger}", diff --git a/scripts/tests/cirque_tests.sh b/scripts/tests/cirque_tests.sh index b7dcdbcab2ff6a..1a591bd30b0c3f 100755 --- a/scripts/tests/cirque_tests.sh +++ b/scripts/tests/cirque_tests.sh @@ -48,7 +48,7 @@ CIRQUE_TESTS=( "FailsafeTest" "MobileDeviceTest" "CommissioningTest" - "IcdWaitForActiveTest" + "IcdDeviceTest" "SplitCommissioningTest" "CommissioningFailureTest" "CommissioningFailureOnReportTest" diff --git a/src/controller/python/test/test_scripts/base.py b/src/controller/python/test/test_scripts/base.py index dc07e15bc2f709..b2c6ee2bb5207e 100644 --- a/src/controller/python/test/test_scripts/base.py +++ b/src/controller/python/test/test_scripts/base.py @@ -1159,7 +1159,7 @@ def TestResolve(self, nodeid): return False async def TestTriggerTestEventHandler(self, nodeid, enable_key, event_trigger): - self.logger.info("Test trigger test event handler for device = %08x", nodeid) + self.logger.info("Test trigger test event handler for device = %08x trigger = %016x", nodeid, event_trigger) try: await self.devCtrl.SendCommand(nodeid, 0, Clusters.GeneralDiagnostics.Commands.TestEventTrigger(enableKey=enable_key, eventTrigger=event_trigger)) return True @@ -1167,10 +1167,10 @@ async def TestTriggerTestEventHandler(self, nodeid, enable_key, event_trigger): self.logger.exception("Failed to trigger test event handler {}".format(ex)) return False - async def TestWaitForActive(self, nodeid): + async def TestWaitForActive(self, nodeid, stayActiveDurationMs=30000): self.logger.info("Test wait for device = %08x", nodeid) try: - await self.devCtrl.WaitForActive(nodeid) + await self.devCtrl.WaitForActive(nodeid, stayActiveDurationMs=stayActiveDurationMs) return True except Exception as ex: self.logger.exception("Failed to wait for active. {}".format(ex)) diff --git a/src/controller/python/test/test_scripts/icd_wait_for_device_test.py b/src/controller/python/test/test_scripts/icd_device_test.py similarity index 83% rename from src/controller/python/test/test_scripts/icd_wait_for_device_test.py rename to src/controller/python/test/test_scripts/icd_device_test.py index e28a76e17ac41e..e93ee5dac399f3 100755 --- a/src/controller/python/test/test_scripts/icd_wait_for_device_test.py +++ b/src/controller/python/test/test_scripts/icd_device_test.py @@ -35,11 +35,15 @@ async def waitForActiveAndTriggerCheckIn(test, nodeid): - coro = test.TestWaitForActive(nodeid=nodeid) - await test.TestTriggerTestEventHandler(nodeid, bytes.fromhex("00112233445566778899aabbccddeeff"), 0x0046 << 48) + coro = test.TestWaitForActive(nodeid=nodeid, stayActiveDurationMs=10) return await coro +async def invalidateHalfCounterValuesAndWaitForCheckIn(test, nodeid, testEventKey): + await test.TestTriggerTestEventHandler(nodeid, bytes.fromhex(testEventKey), 0x0046_0000_0000_0003) + return await waitForActiveAndTriggerCheckIn(test, nodeid) + + async def main(): optParser = OptionParser() optParser.add_option( @@ -108,6 +112,15 @@ async def main(): help="Discovery type of commissioning. (0: networkOnly 1: networkOnlyWithoutPASEAutoRetry 2: All)", metavar="" ) + optParser.add_option( + "--test-event-key", + action="store", + dest="testEventKey", + default="00112233445566778899aabbccddeeff", + type=str, + help="Enable key of Test event trigger.", + metavar="" + ) (options, remainingArgs) = optParser.parse_args(sys.argv[1:]) @@ -125,9 +138,14 @@ async def main(): nodeid=options.nodeid), "Failed to finish key exchange") logger.info("Commissioning completed") + logger.info("Testing wait for active") FailIfNot(await waitForActiveAndTriggerCheckIn(test, nodeid=options.nodeid), "Failed to test wait for active") - logger.info('Successfully handled wait-for-active') + logger.info("Successfully handled wait-for-active") + + logger.info("Testing InvalidateHalfCounterValues for refresh key") + FailIfNot(await invalidateHalfCounterValuesAndWaitForCheckIn(test, nodeid=options.nodeid, testEventKey=options.testEventKey), "Failed to test wait for active") + logger.info("Successfully handled key refresh") timeoutTicker.stop() diff --git a/src/test_driver/linux-cirque/IcdWaitForActiveTest.py b/src/test_driver/linux-cirque/IcdDeviceTest.py similarity index 93% rename from src/test_driver/linux-cirque/IcdWaitForActiveTest.py rename to src/test_driver/linux-cirque/IcdDeviceTest.py index bb2c1cb8384a3c..b4786897423bd6 100755 --- a/src/test_driver/linux-cirque/IcdWaitForActiveTest.py +++ b/src/test_driver/linux-cirque/IcdDeviceTest.py @@ -43,6 +43,8 @@ TEST_DISCOVERY_TYPE = [0, 1, 2] MATTER_DEVELOPMENT_PAA_ROOT_CERTS = "credentials/development/paa-root-certs" +TEST_EVENT_KEY_HEX = "00112233445566778899aabbccddeeff" + DEVICE_CONFIG = { 'device0': { 'type': 'MobileDevice', @@ -88,8 +90,8 @@ def run_controller_test(self): self.execute_device_cmd( server, ("CHIPCirqueDaemon.py -- run gdb -batch -return-child-result -q -ex \"set pagination off\" " - "-ex run -ex \"thread apply all bt\" --args {} --thread --discriminator {}").format( - os.path.join(CHIP_REPO, "out/debug/lit_icd/lit-icd-app"), TEST_DISCRIMINATOR)) + "-ex run -ex \"thread apply all bt\" --args {} --thread --discriminator {} --enable-key {}").format( + os.path.join(CHIP_REPO, "out/debug/lit_icd/lit-icd-app"), TEST_DISCRIMINATOR, TEST_EVENT_KEY_HEX)) self.reset_thread_devices(server_ids) @@ -103,10 +105,10 @@ def run_controller_test(self): CHIP_REPO, "out/debug/linux_x64_gcc/controller/python/chip_repl-0.0-py3-none-any.whl"))) command = ("gdb -batch -return-child-result -q -ex run -ex \"thread apply all bt\" " - "--args python3 {} -t 300 -a {} --paa-trust-store-path {}").format( + "--args python3 {} -t 300 -a {} --paa-trust-store-path {} --test-event-key {}").format( os.path.join( - CHIP_REPO, "src/controller/python/test/test_scripts/icd_wait_for_device_test.py"), ethernet_ip, - os.path.join(CHIP_REPO, MATTER_DEVELOPMENT_PAA_ROOT_CERTS)) + CHIP_REPO, "src/controller/python/test/test_scripts/icd_device_test.py"), ethernet_ip, + os.path.join(CHIP_REPO, MATTER_DEVELOPMENT_PAA_ROOT_CERTS), TEST_EVENT_KEY_HEX) ret = self.execute_device_cmd(req_device_id, command) self.assertEqual(ret['return_code'], '0', From 585a74ca7eeed5891ab01845f3f748ad8286f776 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Thu, 7 Nov 2024 23:23:26 -0800 Subject: [PATCH 098/121] Fix failing to cleanup the synced device after it is removed (#36412) --- .../commands/pairing/PairingCommand.cpp | 11 +++---- .../device_manager/DeviceManager.cpp | 30 ++++++++++--------- .../device_manager/DeviceManager.h | 6 ++-- .../device_manager/PairingManager.cpp | 11 +++---- examples/fabric-sync/admin/DeviceManager.cpp | 12 -------- examples/fabric-sync/admin/DeviceManager.h | 4 +-- examples/fabric-sync/admin/PairingManager.cpp | 2 ++ 7 files changed, 29 insertions(+), 47 deletions(-) diff --git a/examples/fabric-admin/commands/pairing/PairingCommand.cpp b/examples/fabric-admin/commands/pairing/PairingCommand.cpp index 031b57ef5444f7..e7298a1deb04c2 100644 --- a/examples/fabric-admin/commands/pairing/PairingCommand.cpp +++ b/examples/fabric-admin/commands/pairing/PairingCommand.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -33,10 +34,6 @@ #include -#if defined(PW_RPC_ENABLED) -#include -#endif - using namespace ::chip; using namespace ::chip::Controller; @@ -534,16 +531,16 @@ void PairingCommand::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E PairingCommand * command = reinterpret_cast(context); VerifyOrReturn(command != nullptr, ChipLogError(NotSpecified, "OnCurrentFabricRemove: context is null")); + ChipLogProgress(NotSpecified, "PairingCommand::OnCurrentFabricRemove"); + if (err == CHIP_NO_ERROR) { // print to console fprintf(stderr, "Device with Node ID: 0x%lx has been successfully removed.\n", nodeId); -#if defined(PW_RPC_ENABLED) app::InteractionModelEngine::GetInstance()->ShutdownSubscriptions(command->CurrentCommissioner().GetFabricIndex(), nodeId); ScopedNodeId scopedNodeId(nodeId, command->CurrentCommissioner().GetFabricIndex()); - admin::RemoveSynchronizedDevice(scopedNodeId); -#endif + admin::DeviceMgr().RemoveSyncedDevice(scopedNodeId); } else { diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index 7546f503b55274..8be53fd5faf128 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -25,6 +25,10 @@ #include #include +#if defined(PW_RPC_ENABLED) +#include +#endif + using namespace chip; namespace admin { @@ -109,8 +113,13 @@ Device * DeviceManager::FindDeviceByNode(NodeId nodeId) return nullptr; } -void DeviceManager::RemoveSyncedDevice(NodeId nodeId) +void DeviceManager::RemoveSyncedDevice(chip::ScopedNodeId scopedNodeId) { +#if defined(PW_RPC_ENABLED) + RemoveSynchronizedDevice(scopedNodeId); +#endif + + NodeId nodeId = scopedNodeId.GetNodeId(); Device * device = FindDeviceByNode(nodeId); if (device == nullptr) { @@ -259,6 +268,10 @@ void DeviceManager::HandleReadSupportedDeviceCategories(TLV::TLVReader & data) ChipLogProgress(NotSpecified, "Remote Fabric-Bridge supports Fabric Synchronization, start reverse commissioning."); RequestCommissioningApproval(); } + else + { + ChipLogProgress(NotSpecified, "Remote Fabric-Bridge does not support Fabric Synchronization."); + } } void DeviceManager::RequestCommissioningApproval() @@ -406,6 +419,8 @@ void DeviceManager::SendCommissionNodeRequest(uint64_t requestId, uint16_t respo void DeviceManager::HandleReverseOpenCommissioningWindow(TLV::TLVReader & data) { + ChipLogProgress(NotSpecified, "Handle ReverseOpenCommissioningWindow command."); + app::Clusters::CommissionerControl::Commands::ReverseOpenCommissioningWindow::DecodableType value; CHIP_ERROR error = app::DataModel::Decode(data, value); @@ -459,17 +474,4 @@ void DeviceManager::HandleCommandResponse(const app::ConcreteCommandPath & path, } } -void DeviceManager::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) -{ - if (err != CHIP_NO_ERROR) - { - ChipLogError(NotSpecified, "Failed to remove synced device:(" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, - ChipLogValueX64(deviceId), err.Format()); - return; - } - - RemoveSyncedDevice(deviceId); - ChipLogProgress(NotSpecified, "Synced device with NodeId:" ChipLogFormatX64 " has been removed.", ChipLogValueX64(deviceId)); -} - } // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceManager.h b/examples/fabric-admin/device_manager/DeviceManager.h index 9d2a37ab5ab721..c4898baa18daa4 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.h +++ b/examples/fabric-admin/device_manager/DeviceManager.h @@ -50,7 +50,7 @@ class Device chip::EndpointId mEndpointId; }; -class DeviceManager : public PairingDelegate +class DeviceManager { public: DeviceManager() = default; @@ -77,7 +77,7 @@ class DeviceManager : public PairingDelegate void AddSyncedDevice(const Device & device); - void RemoveSyncedDevice(chip::NodeId nodeId); + void RemoveSyncedDevice(chip::ScopedNodeId scopedNodeId); /** * @brief Determines whether a given nodeId corresponds to the "current bridge device," either local or remote. @@ -177,8 +177,6 @@ class DeviceManager : public PairingDelegate private: friend DeviceManager & DeviceMgr(); - void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; - void RequestCommissioningApproval(); void HandleReadSupportedDeviceCategories(chip::TLV::TLVReader & data); diff --git a/examples/fabric-admin/device_manager/PairingManager.cpp b/examples/fabric-admin/device_manager/PairingManager.cpp index 40194f9a686056..fae6c09315e8c2 100644 --- a/examples/fabric-admin/device_manager/PairingManager.cpp +++ b/examples/fabric-admin/device_manager/PairingManager.cpp @@ -23,15 +23,12 @@ #include #include +#include #include #include #include #include -#if defined(PW_RPC_ENABLED) -#include -#endif - using namespace ::chip; using namespace ::chip::Controller; @@ -547,6 +544,8 @@ void PairingManager::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E PairingManager * self = reinterpret_cast(context); VerifyOrReturn(self != nullptr, ChipLogError(NotSpecified, "OnCurrentFabricRemove: context is null")); + ChipLogProgress(NotSpecified, "PairingManager::OnCurrentFabricRemove"); + if (err == CHIP_NO_ERROR) { // print to console @@ -558,12 +557,10 @@ void PairingManager::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E self->SetPairingDelegate(nullptr); } -#if defined(PW_RPC_ENABLED) FabricIndex fabricIndex = self->CurrentCommissioner().GetFabricIndex(); app::InteractionModelEngine::GetInstance()->ShutdownSubscriptions(fabricIndex, nodeId); ScopedNodeId scopedNodeId(nodeId, fabricIndex); - RemoveSynchronizedDevice(scopedNodeId); -#endif + DeviceMgr().RemoveSyncedDevice(scopedNodeId); } else { diff --git a/examples/fabric-sync/admin/DeviceManager.cpp b/examples/fabric-sync/admin/DeviceManager.cpp index 814b7f39356c9d..5c41bbb56f7b83 100644 --- a/examples/fabric-sync/admin/DeviceManager.cpp +++ b/examples/fabric-sync/admin/DeviceManager.cpp @@ -143,16 +143,4 @@ CHIP_ERROR DeviceManager::UnpairRemoteDevice(NodeId nodeId) return CHIP_NO_ERROR; } -void DeviceManager::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR err) -{ - if (err != CHIP_NO_ERROR) - { - ChipLogError(NotSpecified, "Failed to remove synced device:(" ChipLogFormatX64 ") with error: %" CHIP_ERROR_FORMAT, - ChipLogValueX64(deviceId), err.Format()); - return; - } - - ChipLogProgress(NotSpecified, "Synced device with NodeId:" ChipLogFormatX64 " has been removed.", ChipLogValueX64(deviceId)); -} - } // namespace admin diff --git a/examples/fabric-sync/admin/DeviceManager.h b/examples/fabric-sync/admin/DeviceManager.h index 57a3bd300af2e8..db6ad9b528ade4 100644 --- a/examples/fabric-sync/admin/DeviceManager.h +++ b/examples/fabric-sync/admin/DeviceManager.h @@ -25,7 +25,7 @@ namespace admin { -class DeviceManager : public PairingDelegate +class DeviceManager { public: DeviceManager() = default; @@ -119,8 +119,6 @@ class DeviceManager : public PairingDelegate private: friend DeviceManager & DeviceMgr(); - void OnDeviceRemoved(chip::NodeId deviceId, CHIP_ERROR err) override; - static DeviceManager sInstance; chip::NodeId mLastUsedNodeId = 0; diff --git a/examples/fabric-sync/admin/PairingManager.cpp b/examples/fabric-sync/admin/PairingManager.cpp index 6b5f707d0c2132..a3f4af43dafd84 100644 --- a/examples/fabric-sync/admin/PairingManager.cpp +++ b/examples/fabric-sync/admin/PairingManager.cpp @@ -450,6 +450,8 @@ void PairingManager::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E PairingManager * self = reinterpret_cast(context); VerifyOrReturn(self != nullptr, ChipLogError(NotSpecified, "OnCurrentFabricRemove: context is null")); + ChipLogProgress(NotSpecified, "PairingManager::OnCurrentFabricRemove"); + if (err == CHIP_NO_ERROR) { // print to console From 5ace630fa163da3c1154f8b34f86effc71ccc2e9 Mon Sep 17 00:00:00 2001 From: Yuanyao Zhong <82843247+yyzhong-g@users.noreply.github.com> Date: Fri, 8 Nov 2024 02:56:43 -0500 Subject: [PATCH 099/121] Add a helper function to allow ErrorStr not using static char array (#36391) * Add a helper function to allow ErrorStr does not rely on static char array * Use dedicated storage for ErrorStr and add unit tests * Restyled by whitespace * Restyled by clang-format * remove size() --------- Co-authored-by: Restyled.io --- src/lib/core/ErrorStr.cpp | 43 ++++++---- src/lib/core/ErrorStr.h | 7 ++ src/lib/core/tests/TestCHIPErrorStr.cpp | 104 ++++++++++++++++-------- src/lib/support/tests/TestErrorStr.cpp | 7 ++ 4 files changed, 113 insertions(+), 48 deletions(-) diff --git a/src/lib/core/ErrorStr.cpp b/src/lib/core/ErrorStr.cpp index 6d83bc015b21d2..b3cf968c674dd5 100644 --- a/src/lib/core/ErrorStr.cpp +++ b/src/lib/core/ErrorStr.cpp @@ -29,7 +29,7 @@ namespace chip { /** * Static buffer to store the formatted error string. */ -static char sErrorStr[CHIP_CONFIG_ERROR_STR_SIZE]; +static ErrorStrStorage sErrorStr; /** * Linked-list of error formatter functions. @@ -38,7 +38,7 @@ static ErrorFormatter * sErrorFormatterList = nullptr; /** * This routine returns a human-readable NULL-terminated C string - * describing the provided error. + * describing the provided error. This uses the global static storage. * * @param[in] err The error for format and describe. * @param[in] withSourceLocation Whether or not to include the source @@ -50,8 +50,26 @@ static ErrorFormatter * sErrorFormatterList = nullptr; */ DLL_EXPORT const char * ErrorStr(CHIP_ERROR err, bool withSourceLocation) { - char * formattedError = sErrorStr; - uint16_t formattedSpace = sizeof(sErrorStr); + return ErrorStr(err, withSourceLocation, sErrorStr); +} + +/** + * This routine writess a human-readable NULL-terminated C string into the buf + * which describes the provided error. + * + * @param[in] err The error for format and describe. + * @param[in] withSourceLocation Whether or not to include the source + * @param[in] storage ErrorStrStorage to write into + * location in the output string. Only used if CHIP_CONFIG_ERROR_SOURCE && + * !CHIP_CONFIG_SHORT_ERROR_STR. Defaults to true. + * + * @return A pointer to a NULL-terminated C string describing the + * provided error. + */ +DLL_EXPORT const char * ErrorStr(CHIP_ERROR err, bool withSourceLocation, ErrorStrStorage & storage) +{ + char * formattedError = storage.buff; + uint16_t formattedSpace = storage.kBufferSize; #if CHIP_CONFIG_ERROR_SOURCE && !CHIP_CONFIG_SHORT_ERROR_STR @@ -65,34 +83,27 @@ DLL_EXPORT const char * ErrorStr(CHIP_ERROR err, bool withSourceLocation) formattedError += n; formattedSpace = static_cast(formattedSpace - n); } - if (err == CHIP_NO_ERROR) - { - (void) snprintf(formattedError, formattedSpace, CHIP_NO_ERROR_STRING); - return sErrorStr; - } - -#else // CHIP_CONFIG_ERROR_SOURCE && !CHIP_CONFIG_SHORT_ERROR_STR +#endif // CHIP_CONFIG_ERROR_SOURCE && !CHIP_CONFIG_SHORT_ERROR_STR if (err == CHIP_NO_ERROR) { - return CHIP_NO_ERROR_STRING; + (void) snprintf(formattedError, formattedSpace, CHIP_NO_ERROR_STRING); + return storage.buff; } -#endif // CHIP_CONFIG_ERROR_SOURCE && !CHIP_CONFIG_SHORT_ERROR_STR - // Search the registered error formatter for one that will format the given // error code. for (const ErrorFormatter * errFormatter = sErrorFormatterList; errFormatter != nullptr; errFormatter = errFormatter->Next) { if (errFormatter->FormatError(formattedError, formattedSpace, err)) { - return sErrorStr; + return storage.buff; } } // Use a default formatting if no formatter found. FormatError(formattedError, formattedSpace, nullptr, err, nullptr); - return sErrorStr; + return storage.buff; } /** diff --git a/src/lib/core/ErrorStr.h b/src/lib/core/ErrorStr.h index d67680c2151b1e..f1365a6bfb25f3 100644 --- a/src/lib/core/ErrorStr.h +++ b/src/lib/core/ErrorStr.h @@ -48,7 +48,14 @@ struct ErrorFormatter ErrorFormatter * Next; }; +struct ErrorStrStorage +{ + char buff[CHIP_CONFIG_ERROR_STR_SIZE]; + constexpr static uint16_t kBufferSize = sizeof(buff); +}; + extern const char * ErrorStr(CHIP_ERROR err, bool withSourceLocation = true); +extern const char * ErrorStr(CHIP_ERROR err, bool withSourceLocation, ErrorStrStorage & storage); extern void RegisterErrorFormatter(ErrorFormatter * errFormatter); extern void DeregisterErrorFormatter(ErrorFormatter * errFormatter); extern void FormatError(char * buf, uint16_t bufSize, const char * subsys, CHIP_ERROR err, const char * desc); diff --git a/src/lib/core/tests/TestCHIPErrorStr.cpp b/src/lib/core/tests/TestCHIPErrorStr.cpp index 01130aca4261d7..1ce158cc8594ae 100644 --- a/src/lib/core/tests/TestCHIPErrorStr.cpp +++ b/src/lib/core/tests/TestCHIPErrorStr.cpp @@ -170,6 +170,31 @@ static const CHIP_ERROR kTestElements[] = }; // clang-format on +void CheckCoreErrorStrHelper(const char * errStr, CHIP_ERROR err) +{ + char expectedText[9]; + + // Assert that the error string contains the error number in hex. + snprintf(expectedText, sizeof(expectedText), "%08" PRIX32, static_cast(err.AsInteger())); + EXPECT_TRUE((strstr(errStr, expectedText) != nullptr)); + +#if !CHIP_CONFIG_SHORT_ERROR_STR + // Assert that the error string contains a description, which is signaled + // by a presence of a colon proceeding the description. + EXPECT_TRUE((strchr(errStr, ':') != nullptr)); +#endif // !CHIP_CONFIG_SHORT_ERROR_STR + +#if CHIP_CONFIG_ERROR_SOURCE + // GetFile() should be relative to ${chip_root} + char const * const file = err.GetFile(); + ASSERT_NE(file, nullptr); + EXPECT_EQ(strstr(file, "src/lib/core/"), file); + + // File should be included in the error. + EXPECT_NE(strstr(errStr, file), nullptr); +#endif // CHIP_CONFIG_ERROR_SOURCE +} + TEST(TestCHIPErrorStr, CheckCoreErrorStr) { // Register the layer error formatter @@ -179,29 +204,46 @@ TEST(TestCHIPErrorStr, CheckCoreErrorStr) // For each defined error... for (const auto & err : kTestElements) { - const char * errStr = ErrorStr(err); - char expectedText[9]; + // ErrorStr with static char array. + CheckCoreErrorStrHelper(ErrorStr(err, /*withSourceLocation=*/true), err); + } +} + +TEST(TestCHIPErrorStr, CheckCoreErrorStrStorage) +{ + // Register the layer error formatter + + RegisterCHIPLayerErrorFormatter(); + + // For each defined error... + for (const auto & err : kTestElements) + { + // ErrorStr with given storage. + ErrorStrStorage storage; + CheckCoreErrorStrHelper(ErrorStr(err, /*withSourceLocation=*/true, storage), err); + } +} + +void CheckCoreErrorStrWithoutSourceLocationHelper(const char * errStr, CHIP_ERROR err) +{ + char expectedText[9]; - // Assert that the error string contains the error number in hex. - snprintf(expectedText, sizeof(expectedText), "%08" PRIX32, static_cast(err.AsInteger())); - EXPECT_TRUE((strstr(errStr, expectedText) != nullptr)); + // Assert that the error string contains the error number in hex. + snprintf(expectedText, sizeof(expectedText), "%08" PRIX32, static_cast(err.AsInteger())); + EXPECT_TRUE((strstr(errStr, expectedText) != nullptr)); #if !CHIP_CONFIG_SHORT_ERROR_STR - // Assert that the error string contains a description, which is signaled - // by a presence of a colon proceeding the description. - EXPECT_TRUE((strchr(errStr, ':') != nullptr)); + // Assert that the error string contains a description, which is signaled + // by a presence of a colon proceeding the description. + EXPECT_TRUE((strchr(errStr, ':') != nullptr)); #endif // !CHIP_CONFIG_SHORT_ERROR_STR #if CHIP_CONFIG_ERROR_SOURCE - // GetFile() should be relative to ${chip_root} - char const * const file = err.GetFile(); - ASSERT_NE(file, nullptr); - EXPECT_EQ(strstr(file, "src/lib/core/"), file); - - // File should be included in the error. - EXPECT_NE(strstr(errStr, file), nullptr); + char const * const file = err.GetFile(); + ASSERT_NE(file, nullptr); + // File should not be included in the error. + EXPECT_EQ(strstr(errStr, file), nullptr); #endif // CHIP_CONFIG_ERROR_SOURCE - } } TEST(TestCHIPErrorStr, CheckCoreErrorStrWithoutSourceLocation) @@ -213,24 +255,22 @@ TEST(TestCHIPErrorStr, CheckCoreErrorStrWithoutSourceLocation) // For each defined error... for (const auto & err : kTestElements) { - const char * errStr = ErrorStr(err, /*withSourceLocation=*/false); - char expectedText[9]; + // ErrorStr with static char array. + CheckCoreErrorStrWithoutSourceLocationHelper(ErrorStr(err, /*withSourceLocation=*/false), err); + } +} - // Assert that the error string contains the error number in hex. - snprintf(expectedText, sizeof(expectedText), "%08" PRIX32, static_cast(err.AsInteger())); - EXPECT_TRUE((strstr(errStr, expectedText) != nullptr)); +TEST(TestCHIPErrorStr, CheckCoreErrorStrStorageWithoutSourceLocation) +{ + // Register the layer error formatter -#if !CHIP_CONFIG_SHORT_ERROR_STR - // Assert that the error string contains a description, which is signaled - // by a presence of a colon proceeding the description. - EXPECT_TRUE((strchr(errStr, ':') != nullptr)); -#endif // !CHIP_CONFIG_SHORT_ERROR_STR + RegisterCHIPLayerErrorFormatter(); -#if CHIP_CONFIG_ERROR_SOURCE - char const * const file = err.GetFile(); - ASSERT_NE(file, nullptr); - // File should not be included in the error. - EXPECT_EQ(strstr(errStr, file), nullptr); -#endif // CHIP_CONFIG_ERROR_SOURCE + // For each defined error... + for (const auto & err : kTestElements) + { + // ErrorStr with given storage. + ErrorStrStorage storage; + CheckCoreErrorStrWithoutSourceLocationHelper(ErrorStr(err, /*withSourceLocation=*/false, storage), err); } } diff --git a/src/lib/support/tests/TestErrorStr.cpp b/src/lib/support/tests/TestErrorStr.cpp index 809d69b302af0b..ac8a9f5e9e3469 100644 --- a/src/lib/support/tests/TestErrorStr.cpp +++ b/src/lib/support/tests/TestErrorStr.cpp @@ -121,6 +121,13 @@ TEST(TestErrorStr, CheckNoError) EXPECT_STREQ(CHECK_AND_SKIP_SOURCE(ErrorStr(CHIP_NO_ERROR)), CHIP_NO_ERROR_STRING); } +TEST(TestErrorStr, CheckErrorWithProvidedStorage) +{ + ErrorStrStorage storage; + EXPECT_STREQ(CHECK_AND_SKIP_SOURCE(ErrorStr(CHIP_NO_ERROR, true, storage)), CHIP_NO_ERROR_STRING); + EXPECT_STREQ(CHECK_AND_SKIP_SOURCE(ErrorStr(CHIP_ERROR_INTERNAL, true, storage)), "Error 0x000000AC"); +} + TEST(TestErrorStr, CheckFormatErr) { #if CHIP_CONFIG_SHORT_ERROR_STR From cf501156f47c88ceae301993d479eb0b14aeebe4 Mon Sep 17 00:00:00 2001 From: Erwin Pan Date: Fri, 8 Nov 2024 22:09:58 +0800 Subject: [PATCH 100/121] Fix Chef MaxMeasuredValue of PressureMeasurement (#36434) --- .../chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter | 2 +- examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.zap | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter b/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter index 43e8de7b5f4ee1..1bc2e8726e1083 100644 --- a/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter +++ b/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.matter @@ -1845,7 +1845,7 @@ endpoint 1 { server cluster PressureMeasurement { ram attribute measuredValue default = 0xA; ram attribute minMeasuredValue default = 1; - ram attribute maxMeasuredValue default = 0xfffe; + ram attribute maxMeasuredValue default = 32767; callback attribute generatedCommandList; callback attribute acceptedCommandList; callback attribute attributeList; diff --git a/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.zap b/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.zap index 3131dca9c5d00d..f473e3dc7eb5d1 100644 --- a/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.zap +++ b/examples/chef/devices/rootnode_pressuresensor_s0qC9wLH4k.zap @@ -2721,7 +2721,7 @@ "storageOption": "RAM", "singleton": 0, "bounded": 0, - "defaultValue": "0xfffe", + "defaultValue": "32767", "reportable": 1, "minInterval": 1, "maxInterval": 65534, @@ -2830,4 +2830,4 @@ "parentEndpointIdentifier": null } ] -} \ No newline at end of file +} From 18c0788a89b0fa3474efc306cb4e079bf32489fe Mon Sep 17 00:00:00 2001 From: andrei-menzopol <96489227+andrei-menzopol@users.noreply.github.com> Date: Fri, 8 Nov 2024 16:25:56 +0200 Subject: [PATCH 101/121] [nxp][platform][mcxw71_k32w1] Update low-power define (#36431) Signed-off-by: Andrei Menzopol --- src/platform/nxp/mcxw71_k32w1/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/platform/nxp/mcxw71_k32w1/BUILD.gn b/src/platform/nxp/mcxw71_k32w1/BUILD.gn index 9de3c0e5b3c7e0..865475d1e43e22 100644 --- a/src/platform/nxp/mcxw71_k32w1/BUILD.gn +++ b/src/platform/nxp/mcxw71_k32w1/BUILD.gn @@ -89,7 +89,7 @@ config("nxp_platform_config") { static_library("nxp_platform") { deps = [] defines = [ - "CHIP_DEVICE_K32W1=1", + "NXP_DEVICE_K32W1_MCXW7X=1", "NXP_USE_MML=1", ] From 0d68788664dab1afe9a917c8b05bbcab71f869be Mon Sep 17 00:00:00 2001 From: Arkadiusz Bokowy Date: Fri, 8 Nov 2024 17:30:59 +0100 Subject: [PATCH 102/121] Stop main event loop when shell prompt exits (#36433) * Stop main event loop when shell prompt exits * Do not call platform manager shutdown twice * Prevent double free in case Shutdown is called twice --- examples/fabric-sync/shell/ShellCommands.cpp | 1 - examples/platform/linux/AppMain.cpp | 35 ++++++++++++------- .../CHIPDeviceControllerSystemState.h | 2 +- src/platform/Linux/PlatformManagerImpl.cpp | 10 ++++-- 4 files changed, 30 insertions(+), 18 deletions(-) diff --git a/examples/fabric-sync/shell/ShellCommands.cpp b/examples/fabric-sync/shell/ShellCommands.cpp index a654fbcc9f98f1..fa859a34d5261e 100644 --- a/examples/fabric-sync/shell/ShellCommands.cpp +++ b/examples/fabric-sync/shell/ShellCommands.cpp @@ -216,7 +216,6 @@ void RegisterCommands() // Register the root `device` command with the top-level shell. Engine::Root().RegisterCommands(&sDeviceComand, 1); - return; } } // namespace Shell diff --git a/examples/platform/linux/AppMain.cpp b/examples/platform/linux/AppMain.cpp index d18c3106cf5f20..e3b68e319e634e 100644 --- a/examples/platform/linux/AppMain.cpp +++ b/examples/platform/linux/AppMain.cpp @@ -301,6 +301,19 @@ void EventHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg) } } +void StopMainEventLoop() +{ + if (gMainLoopImplementation != nullptr) + { + gMainLoopImplementation->SignalSafeStopMainLoop(); + } + else + { + Server::GetInstance().GenerateShutDownEvent(); + PlatformMgr().ScheduleWork([](intptr_t) { PlatformMgr().StopEventLoopTask(); }); + } +} + void Cleanup() { #if CHIP_CONFIG_TRANSPORT_TRACE_ENABLED @@ -317,17 +330,9 @@ void Cleanup() // We should stop using signals for those faults, and move to a different notification // means, like a pipe. (see issue #19114) #if !defined(ENABLE_CHIP_SHELL) -void StopSignalHandler(int signal) +void StopSignalHandler(int /* signal */) { - if (gMainLoopImplementation != nullptr) - { - gMainLoopImplementation->SignalSafeStopMainLoop(); - } - else - { - Server::GetInstance().GenerateShutDownEvent(); - PlatformMgr().ScheduleWork([](intptr_t) { PlatformMgr().StopEventLoopTask(); }); - } + StopMainEventLoop(); } #endif // !defined(ENABLE_CHIP_SHELL) @@ -530,7 +535,10 @@ void ChipLinuxAppMainLoop(AppMainLoopImplementation * impl) #if defined(ENABLE_CHIP_SHELL) Engine::Root().Init(); - std::thread shellThread([]() { Engine::Root().RunMainLoop(); }); + std::thread shellThread([]() { + Engine::Root().RunMainLoop(); + StopMainEventLoop(); + }); Shell::RegisterCommissioneeCommands(); #endif initParams.operationalServicePort = CHIP_PORT; @@ -692,14 +700,15 @@ void ChipLinuxAppMainLoop(AppMainLoopImplementation * impl) Server::GetInstance().Shutdown(); #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE + // Commissioner shutdown call shuts down entire stack, including the platform manager. ShutdownCommissioner(); +#else + DeviceLayer::PlatformMgr().Shutdown(); #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE #if ENABLE_TRACING tracing_setup.StopTracing(); #endif - DeviceLayer::PlatformMgr().Shutdown(); - Cleanup(); } diff --git a/src/controller/CHIPDeviceControllerSystemState.h b/src/controller/CHIPDeviceControllerSystemState.h index e040ad14616431..0a6476ff38e49f 100644 --- a/src/controller/CHIPDeviceControllerSystemState.h +++ b/src/controller/CHIPDeviceControllerSystemState.h @@ -201,7 +201,7 @@ class DeviceControllerSystemState // // The stack will shut down when all references are released. // - // NB: The system state is owned by the factory; Relase() will not free it + // NB: The system state is owned by the factory; Release() will not free it // but will free its members (Shutdown()). // // Returns true if the system state was shut down in response to this call. diff --git a/src/platform/Linux/PlatformManagerImpl.cpp b/src/platform/Linux/PlatformManagerImpl.cpp index dba3cb447d30d8..ce33209e7429ac 100644 --- a/src/platform/Linux/PlatformManagerImpl.cpp +++ b/src/platform/Linux/PlatformManagerImpl.cpp @@ -274,9 +274,13 @@ void PlatformManagerImpl::_Shutdown() Internal::GenericPlatformManagerImpl_POSIX::_Shutdown(); #if CHIP_DEVICE_CONFIG_WITH_GLIB_MAIN_LOOP - g_main_loop_quit(mGLibMainLoop); - g_thread_join(mGLibMainLoopThread); - g_main_loop_unref(mGLibMainLoop); + if (mGLibMainLoop != nullptr) + { + g_main_loop_quit(mGLibMainLoop); + g_thread_join(mGLibMainLoopThread); + g_main_loop_unref(mGLibMainLoop); + mGLibMainLoop = nullptr; + } #endif } From 86fd3f3b903589fb6aec07770933f0523c0e246a Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Fri, 8 Nov 2024 13:17:26 -0500 Subject: [PATCH 103/121] Place reporting reads and cluster version compares back in Engine.cpp (#36438) * Move back reporting engine code now that separate implementations are not needed * Restyle * Remove comment that does not seem to make sense * Update one more ifdef surround: if no extra logging, remove a larger code chunk * Remove one more file reference --------- Co-authored-by: Andrei Litvin --- src/app/BUILD.gn | 3 - src/app/reporting/Engine.cpp | 92 +++++++++++++++++++++++++-- src/app/reporting/Read.cpp | 116 ----------------------------------- src/app/reporting/Read.h | 41 ------------- 4 files changed, 86 insertions(+), 166 deletions(-) delete mode 100644 src/app/reporting/Read.cpp delete mode 100644 src/app/reporting/Read.h diff --git a/src/app/BUILD.gn b/src/app/BUILD.gn index 5fc0d0c8b97583..28179390cfa8dc 100644 --- a/src/app/BUILD.gn +++ b/src/app/BUILD.gn @@ -186,7 +186,6 @@ static_library("interaction-model") { "WriteClient.h", "reporting/Engine.cpp", "reporting/Engine.h", - "reporting/Read.h", "reporting/ReportScheduler.h", "reporting/ReportSchedulerImpl.cpp", "reporting/ReportSchedulerImpl.h", @@ -199,8 +198,6 @@ static_library("interaction-model") { # # This breaks having `.h` and `.cpp` based off the same compilation unit and # should ideally be cleaned up. - "reporting/Read.cpp", - "reporting/Read.h", "reporting/reporting.h", ] diff --git a/src/app/reporting/Engine.cpp b/src/app/reporting/Engine.cpp index 284aa6fa66db06..ea4c0014e71397 100644 --- a/src/app/reporting/Engine.cpp +++ b/src/app/reporting/Engine.cpp @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -53,6 +52,87 @@ Status EventPathValid(DataModel::Provider * model, const ConcreteEventPath & eve return Status::Success; } +DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, + const Access::SubjectDescriptor & subjectDescriptor, bool isFabricFiltered, + AttributeReportIBs::Builder & reportBuilder, + const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState) +{ + ChipLogDetail(DataManagement, " Cluster %" PRIx32 ", Attribute %" PRIx32 " is dirty", path.mClusterId, + path.mAttributeId); + DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, + DataModelCallbacks::OperationOrder::Pre, path); + + DataModel::ReadAttributeRequest readRequest; + + if (isFabricFiltered) + { + readRequest.readFlags.Set(DataModel::ReadFlags::kFabricFiltered); + } + readRequest.subjectDescriptor = &subjectDescriptor; + readRequest.path = path; + + DataVersion version = 0; + if (std::optional clusterInfo = dataModel->GetClusterInfo(path); clusterInfo.has_value()) + { + version = clusterInfo->dataVersion; + } + else + { + ChipLogError(DataManagement, "Read request on unknown cluster - no data version available"); + } + + TLV::TLVWriter checkpoint; + reportBuilder.Checkpoint(checkpoint); + + AttributeValueEncoder attributeValueEncoder(reportBuilder, subjectDescriptor, path, version, isFabricFiltered, encoderState); + + DataModel::ActionReturnStatus status = dataModel->ReadAttribute(readRequest, attributeValueEncoder); + + if (status.IsSuccess()) + { + // TODO: this callback being only executed on success is awkward. The Write callback is always done + // for both read and write. + // + // For now this preserves existing/previous code logic, however we should consider to ALWAYS + // call this. + DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, + DataModelCallbacks::OperationOrder::Post, path); + return status; + } + + // Encoder state is relevant for errors in case they are retryable. + // + // Generally only out of space encoding errors would be retryable, however we save the state + // for all errors in case this is information that is useful (retry or error position). + if (encoderState != nullptr) + { + *encoderState = attributeValueEncoder.GetState(); + } + +#if CHIP_CONFIG_DATA_MODEL_EXTRA_LOGGING + // Out of space errors may be chunked data, reporting those cases would be very confusing + // as they are not fully errors. Report only others (which presumably are not recoverable + // and will be sent to the client as well). + if (!status.IsOutOfSpaceEncodingResponse()) + { + DataModel::ActionReturnStatus::StringStorage storage; + ChipLogError(DataManagement, "Failed to read attribute: %s", status.c_str(storage)); + } +#endif + return status; +} + +bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const ConcreteClusterPath & path, DataVersion dataVersion) +{ + std::optional info = dataModel->GetClusterInfo(path); + if (!info.has_value()) + { + return false; + } + + return (info->dataVersion == dataVersion); +} + } // namespace Engine::Engine(InteractionModelEngine * apImEngine) : mpImEngine(apImEngine) {} @@ -85,9 +165,9 @@ bool Engine::IsClusterDataVersionMatch(const SingleLinkedListNodeGetDataModelProvider(), - ConcreteClusterPath(filter->mValue.mEndpointId, filter->mValue.mClusterId), - filter->mValue.mDataVersion.Value())) + if (!IsClusterDataVersionEqualTo(mpImEngine->GetDataModelProvider(), + ConcreteClusterPath(filter->mValue.mEndpointId, filter->mValue.mClusterId), + filter->mValue.mDataVersion.Value())) { existVersionMismatch = true; } @@ -199,8 +279,8 @@ CHIP_ERROR Engine::BuildSingleReportDataAttributeReportIBs(ReportDataMessage::Bu // Load the saved state from previous encoding session for chunking of one single attribute (list chunking). AttributeEncodeState encodeState = apReadHandler->GetAttributeEncodeState(); DataModel::ActionReturnStatus status = - Impl::RetrieveClusterData(mpImEngine->GetDataModelProvider(), apReadHandler->GetSubjectDescriptor(), - apReadHandler->IsFabricFiltered(), attributeReportIBs, pathForRetrieval, &encodeState); + RetrieveClusterData(mpImEngine->GetDataModelProvider(), apReadHandler->GetSubjectDescriptor(), + apReadHandler->IsFabricFiltered(), attributeReportIBs, pathForRetrieval, &encodeState); if (status.IsError()) { // Operation error set, since this will affect early return or override on status encoding diff --git a/src/app/reporting/Read.cpp b/src/app/reporting/Read.cpp deleted file mode 100644 index db55b14cd257b3..00000000000000 --- a/src/app/reporting/Read.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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 - -#include -#include -#include -#include -#include -#include - -namespace chip { -namespace app { -namespace reporting { -namespace Impl { - -DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, - const Access::SubjectDescriptor & subjectDescriptor, bool isFabricFiltered, - AttributeReportIBs::Builder & reportBuilder, - const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState) -{ - ChipLogDetail(DataManagement, " Cluster %" PRIx32 ", Attribute %" PRIx32 " is dirty", path.mClusterId, - path.mAttributeId); - DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, - DataModelCallbacks::OperationOrder::Pre, path); - - DataModel::ReadAttributeRequest readRequest; - - if (isFabricFiltered) - { - readRequest.readFlags.Set(DataModel::ReadFlags::kFabricFiltered); - } - readRequest.subjectDescriptor = &subjectDescriptor; - readRequest.path = path; - - DataVersion version = 0; - if (std::optional clusterInfo = dataModel->GetClusterInfo(path); clusterInfo.has_value()) - { - version = clusterInfo->dataVersion; - } - else - { - ChipLogError(DataManagement, "Read request on unknown cluster - no data version available"); - } - - TLV::TLVWriter checkpoint; - reportBuilder.Checkpoint(checkpoint); - - AttributeValueEncoder attributeValueEncoder(reportBuilder, subjectDescriptor, path, version, isFabricFiltered, encoderState); - - DataModel::ActionReturnStatus status = dataModel->ReadAttribute(readRequest, attributeValueEncoder); - - if (status.IsSuccess()) - { - // Odd ifdef is to only do this if the `Read-Check` does not do it already. - // TODO: this callback being only executed on success is awkward. The Write callback is always done - // for both read and write. - // - // For now this preserves existing/previous code logic, however we should consider to ALWAYS - // call this. - DataModelCallbacks::GetInstance()->AttributeOperation(DataModelCallbacks::OperationType::Read, - DataModelCallbacks::OperationOrder::Post, path); - return status; - } - - // Encoder state is relevant for errors in case they are retryable. - // - // Generally only out of space encoding errors would be retryable, however we save the state - // for all errors in case this is information that is useful (retry or error position). - if (encoderState != nullptr) - { - *encoderState = attributeValueEncoder.GetState(); - } - - // Out of space errors may be chunked data, reporting those cases would be very confusing - // as they are not fully errors. Report only others (which presumably are not recoverable - // and will be sent to the client as well). - if (!status.IsOutOfSpaceEncodingResponse()) - { - DataModel::ActionReturnStatus::StringStorage storage; -#if CHIP_CONFIG_DATA_MODEL_EXTRA_LOGGING - ChipLogError(DataManagement, "Failed to read attribute: %s", status.c_str(storage)); -#endif - } - return status; -} - -bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const ConcreteClusterPath & path, DataVersion dataVersion) -{ - std::optional info = dataModel->GetClusterInfo(path); - if (!info.has_value()) - { - return false; - } - - return (info->dataVersion == dataVersion); -} - -} // namespace Impl -} // namespace reporting -} // namespace app -} // namespace chip diff --git a/src/app/reporting/Read.h b/src/app/reporting/Read.h deleted file mode 100644 index 6731addfab736e..00000000000000 --- a/src/app/reporting/Read.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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. - */ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace chip { -namespace app { -namespace reporting { -namespace Impl { - -DataModel::ActionReturnStatus RetrieveClusterData(DataModel::Provider * dataModel, - const Access::SubjectDescriptor & subjectDescriptor, bool isFabricFiltered, - AttributeReportIBs::Builder & reportBuilder, - const ConcreteReadAttributePath & path, AttributeEncodeState * encoderState); - -bool IsClusterDataVersionEqualTo(DataModel::Provider * dataModel, const ConcreteClusterPath & path, DataVersion dataVersion); -} // namespace Impl - -} // namespace reporting -} // namespace app -} // namespace chip From 58b576763e6a72da54f37da915ee6c3433567801 Mon Sep 17 00:00:00 2001 From: Junior Martinez <67972863+jmartinez-silabs@users.noreply.github.com> Date: Fri, 8 Nov 2024 16:07:44 -0500 Subject: [PATCH 104/121] [Silabs ]Fix some build conditions for apps with matter shell enabled (#36442) * Skip the OpenThread API call for WiFi builds Co-authored-by: Sergei Lissianoi * address comment * address comment --------- Co-authored-by: Sergei Lissianoi <54454955+selissia@users.noreply.github.com> Co-authored-by: Sergei Lissianoi --- examples/platform/silabs/uart.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/platform/silabs/uart.cpp b/examples/platform/silabs/uart.cpp index 6ef768ac652e19..c460554c6afc57 100644 --- a/examples/platform/silabs/uart.cpp +++ b/examples/platform/silabs/uart.cpp @@ -364,7 +364,7 @@ void USART_IRQHandler(void) { #ifdef ENABLE_CHIP_SHELL chip::NotifyShellProcess(); -#elif !defined(PW_RPC_ENABLED) && !defined(SL_WIFI) +#elif !defined(PW_RPC_ENABLED) && CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI otSysEventSignalPending(); #endif #ifdef SL_CATALOG_UARTDRV_EUSART_PRESENT @@ -411,7 +411,7 @@ static void UART_rx_callback(UARTDRV_Handle_t handle, Ecode_t transferStatus, ui #ifdef ENABLE_CHIP_SHELL chip::NotifyShellProcess(); -#elif !defined(PW_RPC_ENABLED) +#elif !defined(PW_RPC_ENABLED) && CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI otSysEventSignalPending(); #endif } From 8a3fce1949cb2a8860525492d6e916af1fa70ec6 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Fri, 8 Nov 2024 17:57:36 -0800 Subject: [PATCH 105/121] Use Meyers' Singleton pattern for DeviceManager (#36439) --- .../fabric-sync/FabricSyncCommand.cpp | 49 ++++++++++--------- .../commands/pairing/PairingCommand.cpp | 2 +- .../device_manager/BridgeSubscription.cpp | 4 +- .../device_manager/CommissionerControl.cpp | 2 +- .../device_manager/DeviceManager.cpp | 3 -- .../device_manager/DeviceManager.h | 23 +++------ .../DeviceSubscriptionManager.cpp | 6 --- .../DeviceSubscriptionManager.h | 6 ++- .../device_manager/DeviceSynchronization.cpp | 8 +-- .../device_manager/PairingManager.cpp | 2 +- examples/fabric-admin/main.cpp | 2 +- examples/fabric-admin/rpc/RpcServer.cpp | 10 ++-- 12 files changed, 51 insertions(+), 66 deletions(-) diff --git a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp index 355b704c2ee654..315bf2f3711f35 100644 --- a/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp +++ b/examples/fabric-admin/commands/fabric-sync/FabricSyncCommand.cpp @@ -51,14 +51,14 @@ void FabricSyncAddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_E if (err == CHIP_NO_ERROR) { - DeviceMgr().SetRemoteBridgeNodeId(mBridgeNodeId); + DeviceManager::Instance().SetRemoteBridgeNodeId(mBridgeNodeId); ChipLogProgress(NotSpecified, "Successfully paired bridge device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mBridgeNodeId)); - DeviceMgr().UpdateLastUsedNodeId(mBridgeNodeId); - DeviceMgr().SubscribeRemoteFabricBridge(); + DeviceManager::Instance().UpdateLastUsedNodeId(mBridgeNodeId); + DeviceManager::Instance().SubscribeRemoteFabricBridge(); - if (DeviceMgr().IsLocalBridgeReady()) + if (DeviceManager::Instance().IsLocalBridgeReady()) { // After successful commissioning of the Commissionee, initiate Reverse Commissioning // via the Commissioner Control Cluster. However, we must first verify that the @@ -66,7 +66,7 @@ void FabricSyncAddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_E // // Note: The Fabric-Admin MUST NOT send the RequestCommissioningApproval command // if the remote Fabric-Bridge lacks Fabric Synchronization support. - DeviceLayer::SystemLayer().ScheduleLambda([]() { DeviceMgr().ReadSupportedDeviceCategories(); }); + DeviceLayer::SystemLayer().ScheduleLambda([]() { DeviceManager::Instance().ReadSupportedDeviceCategories(); }); } } else @@ -80,7 +80,7 @@ void FabricSyncAddBridgeCommand::OnCommissioningComplete(NodeId deviceId, CHIP_E CHIP_ERROR FabricSyncAddBridgeCommand::RunCommand(NodeId remoteId) { - if (DeviceMgr().IsFabricSyncReady()) + if (DeviceManager::Instance().IsFabricSyncReady()) { // print to console fprintf(stderr, "Remote Fabric Bridge has already been configured.\n"); @@ -91,7 +91,8 @@ CHIP_ERROR FabricSyncAddBridgeCommand::RunCommand(NodeId remoteId) mBridgeNodeId = remoteId; - DeviceMgr().PairRemoteFabricBridge(remoteId, mSetupPINCode, reinterpret_cast(mRemoteAddr.data()), mRemotePort); + DeviceManager::Instance().PairRemoteFabricBridge(remoteId, mSetupPINCode, reinterpret_cast(mRemoteAddr.data()), + mRemotePort); return CHIP_NO_ERROR; } @@ -106,7 +107,7 @@ void FabricSyncRemoveBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR if (err == CHIP_NO_ERROR) { - DeviceMgr().SetRemoteBridgeNodeId(kUndefinedNodeId); + DeviceManager::Instance().SetRemoteBridgeNodeId(kUndefinedNodeId); ChipLogProgress(NotSpecified, "Successfully removed bridge device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mBridgeNodeId)); } @@ -121,7 +122,7 @@ void FabricSyncRemoveBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_ERROR CHIP_ERROR FabricSyncRemoveBridgeCommand::RunCommand() { - NodeId bridgeNodeId = DeviceMgr().GetRemoteBridgeNodeId(); + NodeId bridgeNodeId = DeviceManager::Instance().GetRemoteBridgeNodeId(); if (bridgeNodeId == kUndefinedNodeId) { @@ -133,7 +134,7 @@ CHIP_ERROR FabricSyncRemoveBridgeCommand::RunCommand() mBridgeNodeId = bridgeNodeId; PairingManager::Instance().SetPairingDelegate(this); - DeviceMgr().UnpairRemoteFabricBridge(); + DeviceManager::Instance().UnpairRemoteFabricBridge(); return CHIP_NO_ERROR; } @@ -157,8 +158,8 @@ void FabricSyncAddLocalBridgeCommand::OnCommissioningComplete(NodeId deviceId, C if (err == CHIP_NO_ERROR) { - DeviceMgr().SetLocalBridgeNodeId(mLocalBridgeNodeId); - DeviceMgr().UpdateLastUsedNodeId(mLocalBridgeNodeId); + DeviceManager::Instance().SetLocalBridgeNodeId(mLocalBridgeNodeId); + DeviceManager::Instance().UpdateLastUsedNodeId(mLocalBridgeNodeId); ChipLogProgress(NotSpecified, "Successfully paired local bridge device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mLocalBridgeNodeId)); } @@ -173,7 +174,7 @@ void FabricSyncAddLocalBridgeCommand::OnCommissioningComplete(NodeId deviceId, C CHIP_ERROR FabricSyncAddLocalBridgeCommand::RunCommand(NodeId deviceId) { - if (DeviceMgr().IsLocalBridgeReady()) + if (DeviceManager::Instance().IsLocalBridgeReady()) { // print to console fprintf(stderr, "Local Fabric Bridge has already been configured.\n"); @@ -185,14 +186,14 @@ CHIP_ERROR FabricSyncAddLocalBridgeCommand::RunCommand(NodeId deviceId) if (mSetupPINCode.HasValue()) { - DeviceMgr().SetLocalBridgeSetupPinCode(mSetupPINCode.Value()); + DeviceManager::Instance().SetLocalBridgeSetupPinCode(mSetupPINCode.Value()); } if (mLocalPort.HasValue()) { - DeviceMgr().SetLocalBridgePort(mLocalPort.Value()); + DeviceManager::Instance().SetLocalBridgePort(mLocalPort.Value()); } - DeviceMgr().PairLocalFabricBridge(deviceId); + DeviceManager::Instance().PairLocalFabricBridge(deviceId); return CHIP_NO_ERROR; } @@ -207,7 +208,7 @@ void FabricSyncRemoveLocalBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_E if (err == CHIP_NO_ERROR) { - DeviceMgr().SetLocalBridgeNodeId(kUndefinedNodeId); + DeviceManager::Instance().SetLocalBridgeNodeId(kUndefinedNodeId); ChipLogProgress(NotSpecified, "Successfully removed local bridge device: NodeId: " ChipLogFormatX64, ChipLogValueX64(mLocalBridgeNodeId)); } @@ -222,7 +223,7 @@ void FabricSyncRemoveLocalBridgeCommand::OnDeviceRemoved(NodeId deviceId, CHIP_E CHIP_ERROR FabricSyncRemoveLocalBridgeCommand::RunCommand() { - NodeId bridgeNodeId = DeviceMgr().GetLocalBridgeNodeId(); + NodeId bridgeNodeId = DeviceManager::Instance().GetLocalBridgeNodeId(); if (bridgeNodeId == kUndefinedNodeId) { @@ -234,7 +235,7 @@ CHIP_ERROR FabricSyncRemoveLocalBridgeCommand::RunCommand() mLocalBridgeNodeId = bridgeNodeId; PairingManager::Instance().SetPairingDelegate(this); - DeviceMgr().UnpairLocalFabricBridge(); + DeviceManager::Instance().UnpairLocalFabricBridge(); return CHIP_NO_ERROR; } @@ -250,14 +251,14 @@ void FabricSyncDeviceCommand::OnCommissioningWindowOpened(NodeId deviceId, CHIP_ CHIP_ERROR error = ManualSetupPayloadGenerator(payload).payloadDecimalStringRepresentation(manualCode); if (error == CHIP_NO_ERROR) { - NodeId nodeId = DeviceMgr().GetNextAvailableNodeId(); + NodeId nodeId = DeviceManager::Instance().GetNextAvailableNodeId(); PairingManager::Instance().SetPairingDelegate(this); mAssignedNodeId = nodeId; usleep(kCommissionPrepareTimeMs * 1000); - DeviceMgr().PairRemoteDevice(nodeId, payloadBuffer); + DeviceManager::Instance().PairRemoteDevice(nodeId, payloadBuffer); } else { @@ -283,7 +284,7 @@ void FabricSyncDeviceCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERRO if (err == CHIP_NO_ERROR) { - DeviceMgr().AddSyncedDevice(Device(mAssignedNodeId, mRemoteEndpointId)); + DeviceManager::Instance().AddSyncedDevice(Device(mAssignedNodeId, mRemoteEndpointId)); } else { @@ -294,7 +295,7 @@ void FabricSyncDeviceCommand::OnCommissioningComplete(NodeId deviceId, CHIP_ERRO CHIP_ERROR FabricSyncDeviceCommand::RunCommand(EndpointId remoteEndpointId) { - if (!DeviceMgr().IsFabricSyncReady()) + if (!DeviceManager::Instance().IsFabricSyncReady()) { // print to console fprintf(stderr, "Remote Fabric Bridge is not configured yet.\n"); @@ -303,7 +304,7 @@ CHIP_ERROR FabricSyncDeviceCommand::RunCommand(EndpointId remoteEndpointId) PairingManager::Instance().SetOpenCommissioningWindowDelegate(this); - DeviceMgr().OpenRemoteDeviceCommissioningWindow(remoteEndpointId); + DeviceManager::Instance().OpenRemoteDeviceCommissioningWindow(remoteEndpointId); return CHIP_NO_ERROR; } diff --git a/examples/fabric-admin/commands/pairing/PairingCommand.cpp b/examples/fabric-admin/commands/pairing/PairingCommand.cpp index e7298a1deb04c2..5ac731871f9af8 100644 --- a/examples/fabric-admin/commands/pairing/PairingCommand.cpp +++ b/examples/fabric-admin/commands/pairing/PairingCommand.cpp @@ -540,7 +540,7 @@ void PairingCommand::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E app::InteractionModelEngine::GetInstance()->ShutdownSubscriptions(command->CurrentCommissioner().GetFabricIndex(), nodeId); ScopedNodeId scopedNodeId(nodeId, command->CurrentCommissioner().GetFabricIndex()); - admin::DeviceMgr().RemoveSyncedDevice(scopedNodeId); + admin::DeviceManager::Instance().RemoveSyncedDevice(scopedNodeId); } else { diff --git a/examples/fabric-admin/device_manager/BridgeSubscription.cpp b/examples/fabric-admin/device_manager/BridgeSubscription.cpp index e7052d7df08a96..1df9371ff74dff 100644 --- a/examples/fabric-admin/device_manager/BridgeSubscription.cpp +++ b/examples/fabric-admin/device_manager/BridgeSubscription.cpp @@ -80,7 +80,7 @@ void BridgeSubscription::OnAttributeData(const ConcreteDataAttributePath & path, return; } - DeviceMgr().HandleAttributeData(path, *data); + DeviceManager::Instance().HandleAttributeData(path, *data); } void BridgeSubscription::OnEventData(const app::EventHeader & eventHeader, TLV::TLVReader * data, const app::StatusIB * status) @@ -101,7 +101,7 @@ void BridgeSubscription::OnEventData(const app::EventHeader & eventHeader, TLV:: return; } - DeviceMgr().HandleEventData(eventHeader, *data); + DeviceManager::Instance().HandleEventData(eventHeader, *data); } void BridgeSubscription::OnError(CHIP_ERROR error) diff --git a/examples/fabric-admin/device_manager/CommissionerControl.cpp b/examples/fabric-admin/device_manager/CommissionerControl.cpp index 80c9437450cc80..3c6dfa5a8a0f57 100644 --- a/examples/fabric-admin/device_manager/CommissionerControl.cpp +++ b/examples/fabric-admin/device_manager/CommissionerControl.cpp @@ -66,7 +66,7 @@ void CommissionerControl::OnResponse(app::CommandSender * client, const app::Con if (data != nullptr) { - DeviceMgr().HandleCommandResponse(path, *data); + DeviceManager::Instance().HandleCommandResponse(path, *data); } } diff --git a/examples/fabric-admin/device_manager/DeviceManager.cpp b/examples/fabric-admin/device_manager/DeviceManager.cpp index 8be53fd5faf128..9f40f92a87c411 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceManager.cpp @@ -42,9 +42,6 @@ constexpr uint16_t kMaxDiscriminatorLength = 4095; } // namespace -// Define the static member -DeviceManager DeviceManager::sInstance; - void DeviceManager::Init() { // TODO: (#34113) Init mLastUsedNodeId from chip config file diff --git a/examples/fabric-admin/device_manager/DeviceManager.h b/examples/fabric-admin/device_manager/DeviceManager.h index c4898baa18daa4..594fcfc5745703 100644 --- a/examples/fabric-admin/device_manager/DeviceManager.h +++ b/examples/fabric-admin/device_manager/DeviceManager.h @@ -55,6 +55,12 @@ class DeviceManager public: DeviceManager() = default; + static DeviceManager & Instance() + { + static DeviceManager instance; + return instance; + } + void Init(); chip::NodeId GetNextAvailableNodeId(); @@ -175,8 +181,6 @@ class DeviceManager Device * FindDeviceByNode(chip::NodeId nodeId); private: - friend DeviceManager & DeviceMgr(); - void RequestCommissioningApproval(); void HandleReadSupportedDeviceCategories(chip::TLV::TLVReader & data); @@ -212,19 +216,4 @@ class DeviceManager FabricSyncGetter mFabricSyncGetter; }; -/** - * Returns the public interface of the DeviceManager singleton object. - * - * Applications should use this to access features of the DeviceManager - * object. - */ -inline DeviceManager & DeviceMgr() -{ - if (!DeviceManager::sInstance.mInitialized) - { - DeviceManager::sInstance.Init(); - } - return DeviceManager::sInstance; -} - } // namespace admin diff --git a/examples/fabric-admin/device_manager/DeviceSubscriptionManager.cpp b/examples/fabric-admin/device_manager/DeviceSubscriptionManager.cpp index ca79cd0fd04887..46f94c99c81138 100644 --- a/examples/fabric-admin/device_manager/DeviceSubscriptionManager.cpp +++ b/examples/fabric-admin/device_manager/DeviceSubscriptionManager.cpp @@ -34,12 +34,6 @@ using namespace ::chip::app; namespace admin { -DeviceSubscriptionManager & DeviceSubscriptionManager::Instance() -{ - static DeviceSubscriptionManager instance; - return instance; -} - CHIP_ERROR DeviceSubscriptionManager::StartSubscription(Controller::DeviceController & controller, ScopedNodeId scopedNodeId) { assertChipStackLockedByCurrentThread(); diff --git a/examples/fabric-admin/device_manager/DeviceSubscriptionManager.h b/examples/fabric-admin/device_manager/DeviceSubscriptionManager.h index eb32d3f439276d..5f04522dcc1fac 100644 --- a/examples/fabric-admin/device_manager/DeviceSubscriptionManager.h +++ b/examples/fabric-admin/device_manager/DeviceSubscriptionManager.h @@ -30,7 +30,11 @@ namespace admin { class DeviceSubscriptionManager { public: - static DeviceSubscriptionManager & Instance(); + static DeviceSubscriptionManager & Instance() + { + static DeviceSubscriptionManager instance; + return instance; + } /// Usually called after we have added a synchronized device to fabric-bridge to monitor /// for any changes that need to be propagated to fabric-bridge. diff --git a/examples/fabric-admin/device_manager/DeviceSynchronization.cpp b/examples/fabric-admin/device_manager/DeviceSynchronization.cpp index a88df405617707..092c2505d19d73 100644 --- a/examples/fabric-admin/device_manager/DeviceSynchronization.cpp +++ b/examples/fabric-admin/device_manager/DeviceSynchronization.cpp @@ -143,7 +143,7 @@ void DeviceSynchronizer::OnReportEnd() void DeviceSynchronizer::OnDone(app::ReadClient * apReadClient) { #if defined(PW_RPC_ENABLED) - if (mState == State::ReceivedResponse && !DeviceMgr().IsCurrentBridgeDevice(mNodeId)) + if (mState == State::ReceivedResponse && !DeviceManager::Instance().IsCurrentBridgeDevice(mNodeId)) { GetUniqueId(); if (mState == State::GettingUid) @@ -230,15 +230,15 @@ void DeviceSynchronizer::GetUniqueId() VerifyOrReturn(!mCurrentDeviceData.has_unique_id, ChipLogDetail(NotSpecified, "We already have UniqueId")); #endif - auto * device = DeviceMgr().FindDeviceByNode(mNodeId); + auto * device = DeviceManager::Instance().FindDeviceByNode(mNodeId); // If there is no associated remote Fabric Sync Aggregator there is no other place for us to try // getting the UniqueId from and can return leaving the state in ReceivedResponse. VerifyOrReturn(device, ChipLogDetail(NotSpecified, "No remote Fabric Sync Aggregator to get UniqueId from")); // Because device is not-null we expect IsFabricSyncReady to be true. IsFabricSyncReady indicates we have a // connection to the remote Fabric Sync Aggregator. - VerifyOrDie(DeviceMgr().IsFabricSyncReady()); - auto remoteBridgeNodeId = DeviceMgr().GetRemoteBridgeNodeId(); + VerifyOrDie(DeviceManager::Instance().IsFabricSyncReady()); + auto remoteBridgeNodeId = DeviceManager::Instance().GetRemoteBridgeNodeId(); EndpointId remoteEndpointIdOfInterest = device->GetEndpointId(); ChipLogDetail(NotSpecified, "Attempting to get UniqueId from remote Fabric Sync Aggregator"); diff --git a/examples/fabric-admin/device_manager/PairingManager.cpp b/examples/fabric-admin/device_manager/PairingManager.cpp index fae6c09315e8c2..8474d78f023343 100644 --- a/examples/fabric-admin/device_manager/PairingManager.cpp +++ b/examples/fabric-admin/device_manager/PairingManager.cpp @@ -560,7 +560,7 @@ void PairingManager::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_E FabricIndex fabricIndex = self->CurrentCommissioner().GetFabricIndex(); app::InteractionModelEngine::GetInstance()->ShutdownSubscriptions(fabricIndex, nodeId); ScopedNodeId scopedNodeId(nodeId, fabricIndex); - DeviceMgr().RemoveSyncedDevice(scopedNodeId); + DeviceManager::Instance().RemoveSyncedDevice(scopedNodeId); } else { diff --git a/examples/fabric-admin/main.cpp b/examples/fabric-admin/main.cpp index 15471eed0530f6..5b7219a2109786 100644 --- a/examples/fabric-admin/main.cpp +++ b/examples/fabric-admin/main.cpp @@ -32,7 +32,7 @@ using namespace chip; void ApplicationInit() { - admin::DeviceMgr().Init(); + admin::DeviceManager::Instance().Init(); } // ================================================================================ diff --git a/examples/fabric-admin/rpc/RpcServer.cpp b/examples/fabric-admin/rpc/RpcServer.cpp index 1b084ef2157ce7..05fb9492248131 100644 --- a/examples/fabric-admin/rpc/RpcServer.cpp +++ b/examples/fabric-admin/rpc/RpcServer.cpp @@ -112,9 +112,9 @@ class FabricAdmin final : public rpc::FabricAdmin, public IcdManager::Delegate ChipLogValueX64(scopedNodeId.GetNodeId()), commissioningTimeoutSec, iterations, discriminator); // Open the device commissioning window using raw binary data for salt and verifier - DeviceMgr().OpenDeviceCommissioningWindow(scopedNodeId, iterations, commissioningTimeoutSec, discriminator, - ByteSpan(request.salt.bytes, request.salt.size), - ByteSpan(request.verifier.bytes, request.verifier.size)); + DeviceManager::Instance().OpenDeviceCommissioningWindow(scopedNodeId, iterations, commissioningTimeoutSec, discriminator, + ByteSpan(request.salt.bytes, request.salt.size), + ByteSpan(request.verifier.bytes, request.verifier.size)); response.success = true; @@ -146,13 +146,13 @@ class FabricAdmin final : public rpc::FabricAdmin, public IcdManager::Delegate if (error == CHIP_NO_ERROR) { - NodeId nodeId = DeviceMgr().GetNextAvailableNodeId(); + NodeId nodeId = DeviceManager::Instance().GetNextAvailableNodeId(); // After responding with RequestCommissioningApproval to the node where the client initiated the // RequestCommissioningApproval, you need to wait for it to open a commissioning window on its bridge. usleep(kCommissionPrepareTimeMs * 1000); - DeviceMgr().PairRemoteDevice(nodeId, code.c_str()); + DeviceManager::Instance().PairRemoteDevice(nodeId, code.c_str()); } else { From e25647f47a4d3384e1a73f8e4314fb99c31e9a72 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Fri, 8 Nov 2024 17:57:59 -0800 Subject: [PATCH 106/121] [Fabric-Bridge] Use Meyers' Singleton pattern for BridgedDeviceManager (#36440) --- .../include/BridgedDeviceManager.h | 19 ++++++------------- .../src/BridgedAdministratorCommissioning.cpp | 2 +- .../src/BridgedDeviceBasicInformationImpl.cpp | 4 ++-- .../src/BridgedDeviceManager.cpp | 3 --- .../fabric-bridge-app/linux/RpcServer.cpp | 12 ++++++------ examples/fabric-bridge-app/linux/main.cpp | 6 +++--- 6 files changed, 18 insertions(+), 28 deletions(-) diff --git a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceManager.h b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceManager.h index 1a6a57948f340a..d06c6fa4ae366e 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceManager.h +++ b/examples/fabric-bridge-app/fabric-bridge-common/include/BridgedDeviceManager.h @@ -31,6 +31,12 @@ class BridgedDeviceManager public: BridgedDeviceManager() = default; + static BridgedDeviceManager & Instance() + { + static BridgedDeviceManager instance; + return instance; + } + /** * @brief Initializes the BridgedDeviceManager. * @@ -112,8 +118,6 @@ class BridgedDeviceManager BridgedDevice * GetDeviceByUniqueId(const std::string & id); private: - friend BridgedDeviceManager & BridgeDeviceMgr(); - /** * Creates a new unique ID that is not used by any other mDevice */ @@ -126,15 +130,4 @@ class BridgedDeviceManager std::unique_ptr mDevices[CHIP_DEVICE_CONFIG_DYNAMIC_ENDPOINT_COUNT + 1]; }; -/** - * Returns the public interface of the BridgedDeviceManager singleton object. - * - * Applications should use this to access features of the BridgedDeviceManager - * object. - */ -inline BridgedDeviceManager & BridgeDeviceMgr() -{ - return BridgedDeviceManager::sInstance; -} - } // namespace bridge diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp index 3299df75a9039e..6cfb5a5caaedd7 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedAdministratorCommissioning.cpp @@ -45,7 +45,7 @@ CHIP_ERROR BridgedAdministratorCommissioning::Read(const ConcreteReadAttributePa { VerifyOrDie(aPath.mClusterId == Clusters::AdministratorCommissioning::Id); EndpointId endpointId = aPath.mEndpointId; - BridgedDevice * device = BridgeDeviceMgr().GetDevice(endpointId); + BridgedDevice * device = BridgedDeviceManager::Instance().GetDevice(endpointId); if (!device) { diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceBasicInformationImpl.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceBasicInformationImpl.cpp index d021671c8bf1bd..3a03d8f84a81a0 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceBasicInformationImpl.cpp +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceBasicInformationImpl.cpp @@ -36,7 +36,7 @@ CHIP_ERROR BridgedDeviceBasicInformationImpl::Read(const ConcreteReadAttributePa // Registration is done for the bridged device basic information only VerifyOrDie(path.mClusterId == app::Clusters::BridgedDeviceBasicInformation::Id); - BridgedDevice * dev = BridgeDeviceMgr().GetDevice(path.mEndpointId); + BridgedDevice * dev = BridgedDeviceManager::Instance().GetDevice(path.mEndpointId); VerifyOrReturnError(dev != nullptr, CHIP_ERROR_NOT_FOUND); switch (path.mAttributeId) @@ -93,7 +93,7 @@ CHIP_ERROR BridgedDeviceBasicInformationImpl::Write(const ConcreteDataAttributeP { VerifyOrDie(path.mClusterId == app::Clusters::BridgedDeviceBasicInformation::Id); - BridgedDevice * dev = BridgeDeviceMgr().GetDevice(path.mEndpointId); + BridgedDevice * dev = BridgedDeviceManager::Instance().GetDevice(path.mEndpointId); VerifyOrReturnError(dev != nullptr, CHIP_ERROR_NOT_FOUND); if (!dev->IsReachable()) diff --git a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceManager.cpp b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceManager.cpp index babe2db9172259..5c53d413cbb344 100644 --- a/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceManager.cpp +++ b/examples/fabric-bridge-app/fabric-bridge-common/src/BridgedDeviceManager.cpp @@ -176,9 +176,6 @@ const EmberAfDeviceType sBridgedDeviceTypes[] = { { DEVICE_TYPE_BRIDGED_NODE, DE } // namespace -// Define the static member -BridgedDeviceManager BridgedDeviceManager::sInstance; - void BridgedDeviceManager::Init() { mFirstDynamicEndpointId = static_cast( diff --git a/examples/fabric-bridge-app/linux/RpcServer.cpp b/examples/fabric-bridge-app/linux/RpcServer.cpp index a34692b177cc56..e699c474104064 100644 --- a/examples/fabric-bridge-app/linux/RpcServer.cpp +++ b/examples/fabric-bridge-app/linux/RpcServer.cpp @@ -118,7 +118,7 @@ pw::Status FabricBridge::AddSynchronizedDevice(const chip_rpc_SynchronizedDevice device->SetBridgedAttributes(attributes); device->SetIcd(request.has_is_icd && request.is_icd); - auto result = BridgeDeviceMgr().AddDeviceEndpoint(std::move(device), 1 /* parentEndpointId */); + auto result = BridgedDeviceManager::Instance().AddDeviceEndpoint(std::move(device), 1 /* parentEndpointId */); if (!result.has_value()) { ChipLogError(NotSpecified, "Failed to add device with Id=[%d:0x" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), @@ -126,7 +126,7 @@ pw::Status FabricBridge::AddSynchronizedDevice(const chip_rpc_SynchronizedDevice return pw::Status::Unknown(); } - BridgedDevice * addedDevice = BridgeDeviceMgr().GetDeviceByScopedNodeId(scopedNodeId); + BridgedDevice * addedDevice = BridgedDeviceManager::Instance().GetDeviceByScopedNodeId(scopedNodeId); VerifyOrDie(addedDevice); CHIP_ERROR err = EcosystemInformation::EcosystemInformationServer::Instance().AddEcosystemInformationClusterToEndpoint( @@ -143,7 +143,7 @@ pw::Status FabricBridge::RemoveSynchronizedDevice(const chip_rpc_SynchronizedDev ChipLogProgress(NotSpecified, "Received RemoveSynchronizedDevice: Id=[%d:" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), ChipLogValueX64(scopedNodeId.GetNodeId())); - auto removed_idx = BridgeDeviceMgr().RemoveDeviceByScopedNodeId(scopedNodeId); + auto removed_idx = BridgedDeviceManager::Instance().RemoveDeviceByScopedNodeId(scopedNodeId); if (!removed_idx.has_value()) { ChipLogError(NotSpecified, "Failed to remove device with Id=[%d:0x" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), @@ -161,7 +161,7 @@ pw::Status FabricBridge::ActiveChanged(const chip_rpc_KeepActiveChanged & reques ChipLogProgress(NotSpecified, "Received ActiveChanged: Id=[%d:" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), ChipLogValueX64(scopedNodeId.GetNodeId())); - auto * device = BridgeDeviceMgr().GetDeviceByScopedNodeId(scopedNodeId); + auto * device = BridgedDeviceManager::Instance().GetDeviceByScopedNodeId(scopedNodeId); if (device == nullptr) { ChipLogError(NotSpecified, "Could not find bridged device associated with Id=[%d:0x" ChipLogFormatX64 "]", @@ -181,7 +181,7 @@ pw::Status FabricBridge::AdminCommissioningAttributeChanged(const chip_rpc_Admin ChipLogProgress(NotSpecified, "Received CADMIN attribute change: Id=[%d:" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), ChipLogValueX64(scopedNodeId.GetNodeId())); - auto * device = BridgeDeviceMgr().GetDeviceByScopedNodeId(scopedNodeId); + auto * device = BridgedDeviceManager::Instance().GetDeviceByScopedNodeId(scopedNodeId); if (device == nullptr) { ChipLogError(NotSpecified, "Could not find bridged device associated with Id=[%d:0x" ChipLogFormatX64 "]", @@ -220,7 +220,7 @@ pw::Status FabricBridge::DeviceReachableChanged(const chip_rpc_ReachabilityChang ChipLogProgress(NotSpecified, "Received device reachable changed: Id=[%d:" ChipLogFormatX64 "]", scopedNodeId.GetFabricIndex(), ChipLogValueX64(scopedNodeId.GetNodeId())); - auto * device = BridgeDeviceMgr().GetDeviceByScopedNodeId(scopedNodeId); + auto * device = BridgedDeviceManager::Instance().GetDeviceByScopedNodeId(scopedNodeId); if (device == nullptr) { ChipLogError(NotSpecified, "Could not find bridged device associated with Id=[%d:0x" ChipLogFormatX64 "]", diff --git a/examples/fabric-bridge-app/linux/main.cpp b/examples/fabric-bridge-app/linux/main.cpp index cca3fbc8d0d19c..8c622cac541004 100644 --- a/examples/fabric-bridge-app/linux/main.cpp +++ b/examples/fabric-bridge-app/linux/main.cpp @@ -151,7 +151,7 @@ void AdministratorCommissioningCommandHandler::InvokeCommand(HandlerContext & ha Status status = Status::Failure; #if defined(PW_RPC_FABRIC_BRIDGE_SERVICE) && PW_RPC_FABRIC_BRIDGE_SERVICE - BridgedDevice * device = BridgeDeviceMgr().GetDevice(endpointId); + BridgedDevice * device = BridgedDeviceManager::Instance().GetDevice(endpointId); // TODO: issues:#33784, need to make OpenCommissioningWindow synchronous if (device != nullptr && @@ -214,7 +214,7 @@ void BridgedDeviceInformationCommandHandler::InvokeCommand(HandlerContext & hand return; } - BridgedDevice * device = BridgeDeviceMgr().GetDevice(endpointId); + BridgedDevice * device = BridgedDeviceManager::Instance().GetDevice(endpointId); if (device == nullptr || !device->IsIcd()) { handlerContext.mCommandHandler.AddStatus(handlerContext.mRequestPath, Status::Failure); @@ -262,7 +262,7 @@ void ApplicationInit() AttemptRpcClientConnect(&DeviceLayer::SystemLayer(), nullptr); #endif - bridge::BridgeDeviceMgr().Init(); + bridge::BridgedDeviceManager::Instance().Init(); VerifyOrDie(bridge::gBridgedAdministratorCommissioning.Init() == CHIP_NO_ERROR); VerifyOrDieWithMsg(bridge::CommissionerControlInit() == CHIP_NO_ERROR, NotSpecified, From 0aa26565d8954a2c36da5ffae101c4640263cf41 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Fri, 8 Nov 2024 17:58:38 -0800 Subject: [PATCH 107/121] [Fabric-Sync] Remove incorrect logs (#36443) --- examples/fabric-sync/admin/DeviceManager.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/examples/fabric-sync/admin/DeviceManager.cpp b/examples/fabric-sync/admin/DeviceManager.cpp index 5c41bbb56f7b83..76863e6a33869e 100644 --- a/examples/fabric-sync/admin/DeviceManager.cpp +++ b/examples/fabric-sync/admin/DeviceManager.cpp @@ -75,7 +75,6 @@ CHIP_ERROR DeviceManager::PairRemoteFabricBridge(NodeId nodeId, uint32_t setupPI return err; } - ChipLogProgress(NotSpecified, "Successfully paired remote fabric bridge: Node ID " ChipLogFormatX64, ChipLogValueX64(nodeId)); return CHIP_NO_ERROR; } @@ -90,7 +89,6 @@ CHIP_ERROR DeviceManager::PairRemoteDevice(NodeId nodeId, const char * payload) return err; } - ChipLogProgress(NotSpecified, "Successfully paired device: Node ID " ChipLogFormatX64, ChipLogValueX64(nodeId)); return CHIP_NO_ERROR; } @@ -106,7 +104,6 @@ CHIP_ERROR DeviceManager::PairRemoteDevice(NodeId nodeId, uint32_t setupPINCode, return err; } - ChipLogProgress(NotSpecified, "Successfully paired device: Node ID " ChipLogFormatX64, ChipLogValueX64(nodeId)); return CHIP_NO_ERROR; } @@ -125,8 +122,6 @@ CHIP_ERROR DeviceManager::UnpairRemoteFabricBridge() return err; } - ChipLogProgress(NotSpecified, "Successfully unpaired remote fabric bridge: Node ID " ChipLogFormatX64, - ChipLogValueX64(mRemoteBridgeNodeId)); return CHIP_NO_ERROR; } @@ -139,7 +134,6 @@ CHIP_ERROR DeviceManager::UnpairRemoteDevice(NodeId nodeId) return err; } - ChipLogProgress(NotSpecified, "Successfully unpaired remote device: Node ID " ChipLogFormatX64, ChipLogValueX64(nodeId)); return CHIP_NO_ERROR; } From c3b35eb6c16437ad19d919faa69d269c95da10db Mon Sep 17 00:00:00 2001 From: Sergio Soares Date: Sat, 9 Nov 2024 15:41:13 -0500 Subject: [PATCH 108/121] matter-devices.xml: remove EXTS as required attribute for AccessControl (#36410) This PR removes the EXTENSION attribute as a requirement for the AccessControl cluster on the root node as it goes against the spec. --- src/app/zap-templates/zcl/data-model/chip/matter-devices.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml b/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml index 8e1feb4fb30c55..6d4525ab6a67cb 100644 --- a/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml +++ b/src/app/zap-templates/zcl/data-model/chip/matter-devices.xml @@ -40,7 +40,6 @@ limitations under the License. ACL - EXTENSION DATA_MODEL_REVISION From 0f133e3c319f496723af564a8c8187745592b761 Mon Sep 17 00:00:00 2001 From: Pradip De Date: Mon, 11 Nov 2024 15:23:59 +0000 Subject: [PATCH 109/121] Fix indentation issue in zap template function. (#36446) --- .../zap-templates/templates/app/cluster-objects-src.zapt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/app/zap-templates/templates/app/cluster-objects-src.zapt b/src/app/zap-templates/templates/app/cluster-objects-src.zapt index 2663a6dd44c7a3..e32a0be1165120 100644 --- a/src/app/zap-templates/templates/app/cluster-objects-src.zapt +++ b/src/app/zap-templates/templates/app/cluster-objects-src.zapt @@ -267,14 +267,14 @@ bool CommandHasLargePayload(ClusterId aCluster, CommandId aCommand) {{#zcl_commands}} {{#if isLargeMessage}} if ((aCluster == Clusters::{{asUpperCamelCase parent.name}}::Id) && - (aCommand == Clusters::{{asUpperCamelCase parent.name}}::Commands::{{asUpperCamelCase name}}::Id)) - { + (aCommand == Clusters::{{asUpperCamelCase parent.name}}::Commands::{{asUpperCamelCase name}}::Id)) + { return true; - } + } {{/if}} {{/zcl_commands}} {{/zcl_clusters}} - return false; + return false; } } // namespace app From d099b0b1ce5a5c7429a9d03e9c015b2f38c85acb Mon Sep 17 00:00:00 2001 From: Andrei Litvin Date: Mon, 11 Nov 2024 11:12:12 -0500 Subject: [PATCH 110/121] Deduplicate repeated code in DeviceTypeResolver (#36436) * Dedup code in devicetyperesolver * Restyle * Add missing file * Restyled by clang-format * Restyled by gn --------- Co-authored-by: Andrei Litvin Co-authored-by: Restyled.io --- src/access/BUILD.gn | 9 ++++ src/access/ProviderDeviceTypeResolver.h | 50 +++++++++++++++++++ src/app/BUILD.gn | 1 + src/app/dynamic_server/AccessControl.cpp | 20 +++----- src/app/server/BUILD.gn | 2 + src/app/server/Server.cpp | 21 ++------ .../ServerEndpoint/MTRServerAccessControl.mm | 15 ++---- 7 files changed, 77 insertions(+), 41 deletions(-) create mode 100644 src/access/ProviderDeviceTypeResolver.h diff --git a/src/access/BUILD.gn b/src/access/BUILD.gn index 3f3aaafe8a6a9b..66370090a4f582 100644 --- a/src/access/BUILD.gn +++ b/src/access/BUILD.gn @@ -78,3 +78,12 @@ static_library("access") { ] } } + +source_set("provider-impl") { + sources = [ "ProviderDeviceTypeResolver.h" ] + + public_deps = [ + ":access", + "${chip_root}/src/app/data-model-provider", + ] +} diff --git a/src/access/ProviderDeviceTypeResolver.h b/src/access/ProviderDeviceTypeResolver.h new file mode 100644 index 00000000000000..0a215d4a899930 --- /dev/null +++ b/src/access/ProviderDeviceTypeResolver.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 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. + */ +#pragma once + +#include +#include + +namespace chip { +namespace Access { + +/// A device type resolver where the DataModel::Provider is fetched dynamically (may change over time) +class DynamicProviderDeviceTypeResolver : public chip::Access::AccessControl::DeviceTypeResolver +{ +public: + using ModelGetter = app::DataModel::Provider * (*) (); + + DynamicProviderDeviceTypeResolver(ModelGetter model) : mModelGetter(model) {} + + bool IsDeviceTypeOnEndpoint(chip::DeviceTypeId deviceType, chip::EndpointId endpoint) override + { + app::DataModel::Provider * model = mModelGetter(); + for (auto type = model->FirstDeviceType(endpoint); type.has_value(); type = model->NextDeviceType(endpoint, *type)) + { + if (type->deviceTypeId == deviceType) + { + return true; + } + } + return false; + } + +private: + ModelGetter mModelGetter; +}; + +} // namespace Access +} // namespace chip diff --git a/src/app/BUILD.gn b/src/app/BUILD.gn index 28179390cfa8dc..b0cde0960c9013 100644 --- a/src/app/BUILD.gn +++ b/src/app/BUILD.gn @@ -264,6 +264,7 @@ static_library("interaction-model") { public_deps += [ ":global-attributes", "${chip_root}/src/access", + "${chip_root}/src/access:provider-impl", "${chip_root}/src/app/common:attribute-type", ] diff --git a/src/app/dynamic_server/AccessControl.cpp b/src/app/dynamic_server/AccessControl.cpp index 9f39040e00b056..75385f49308792 100644 --- a/src/app/dynamic_server/AccessControl.cpp +++ b/src/app/dynamic_server/AccessControl.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -34,22 +35,13 @@ namespace { // DynamicDispatch.cpp. constexpr EndpointId kSupportedEndpoint = 0; -class DeviceTypeResolver : public Access::AccessControl::DeviceTypeResolver +class DeviceTypeResolver : public chip::Access::DynamicProviderDeviceTypeResolver { public: - bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) override - { - chip::app::DataModel::Provider * model = chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); - - for (auto type = model->FirstDeviceType(endpoint); type.has_value(); type = model->NextDeviceType(endpoint, *type)) - { - if (type->deviceTypeId == deviceType) - { - return true; - } - } - return false; - } + DeviceTypeResolver() : + chip::Access::DynamicProviderDeviceTypeResolver( + [] { return chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); }) + {} }; // TODO: Make the policy more configurable by consumers. diff --git a/src/app/server/BUILD.gn b/src/app/server/BUILD.gn index 4addf8eea938e3..42c4caf05cad78 100644 --- a/src/app/server/BUILD.gn +++ b/src/app/server/BUILD.gn @@ -52,6 +52,8 @@ static_library("server") { cflags = [ "-Wconversion" ] public_deps = [ + "${chip_root}/src/access", + "${chip_root}/src/access:provider-impl", "${chip_root}/src/app", "${chip_root}/src/app:test-event-trigger", "${chip_root}/src/app/icd/server:icd-server-config", diff --git a/src/app/server/Server.cpp b/src/app/server/Server.cpp index cfb8d21de3a130..6808431b67bf4f 100644 --- a/src/app/server/Server.cpp +++ b/src/app/server/Server.cpp @@ -17,6 +17,7 @@ #include +#include #include #include @@ -82,23 +83,9 @@ using chip::Transport::TcpListenParameters; namespace { -class DeviceTypeResolver : public chip::Access::AccessControl::DeviceTypeResolver -{ -public: - bool IsDeviceTypeOnEndpoint(chip::DeviceTypeId deviceType, chip::EndpointId endpoint) override - { - chip::app::DataModel::Provider * model = chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); - - for (auto type = model->FirstDeviceType(endpoint); type.has_value(); type = model->NextDeviceType(endpoint, *type)) - { - if (type->deviceTypeId == deviceType) - { - return true; - } - } - return false; - } -} sDeviceTypeResolver; +chip::Access::DynamicProviderDeviceTypeResolver sDeviceTypeResolver([] { + return chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); +}); } // namespace diff --git a/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm b/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm index 35f602e0de2aeb..67d546b4636e98 100644 --- a/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm +++ b/src/darwin/Framework/CHIP/ServerEndpoint/MTRServerAccessControl.mm @@ -26,6 +26,7 @@ #include #include +#include #include #include #include @@ -42,18 +43,12 @@ namespace { -class DeviceTypeResolver : public Access::AccessControl::DeviceTypeResolver { +class DeviceTypeResolver : public chip::Access::DynamicProviderDeviceTypeResolver { public: - bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) override + DeviceTypeResolver() + : chip::Access::DynamicProviderDeviceTypeResolver( + [] { return chip::app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); }) { - app::DataModel::Provider * model = app::InteractionModelEngine::GetInstance()->GetDataModelProvider(); - - for (auto type = model->FirstDeviceType(endpoint); type.has_value(); type = model->NextDeviceType(endpoint, *type)) { - if (type->deviceTypeId == deviceType) { - return true; - } - } - return false; } }; From 882b76eb5e918d75d700b55098fd7af640610ad5 Mon Sep 17 00:00:00 2001 From: BoB13-Matter Date: Tue, 12 Nov 2024 01:27:04 +0900 Subject: [PATCH 111/121] Fix argument count handling in Command::InitArguments to prevent integer overflow (#36414) * Fix unsigned overflow in Command::InitArguments with zero args * Update format --- examples/chip-tool/commands/common/Command.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/examples/chip-tool/commands/common/Command.cpp b/examples/chip-tool/commands/common/Command.cpp index 82e9eedc461dd5..91a65db789d976 100644 --- a/examples/chip-tool/commands/common/Command.cpp +++ b/examples/chip-tool/commands/common/Command.cpp @@ -55,6 +55,10 @@ bool Command::InitArguments(int argc, char ** argv) { optionalArgsCount++; } + else if (argvExtraArgsCount == 0) + { + mandatoryArgsCount++; + } else { mandatoryArgsCount++; From d4d19bec450e9d4851585ebb4e01bd0f9369086a Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Mon, 11 Nov 2024 08:48:07 -0800 Subject: [PATCH 112/121] Do not remove logs after stop fabric sync (#36449) --- examples/fabric-admin/scripts/run_fabric_sync.sh | 5 +++++ examples/fabric-admin/scripts/stop_fabric_sync.sh | 3 --- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/examples/fabric-admin/scripts/run_fabric_sync.sh b/examples/fabric-admin/scripts/run_fabric_sync.sh index 49182f7ce92825..60e6f9554ec855 100755 --- a/examples/fabric-admin/scripts/run_fabric_sync.sh +++ b/examples/fabric-admin/scripts/run_fabric_sync.sh @@ -104,6 +104,11 @@ else exit 1 fi +# Remove previous log files +rm /tmp/fabric_admin.log +rm /tmp/fabric_bridge_app.log +echo "Removed fabric sync log files." + # Start fabric-bridge-app if available and redirect its output to /dev/null if [ -f "$FABRIC_BRIDGE_APP_PATH" ]; then "$FABRIC_BRIDGE_APP_PATH" >"$FABRIC_BRIDGE_APP_LOG" 2>&1 & diff --git a/examples/fabric-admin/scripts/stop_fabric_sync.sh b/examples/fabric-admin/scripts/stop_fabric_sync.sh index a03e188b5eb0c6..e9e44f4a5dc9e6 100755 --- a/examples/fabric-admin/scripts/stop_fabric_sync.sh +++ b/examples/fabric-admin/scripts/stop_fabric_sync.sh @@ -22,6 +22,3 @@ fi # Remove /tmp/chip_* files and directories rm -rf /tmp/chip_* echo "Removed /tmp/chip_* files and directories." -rm /tmp/fabric_admin.log -rm /tmp/fabric_bridge_app.log -echo "Removed fabric sync log files." From f10e90ff086d42b7fef8b20f2e18ab679a0f8dfc Mon Sep 17 00:00:00 2001 From: Vatsal Ghelani <152916324+vatsalghelani-csa@users.noreply.github.com> Date: Mon, 11 Nov 2024 12:01:32 -0500 Subject: [PATCH 113/121] Adding python code for generating data model xml .gni file (#36437) * Adding python code for granating data model xml .gni file * Fixed python code and remove buildable * Update src/python_testing/matter_testing_infrastructure/generate_data_model_xmls_gni.py Co-authored-by: Andrei Litvin * Update src/python_testing/matter_testing_infrastructure/generate_data_model_xmls_gni.py Co-authored-by: Andrei Litvin * Update src/python_testing/matter_testing_infrastructure/generate_data_model_xmls_gni.py Co-authored-by: Andrei Litvin * Fixed mismatches and typo from suggestion commits * Fixed file configuraton to figure out the right directory, so this can be run from anywhere * Restyled by autopep8 * Restyled by isort * Update src/python_testing/matter_testing_infrastructure/generate_data_model_xmls_gni.py --------- Co-authored-by: Andrei Litvin Co-authored-by: Restyled.io --- .../generate_data_model_xmls_gni.py | 112 ++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 src/python_testing/matter_testing_infrastructure/generate_data_model_xmls_gni.py diff --git a/src/python_testing/matter_testing_infrastructure/generate_data_model_xmls_gni.py b/src/python_testing/matter_testing_infrastructure/generate_data_model_xmls_gni.py new file mode 100644 index 00000000000000..76179797f5fe8c --- /dev/null +++ b/src/python_testing/matter_testing_infrastructure/generate_data_model_xmls_gni.py @@ -0,0 +1,112 @@ +# Copyright (c) 2024 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. + +""" +Generates a gni file containing all data_model files (generally XML and JSON files) +that are typically used by matter_testing_infrastructure. + +These files are to be bundled with whl packages of the matter_testing_infrastructure +so that methods requiring data model files work just by installing the python +package without requiring a full chip SDK checkout. +""" +import os + +import jinja2 + +# Set chip_root to be dynamically based on the script's location +chip_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../..")) + +# Directories to search for .xml and .json files relative to chip_root +directories = [ + os.path.join(chip_root, "data_model/1.3/clusters/"), + os.path.join(chip_root, "data_model/1.3/device_types/"), + os.path.join(chip_root, "data_model/1.4/clusters/"), + os.path.join(chip_root, "data_model/1.4/device_types/"), + os.path.join(chip_root, "data_model/master/clusters/"), + os.path.join(chip_root, "data_model/master/device_types/"), +] + +# Template for generating the GNI file content with proper indentation +GNI_TEMPLATE = """\ +# Copyright (c) 2024 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("//build_overrides/chip.gni") + +data_model_XMLS = [ +{% for name in file_list %} + "{{ name }}", +{% endfor %} +] +""" + +# Function to find and collect all .xml and .json files + + +def get_data_model_file_names(): + file_list = [] + for directory in directories: + for root, _, files in os.walk(directory): + for file in files: + if file.endswith(".xml") or file.endswith(".json"): + # Replace absolute path with `${chip_root}` for GNI compatibility + relative_path = os.path.join("${chip_root}", os.path.relpath(root, chip_root), file) + file_list.append(relative_path) + # Sort files alphabetically + file_list.sort() + return file_list + +# Main function to generate the data_model_xmls.gni file + + +def generate_gni_file(): + # Step 1: Find all files and create the sorted file list + file_list = get_data_model_file_names() + + # Step 2: Render the template with the file list + environment = jinja2.Environment(trim_blocks=True, lstrip_blocks=True) + template = environment.from_string(GNI_TEMPLATE) + output_content = template.render(file_list=file_list) + + # Step 3: Dynamically generate the output file path + # Get the script's directory (where this script is located) + script_dir = os.path.dirname(os.path.realpath(__file__)) # Directory of the current script + + # Step 4: Ensure we are in the correct `src/python_testing/` directory + base_dir = os.path.abspath(os.path.join(script_dir, "../..")) # Go up two levels to src/python_testing/ + # Now append `matter_testing_infrastructure` + output_dir = os.path.join(base_dir, "python_testing", "matter_testing_infrastructure") + output_file = os.path.join(output_dir, "data_model_xmls.gni") + + # Step 5: Write the rendered content to the output file + os.makedirs(output_dir, exist_ok=True) # Ensure the output directory exists + with open(output_file, "wt") as f: + f.write(output_content) + print(f"{output_file} has been generated successfully.") + + +# Run the function to generate the .gni file +if __name__ == "__main__": + generate_gni_file() From d6b098bcfa7bf1f8d048e5cf96110a833c7035f8 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Mon, 11 Nov 2024 14:55:13 -0500 Subject: [PATCH 114/121] Fix valid response check. (#36461) We should not be comparing strings by pointer value. --- .../Framework/CHIP/MTRDeviceDataValidation.mm | 2 +- src/darwin/Framework/CHIPTests/MTRDeviceTests.m | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/darwin/Framework/CHIP/MTRDeviceDataValidation.mm b/src/darwin/Framework/CHIP/MTRDeviceDataValidation.mm index 55014b453132a3..cd4ebabf811b9b 100644 --- a/src/darwin/Framework/CHIP/MTRDeviceDataValidation.mm +++ b/src/darwin/Framework/CHIP/MTRDeviceDataValidation.mm @@ -207,7 +207,7 @@ BOOL MTRInvokeResponseIsWellFormed(NSArray * r // Now we know data is a dictionary (in fact a data-value). The only thing // we promise about it is that it has type MTRStructureValueType. - if (data[MTRTypeKey] != MTRStructureValueType) { + if (![MTRStructureValueType isEqual:data[MTRTypeKey]]) { MTR_LOG_ERROR("Invoke response data is not of structure type: %@", data); return NO; } diff --git a/src/darwin/Framework/CHIPTests/MTRDeviceTests.m b/src/darwin/Framework/CHIPTests/MTRDeviceTests.m index 5b6e767fc8e260..a0dd9651bd73b5 100644 --- a/src/darwin/Framework/CHIPTests/MTRDeviceTests.m +++ b/src/darwin/Framework/CHIPTests/MTRDeviceTests.m @@ -5580,6 +5580,19 @@ - (void)test044_InvokeResponseWellFormedness ], @"valid" : @(YES), }, + @{ + @"input" : @[ + @{ + @"commandPath" : [MTRCommandPath commandPathWithEndpointID:@(0) clusterID:@(6) commandID:@(0)], + @"data" : @ { + @"type" : @"Structure", + @"value" : @[], // Empty structure, valid + }, + }, + ], + // Same as the previous test, but not using the SDK string constants + @"valid" : @(YES), + }, @{ @"input" : @[ @{ From b825bb38fa0b97cf2c724a0852545de83e049734 Mon Sep 17 00:00:00 2001 From: Mathieu Kardous <84793247+mkardous-silabs@users.noreply.github.com> Date: Mon, 11 Nov 2024 16:18:50 -0500 Subject: [PATCH 115/121] [Silabs] Brake the wifi implementations into platform specific source files (#36460) * Split source between wifi platforms * Brake out wiseconnect specific code from the common abstraction * move power save function to specific interface * Remove hw state from extern C * Remove power save call form extern C * Remove unnecessary include * Restyle * Fix ifdef c++ include guards --- examples/platform/silabs/BaseApplication.cpp | 1 + examples/platform/silabs/MatterConfig.cpp | 2 +- examples/platform/silabs/SiWx917/BUILD.gn | 1 + .../silabs/SiWx917/SiWxWifiInterface.cpp | 95 +++-- .../efr32/rs911x/Rsi91xWifiInterface.cpp | 38 +- .../silabs/efr32/rs911x/hal/efx_spi.c | 18 +- .../efr32/rs911x/hal/rsi_hal_mcu_interrupt.c | 2 - .../efr32/rs911x/hal/rsi_hal_mcu_ioports.c | 18 +- .../efr32/rs911x/hal/rsi_hal_mcu_timer.c | 6 +- .../efr32/rs911x/hal/sl_si91x_ncp_utility.c | 3 +- .../platform/silabs/efr32/rs911x/rs9117.gni | 1 + .../platform/silabs/efr32/rs911x/rs911x.gni | 1 + .../silabs/efr32/wf200/Wf200WifiInterface.cpp | 323 +++++++++------ .../platform/silabs/efr32/wf200/efr_spi.c | 1 - .../platform/silabs/efr32/wf200/wf200_init.c | 10 +- .../silabs/wifi/WifiInterfaceAbstraction.cpp | 367 +----------------- .../silabs/wifi/WifiInterfaceAbstraction.h | 44 +-- .../wifi/WiseconnectInterfaceAbstraction.cpp | 350 +++++++++++++++++ .../wifi/WiseconnectInterfaceAbstraction.h | 48 +++ src/platform/silabs/BLEManagerImpl.h | 6 - src/platform/silabs/efr32/wifi/ethernetif.cpp | 4 +- src/platform/silabs/efr32/wifi/ethernetif.h | 8 + src/platform/silabs/efr32/wifi/lwip_netif.cpp | 5 + src/platform/silabs/efr32/wifi/wfx_msgs.h | 37 +- .../silabs/platformAbstraction/GsdkSpam.cpp | 4 +- .../platformAbstraction/WiseMcuSpam.cpp | 4 +- src/platform/silabs/rs911x/BLEManagerImpl.cpp | 11 +- src/platform/silabs/rs911x/rsi_ble_config.h | 8 + .../silabs/rs911x/wfx_sl_ble_init.cpp | 2 + src/platform/silabs/rs911x/wfx_sl_ble_init.h | 8 +- src/platform/silabs/wifi/wfx_host_events.h | 215 ++-------- 31 files changed, 803 insertions(+), 838 deletions(-) create mode 100644 examples/platform/silabs/wifi/WiseconnectInterfaceAbstraction.cpp create mode 100644 examples/platform/silabs/wifi/WiseconnectInterfaceAbstraction.h diff --git a/examples/platform/silabs/BaseApplication.cpp b/examples/platform/silabs/BaseApplication.cpp index 5de80c2d108549..b8a240f5e01a21 100644 --- a/examples/platform/silabs/BaseApplication.cpp +++ b/examples/platform/silabs/BaseApplication.cpp @@ -64,6 +64,7 @@ #include #ifdef SL_WIFI +#include "WifiInterfaceAbstraction.h" #include "wfx_host_events.h" #include #include diff --git a/examples/platform/silabs/MatterConfig.cpp b/examples/platform/silabs/MatterConfig.cpp index c7d4487cfc4f5d..2045c83afad0c2 100644 --- a/examples/platform/silabs/MatterConfig.cpp +++ b/examples/platform/silabs/MatterConfig.cpp @@ -42,7 +42,7 @@ #if defined(SLI_SI91X_MCU_INTERFACE) && SLI_SI91X_MCU_INTERFACE == 1 #include "SiWxPlatformInterface.h" -#include "WifiInterfaceAbstraction.h" +#include "WiseconnectInterfaceAbstraction.h" #endif // SLI_SI91X_MCU_INTERFACE #include diff --git a/examples/platform/silabs/SiWx917/BUILD.gn b/examples/platform/silabs/SiWx917/BUILD.gn index 3409d8e815e6f0..5045989389af0e 100644 --- a/examples/platform/silabs/SiWx917/BUILD.gn +++ b/examples/platform/silabs/SiWx917/BUILD.gn @@ -115,6 +115,7 @@ config("wifi-interface-config") { source_set("wifi-interface") { sources = [ "${silabs_common_plat_dir}/wifi/WifiInterfaceAbstraction.cpp", + "${silabs_common_plat_dir}/wifi/WiseconnectInterfaceAbstraction.cpp", "SiWxWifiInterface.cpp", # Wi-Fi Config - Using the file sdk support until the wiseconnect file is fixed diff --git a/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp b/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp index 8696d083706638..962d1720b736cf 100644 --- a/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp +++ b/examples/platform/silabs/SiWx917/SiWxWifiInterface.cpp @@ -29,6 +29,7 @@ #include "FreeRTOS.h" #include "WifiInterfaceAbstraction.h" +#include "WiseconnectInterfaceAbstraction.h" #include "ble_config.h" #include "dhcp_client.h" #include "event_groups.h" @@ -45,7 +46,6 @@ #include extern "C" { -#include "sl_net.h" #include "sl_si91x_driver.h" #include "sl_si91x_host_interface.h" #include "sl_si91x_types.h" @@ -53,7 +53,6 @@ extern "C" { #include "sl_wifi_callback_framework.h" #include "sl_wifi_constants.h" #include "sl_wifi_types.h" -#include "wfx_host_events.h" #if SL_MBEDTLS_USE_TINYCRYPT #include "sl_si91x_constants.h" #include "sl_si91x_trng.h" @@ -440,6 +439,38 @@ sl_status_t JoinWifiNetwork(void) } // namespace +/** + * @brief Wifi initialization called from app main + * + * @return sl_status_t Returns underlying Wi-Fi initialization error + */ +sl_status_t sl_matter_wifi_platform_init(void) +{ + sl_status_t status = SL_STATUS_OK; + + status = sl_net_init((sl_net_interface_t) SL_NET_WIFI_CLIENT_INTERFACE, &config, &wifi_client_context, nullptr); + VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogError(DeviceLayer, "sl_net_init failed: %lx", status)); + + // Create Sempaphore for scan completion + sScanCompleteSemaphore = osSemaphoreNew(1, 0, nullptr); + VerifyOrReturnError(sScanCompleteSemaphore != nullptr, SL_STATUS_ALLOCATION_FAILED); + + // Create Semaphore for scan in-progress protection + sScanInProgressSemaphore = osSemaphoreNew(1, 1, nullptr); + VerifyOrReturnError(sScanCompleteSemaphore != nullptr, SL_STATUS_ALLOCATION_FAILED); + + // Create the message queue + sWifiEventQueue = osMessageQueueNew(kWfxQueueSize, sizeof(WifiEvent), nullptr); + VerifyOrReturnError(sWifiEventQueue != nullptr, SL_STATUS_ALLOCATION_FAILED); + + // Create timer for DHCP polling + // TODO: Use LWIP timer instead of creating a new one here + sDHCPTimer = osTimerNew(DHCPTimerEventHandler, osTimerPeriodic, nullptr, nullptr); + VerifyOrReturnError(sDHCPTimer != nullptr, SL_STATUS_ALLOCATION_FAILED); + + return status; +} + /****************************************************************** * @fn int32_t wfx_rsi_get_ap_info(wfx_wifi_scan_result_t *ap) * @brief @@ -614,7 +645,7 @@ sl_status_t show_scan_results(sl_wifi_scan_result_t * scan_result) // if user has provided ssid, then check if the current scan result ssid matches the user provided ssid if (wfx_rsi.scan_ssid != nullptr && (strncmp(wfx_rsi.scan_ssid, cur_scan_result.ssid, std::min(strlen(wfx_rsi.scan_ssid), strlen(cur_scan_result.ssid))) == - CMP_SUCCESS)) + 0)) { continue; } @@ -838,38 +869,6 @@ void ProcessEvent(WifiEvent event) } } -/** - * @brief Wifi initialization called from app main - * - * @return sl_status_t Returns underlying Wi-Fi initialization error - */ -sl_status_t sl_matter_wifi_platform_init(void) -{ - sl_status_t status = SL_STATUS_OK; - - status = sl_net_init((sl_net_interface_t) SL_NET_WIFI_CLIENT_INTERFACE, &config, &wifi_client_context, nullptr); - VerifyOrReturnError(status == SL_STATUS_OK, status, ChipLogError(DeviceLayer, "sl_net_init failed: %lx", status)); - - // Create Sempaphore for scan completion - sScanCompleteSemaphore = osSemaphoreNew(1, 0, nullptr); - VerifyOrReturnError(sScanCompleteSemaphore != nullptr, SL_STATUS_ALLOCATION_FAILED); - - // Create Semaphore for scan in-progress protection - sScanInProgressSemaphore = osSemaphoreNew(1, 1, nullptr); - VerifyOrReturnError(sScanCompleteSemaphore != nullptr, SL_STATUS_ALLOCATION_FAILED); - - // Create the message queue - sWifiEventQueue = osMessageQueueNew(kWfxQueueSize, sizeof(WifiEvent), nullptr); - VerifyOrReturnError(sWifiEventQueue != nullptr, SL_STATUS_ALLOCATION_FAILED); - - // Create timer for DHCP polling - // TODO: Use LWIP timer instead of creating a new one here - sDHCPTimer = osTimerNew(DHCPTimerEventHandler, osTimerPeriodic, nullptr, nullptr); - VerifyOrReturnError(sDHCPTimer != nullptr, SL_STATUS_ALLOCATION_FAILED); - - return status; -} - /********************************************************************************* * @fn void sl_matter_wifi_task(void *arg) * @brief @@ -922,10 +921,10 @@ void wfx_dhcp_got_ipv4(uint32_t ip) /* * Acquire the new IP address */ - wfx_rsi.ip4_addr[0] = (ip) &HEX_VALUE_FF; - wfx_rsi.ip4_addr[1] = (ip >> 8) & HEX_VALUE_FF; - wfx_rsi.ip4_addr[2] = (ip >> 16) & HEX_VALUE_FF; - wfx_rsi.ip4_addr[3] = (ip >> 24) & HEX_VALUE_FF; + wfx_rsi.ip4_addr[0] = (ip) &0xFF; + wfx_rsi.ip4_addr[1] = (ip >> 8) & 0xFF; + wfx_rsi.ip4_addr[2] = (ip >> 16) & 0xFF; + wfx_rsi.ip4_addr[3] = (ip >> 24) & 0xFF; ChipLogDetail(DeviceLayer, "DHCP OK: IP=%d.%d.%d.%d", wfx_rsi.ip4_addr[0], wfx_rsi.ip4_addr[1], wfx_rsi.ip4_addr[2], wfx_rsi.ip4_addr[3]); /* Notify the Connectivity Manager - via the app */ @@ -933,3 +932,21 @@ void wfx_dhcp_got_ipv4(uint32_t ip) wfx_ip_changed_notify(IP_STATUS_SUCCESS); } #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ + +#if SL_ICD_ENABLED +/********************************************************************* + * @fn sl_status_t wfx_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_si91x_performance_profile_t + sl_si91x_wifi_state) + * @brief + * Implements the power save in sleepy application + * @param[in] sl_si91x_ble_state : State to set for the BLE + sl_si91x_wifi_state : State to set for the WiFi + * @return SL_STATUS_OK if successful, + * SL_STATUS_FAIL otherwise + ***********************************************************************/ +sl_status_t wfx_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, + sl_si91x_performance_profile_t sl_si91x_wifi_state) // TODO : Figure out why the extern C is necessary +{ + return (wfx_rsi_power_save(sl_si91x_ble_state, sl_si91x_wifi_state) ? SL_STATUS_FAIL : SL_STATUS_OK); +} +#endif diff --git a/examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp b/examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp index 5c3a7f7240b21d..5513ee37335319 100644 --- a/examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp +++ b/examples/platform/silabs/efr32/rs911x/Rsi91xWifiInterface.cpp @@ -50,6 +50,7 @@ extern "C" { #endif #include "WifiInterfaceAbstraction.h" +#include "WiseconnectInterfaceAbstraction.h" #include "dhcp_client.h" #include "ethernetif.h" #include "lwip/nd6.h" @@ -60,8 +61,20 @@ extern "C" { #include #include +using WifiStateFlags = chip::BitFlags; + #define WFX_QUEUE_SIZE 10 #define WFX_RSI_BUF_SZ (1024 * 10) +#define RSI_RESPONSE_MAX_SIZE (28) +#define RSI_RESPONSE_HOLD_BUFF_SIZE (128) +#define RSI_DRIVER_STATUS (0) +#define OPER_MODE_0 (0) +#define COEX_MODE_0 (0) +#define RESP_BUFF_SIZE (6) +#define AP_CHANNEL_NO_0 (0) +#define SCAN_BITMAP_OPTN_1 (1) + +WfxRsi_t wfx_rsi; static osThreadId_t sDrvThread; constexpr uint32_t kDrvTaskSize = 1792; @@ -750,7 +763,7 @@ void ProcessEvent(WifiEvent event) chip::Platform::CopyString(ap.ssid, ap.ssid_length, reinterpret_cast(scan->ssid)); // check if the scanned ssid is the one we are looking for - if (wfx_rsi.scan_ssid_length != 0 && strncmp(wfx_rsi.scan_ssid, ap.ssid, WFX_MAX_SSID_LENGTH) != CMP_SUCCESS) + if (wfx_rsi.scan_ssid_length != 0 && strncmp(wfx_rsi.scan_ssid, ap.ssid, WFX_MAX_SSID_LENGTH) != 0) { continue; // we found the targeted ssid. } @@ -861,10 +874,10 @@ void wfx_dhcp_got_ipv4(uint32_t ip) /* * Acquire the new IP address */ - wfx_rsi.ip4_addr[0] = (ip) &HEX_VALUE_FF; - wfx_rsi.ip4_addr[1] = (ip >> 8) & HEX_VALUE_FF; - wfx_rsi.ip4_addr[2] = (ip >> 16) & HEX_VALUE_FF; - wfx_rsi.ip4_addr[3] = (ip >> 24) & HEX_VALUE_FF; + wfx_rsi.ip4_addr[0] = (ip) &0xFF; + wfx_rsi.ip4_addr[1] = (ip >> 8) & 0xFF; + wfx_rsi.ip4_addr[2] = (ip >> 16) & 0xFF; + wfx_rsi.ip4_addr[3] = (ip >> 24) & 0xFF; ChipLogProgress(DeviceLayer, "DHCP OK: IP=%d.%d.%d.%d", wfx_rsi.ip4_addr[0], wfx_rsi.ip4_addr[1], wfx_rsi.ip4_addr[2], wfx_rsi.ip4_addr[3]); /* Notify the Connectivity Manager - via the app */ @@ -960,4 +973,17 @@ int32_t wfx_rsi_send_data(void * p, uint16_t len) return status; } -WfxRsi_t wfx_rsi; +#if SL_ICD_ENABLED +/********************************************************************* + * @fn sl_status_t wfx_power_save(void) + * @brief + * Implements the power save in sleepy application + * @param[in] None + * @return SL_STATUS_OK if successful, + * SL_STATUS_FAIL otherwise + ***********************************************************************/ +sl_status_t wfx_power_save(void) // TODO : Figure out why the extern C is necessary +{ + return (wfx_rsi_power_save() ? SL_STATUS_FAIL : SL_STATUS_OK); +} +#endif /* SL_ICD_ENABLED */ diff --git a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c b/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c index 443d7be4ab4a2c..75f1edcd55fd9d 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c +++ b/examples/platform/silabs/efr32/rs911x/hal/efx_spi.c @@ -43,7 +43,6 @@ #include "silabs_utils.h" #include "spi_multiplex.h" -#include "wfx_host_events.h" #ifdef SL_BOARD_NAME #include "sl_board_control.h" @@ -74,6 +73,9 @@ #define SL_SPIDRV_HANDLE sl_spidrv_eusart_exp_handle #define SL_SPIDRV_EXP_BITRATE_MULTIPLEXED SL_SPIDRV_EUSART_EXP_BITRATE +#define MIN_XLEN (0) +#define WFX_SPI_NVIC_PRIORITY (5) + #define CONCAT(A, B) (A##B) #define SPI_CLOCK(N) CONCAT(cmuClock_USART, N) // Macro to drive semaphore block minimun timer in milli seconds @@ -110,16 +112,16 @@ void sl_wfx_host_gpio_init(void) CMU_ClockEnable(cmuClock_GPIO, true); // Set CS pin to high/inactive - GPIO_PinModeSet(SL_SPIDRV_EUSART_EXP_CS_PORT, SL_SPIDRV_EUSART_EXP_CS_PIN, gpioModePushPull, PINOUT_SET); + GPIO_PinModeSet(SL_SPIDRV_EUSART_EXP_CS_PORT, SL_SPIDRV_EUSART_EXP_CS_PIN, gpioModePushPull, 1); - GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModePushPull, PINOUT_SET); - GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModePushPull, PINOUT_CLEAR); + GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModePushPull, 1); + GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModePushPull, 0); CMU_OscillatorEnable(cmuOsc_LFXO, true, true); // Set up interrupt based callback function - trigger on both edges. GPIOINT_Init(); - GPIO_PinModeSet(WFX_INTERRUPT_PIN.port, WFX_INTERRUPT_PIN.pin, gpioModeInputPull, PINOUT_CLEAR); + GPIO_PinModeSet(WFX_INTERRUPT_PIN.port, WFX_INTERRUPT_PIN.pin, gpioModeInputPull, 0); GPIO_ExtIntConfig(WFX_INTERRUPT_PIN.port, WFX_INTERRUPT_PIN.pin, SL_WFX_HOST_PINOUT_SPI_IRQ, true, false, true); GPIOINT_CallbackRegister(SL_WFX_HOST_PINOUT_SPI_IRQ, rsi_gpio_irq_cb); GPIO_IntDisable(1 << SL_WFX_HOST_PINOUT_SPI_IRQ); /* Will be enabled by RSI */ @@ -204,7 +206,7 @@ sl_status_t sl_wfx_host_spi_cs_deassert(void) if (SL_STATUS_OK == status) { GPIO_PinOutSet(SL_SPIDRV_EUSART_EXP_CS_PORT, SL_SPIDRV_EUSART_EXP_CS_PIN); - GPIO->EUSARTROUTE[SL_SPIDRV_EUSART_EXP_PERIPHERAL_NO].ROUTEEN = PINOUT_CLEAR; + GPIO->EUSARTROUTE[SL_SPIDRV_EUSART_EXP_PERIPHERAL_NO].ROUTEEN = 0; spi_enabled = false; } } @@ -267,7 +269,7 @@ sl_status_t sl_wfx_host_post_bootloader_spi_transfer(void) #endif // SL_SPICTRL_MUX return SL_STATUS_FAIL; } - GPIO->USARTROUTE[SL_MX25_FLASH_SHUTDOWN_PERIPHERAL_NO].ROUTEEN = PINOUT_CLEAR; + GPIO->USARTROUTE[SL_MX25_FLASH_SHUTDOWN_PERIPHERAL_NO].ROUTEEN = 0; #if SL_MX25CTRL_MUX sl_wfx_host_spiflash_cs_deassert(); #endif // SL_MX25CTRL_MUX @@ -300,7 +302,7 @@ sl_status_t sl_wfx_host_post_lcd_spi_transfer(void) { USART_Enable(SL_MEMLCD_SPI_PERIPHERAL, usartDisable); CMU_ClockEnable(SPI_CLOCK(SL_MEMLCD_SPI_PERIPHERAL_NO), false); - GPIO->USARTROUTE[SL_MEMLCD_SPI_PERIPHERAL_NO].ROUTEEN = PINOUT_CLEAR; + GPIO->USARTROUTE[SL_MEMLCD_SPI_PERIPHERAL_NO].ROUTEEN = 0; sl_status_t status = sl_board_disable_display(); #if SL_SPICTRL_MUX xSemaphoreGive(spi_sem_sync_hdl); diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c index 3c67d3955229c8..8bd277e6242c4d 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c +++ b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_interrupt.c @@ -35,8 +35,6 @@ #include "event_groups.h" #include "task.h" -#include "wfx_host_events.h" - #if (SLI_SI91X_MCU_INTERFACE | EXP_BOARD) #include "sl_board_configuration.h" diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c index df3438b6ed5409..ba517b417bdff7 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c +++ b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_ioports.c @@ -35,8 +35,6 @@ #include "event_groups.h" #include "task.h" -#include "wfx_host_events.h" - #include "rsi_board_configuration.h" #include "rsi_driver.h" /*===========================================================*/ @@ -63,17 +61,17 @@ void rsi_hal_config_gpio(uint8_t gpio_number, uint8_t mode, uint8_t value) { case RSI_HAL_SLEEP_CONFIRM_PIN: case RSI_HAL_LP_SLEEP_CONFIRM_PIN: - GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModeWiredOrPullDown, PINOUT_SET); + GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModeWiredOrPullDown, 1); break; case RSI_HAL_WAKEUP_INDICATION_PIN: #ifndef LOGGING_STATS - GPIO_PinModeSet(WAKE_INDICATOR_PIN.port, WAKE_INDICATOR_PIN.pin, gpioModeWiredOrPullDown, PINOUT_CLEAR); + GPIO_PinModeSet(WAKE_INDICATOR_PIN.port, WAKE_INDICATOR_PIN.pin, gpioModeWiredOrPullDown, 0); #else - GPIO_PinModeSet(LOGGING_WAKE_INDICATOR_PIN.port, LOGGING_WAKE_INDICATOR_PIN.pin, gpioModeWiredOrPullDown, PINOUT_CLEAR); + GPIO_PinModeSet(LOGGING_WAKE_INDICATOR_PIN.port, LOGGING_WAKE_INDICATOR_PIN.pin, gpioModeWiredOrPullDown, 0); #endif break; case RSI_HAL_RESET_PIN: - GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModePushPull, PINOUT_SET); + GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModePushPull, 1); break; default: break; @@ -95,17 +93,17 @@ void rsi_hal_set_gpio(uint8_t gpio_number) { case RSI_HAL_SLEEP_CONFIRM_PIN: case RSI_HAL_LP_SLEEP_CONFIRM_PIN: - GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModeWiredOrPullDown, PINOUT_SET); + GPIO_PinModeSet(WFX_SLEEP_CONFIRM_PIN.port, WFX_SLEEP_CONFIRM_PIN.pin, gpioModeWiredOrPullDown, 1); break; case RSI_HAL_WAKEUP_INDICATION_PIN: #ifndef LOGGING_STATS - GPIO_PinModeSet(WAKE_INDICATOR_PIN.port, WAKE_INDICATOR_PIN.pin, gpioModeInput, PINOUT_SET); + GPIO_PinModeSet(WAKE_INDICATOR_PIN.port, WAKE_INDICATOR_PIN.pin, gpioModeInput, 1); #else - GPIO_PinModeSet(LOGGING_WAKE_INDICATOR_PIN.port, LOGGING_WAKE_INDICATOR_PIN.pin, gpioModeInput, PINOUT_SET); + GPIO_PinModeSet(LOGGING_WAKE_INDICATOR_PIN.port, LOGGING_WAKE_INDICATOR_PIN.pin, gpioModeInput, 1); #endif break; case RSI_HAL_RESET_PIN: - GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModeWiredOrPullDown, PINOUT_SET); + GPIO_PinModeSet(WFX_RESET_PIN.port, WFX_RESET_PIN.pin, gpioModeWiredOrPullDown, 1); break; default: break; diff --git a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c index 0f0c39a680bd68..9c1b1377487a75 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c +++ b/examples/platform/silabs/efr32/rs911x/hal/rsi_hal_mcu_timer.c @@ -34,8 +34,6 @@ extern void SysTick_Handler(void); extern void xPortSysTickHandler(void); #endif /* SysTick */ #endif /* RSI_WITH_OS */ -#include "wfx_host_events.h" - /* RSI Driver include file */ #include "rsi_driver.h" /* RSI WLAN Config include file */ @@ -51,6 +49,8 @@ extern void xPortSysTickHandler(void); #include "rsi_wlan_config.h" #define WFX_RSI_NUM_TIMERS (2) /* Number of RSI timers to alloc */ +#define CONVERT_SEC_TO_MSEC (1000) +#define CONVERT_USEC_TO_MSEC (1 / 1000) #ifndef _use_the_rsi_defined_functions @@ -135,7 +135,7 @@ int32_t rsi_timer_start(uint8_t timer_node, uint8_t mode, uint8_t type, uint32_t return RSI_ERROR_INSUFFICIENT_BUFFER; } - (void) xTimerStart(tp->handle, TIMER_TICKS_TO_WAIT_0); + (void) xTimerStart(tp->handle, pdMS_TO_TICKS(0)); return RSI_ERROR_NONE; } diff --git a/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c b/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c index d6b67440364832..1d1ab1409c4161 100644 --- a/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c +++ b/examples/platform/silabs/efr32/rs911x/hal/sl_si91x_ncp_utility.c @@ -46,7 +46,6 @@ #include "silabs_utils.h" #include "sl_si91x_ncp_utility.h" -#include "wfx_host_events.h" #if SL_MX25CTRL_MUX sl_status_t sl_wfx_host_spiflash_cs_assert(void); @@ -220,7 +219,7 @@ sl_status_t sl_wfx_host_post_bootloader_spi_transfer(void) #endif // SL_SPICTRL_MUX return SL_STATUS_FAIL; } - GPIO->USARTROUTE[SL_MX25_FLASH_SHUTDOWN_PERIPHERAL_NO].ROUTEEN = PINOUT_CLEAR; + GPIO->USARTROUTE[SL_MX25_FLASH_SHUTDOWN_PERIPHERAL_NO].ROUTEEN = 0; #if SL_MX25CTRL_MUX sl_wfx_host_spiflash_cs_deassert(); #endif // SL_MX25CTRL_MUX diff --git a/examples/platform/silabs/efr32/rs911x/rs9117.gni b/examples/platform/silabs/efr32/rs911x/rs9117.gni index 63f027e59f9087..87e3caeeb74ad5 100644 --- a/examples/platform/silabs/efr32/rs911x/rs9117.gni +++ b/examples/platform/silabs/efr32/rs911x/rs9117.gni @@ -22,6 +22,7 @@ rs911x_src_plat = [ "${examples_plat_dir}/rs911x/hal/sl_si91x_ncp_utility.c", "${examples_plat_dir}/rs911x/hal/efx32_ncp_host.c", "${silabs_common_plat_dir}/wifi/WifiInterfaceAbstraction.cpp", + "${silabs_common_plat_dir}/wifi/WiseconnectInterfaceAbstraction.cpp", ] rs9117_inc_plat = [ diff --git a/examples/platform/silabs/efr32/rs911x/rs911x.gni b/examples/platform/silabs/efr32/rs911x/rs911x.gni index 4aedb66dca9f0c..068d5abdb349c7 100644 --- a/examples/platform/silabs/efr32/rs911x/rs911x.gni +++ b/examples/platform/silabs/efr32/rs911x/rs911x.gni @@ -23,6 +23,7 @@ rs911x_src_plat = [ "${examples_plat_dir}/rs911x/hal/rsi_hal_mcu_timer.c", "${examples_plat_dir}/rs911x/hal/efx_spi.c", "${silabs_common_plat_dir}/wifi/WifiInterfaceAbstraction.cpp", + "${silabs_common_plat_dir}/wifi/WiseconnectInterfaceAbstraction.cpp", ] # diff --git a/examples/platform/silabs/efr32/wf200/Wf200WifiInterface.cpp b/examples/platform/silabs/efr32/wf200/Wf200WifiInterface.cpp index e38f4c43a27e67..0aec9baa4dccae 100644 --- a/examples/platform/silabs/efr32/wf200/Wf200WifiInterface.cpp +++ b/examples/platform/silabs/efr32/wf200/Wf200WifiInterface.cpp @@ -15,35 +15,31 @@ * limitations under the License. */ -/* Includes */ - -#include -#include -#include - +#include "AppConfig.h" +#include "FreeRTOS.h" +#include "dhcp_client.h" #include "em_bus.h" #include "em_cmu.h" #include "em_gpio.h" #include "em_ldma.h" #include "em_usart.h" +#include "ethernetif.h" +#include "event_groups.h" #include "gpiointerrupt.h" - -#include "AppConfig.h" #include "sl_wfx_board.h" +#include "sl_wfx_cmd_api.h" +#include "sl_wfx_constants.h" #include "sl_wfx_host.h" #include "sl_wfx_task.h" -#include "wfx_host_events.h" - -#include "FreeRTOS.h" -#include "event_groups.h" #include "task.h" - -#include "dhcp_client.h" -#include "ethernetif.h" +#include "wfx_host_events.h" #include #include #include #include +#include +#include +#include using namespace ::chip; using namespace ::chip::DeviceLayer; @@ -68,9 +64,30 @@ static wfx_wifi_scan_result_t ap_info; #define PASSIVE_CHANNEL_TIME 0 #define NUM_PROBE_REQUEST 2 -// wfx_fmac_driver context -sl_wfx_context_t wifiContext; -static uint8_t wifi_extra; +/* Wi-Fi bitmask events - for the task */ +#define SL_WFX_CONNECT (1 << 1) +#define SL_WFX_DISCONNECT (1 << 2) +#define SL_WFX_START_AP (1 << 3) +#define SL_WFX_STOP_AP (1 << 4) +#define SL_WFX_SCAN_START (1 << 5) +#define SL_WFX_SCAN_COMPLETE (1 << 6) +#define SL_WFX_RETRY_CONNECT (1 << 7) + +#define WLAN_TASK_STACK_SIZE (1024) +#define ETH_FRAME (0) +#define AP_START_SUCCESS (0) +#define BITS_TO_WAIT (0) +#define BEACON_1 (0) +#define CHANNEL_LIST ((const uint8_t *) 0) +#define CHANNEL_COUNT (0) +#define IE_DATA ((const uint8_t *) 0) +#define IE_DATA_LENGTH (0) +#define BSSID_SCAN ((const uint8_t *) 0) +#define CHANNEL_0 (0) +#define PREVENT_ROAMING (1) +#define DISABLE_PMF_MODE (0) +#define STA_IP_FAIL (0) +#define WLAN_TASK_PRIORITY (1) /***************************************************************************** * macros @@ -90,8 +107,6 @@ uint8_t softap_channel = SOFTAP_CHANNEL_DEFAULT; /* station network interface structures */ struct netif * sta_netif; wfx_wifi_provision_t wifi_provision; -sl_wfx_get_counters_cnf_t * counters; -sl_wfx_get_counters_cnf_t * Tempcounters; #define PUT_COUNTER(name) ChipLogDetail(DeviceLayer, "%-24s %lu", #name, (unsigned long) counters->body.count_##name); bool hasNotifiedIPV6 = false; @@ -131,6 +146,162 @@ static void sl_wfx_ap_client_rejected_callback(uint32_t status, uint8_t * mac); extern uint32_t gOverrunCount; +namespace { + +// wfx_fmac_driver context +sl_wfx_context_t wifiContext; +uint8_t wifi_extra; + +typedef struct __attribute__((__packed__)) sl_wfx_get_counters_cnf_body_s +{ + uint32_t status; + uint16_t mib_id; + uint16_t length; + uint32_t rcpi; + uint32_t count_plcp_errors; + uint32_t count_fcs_errors; + uint32_t count_tx_packets; + uint32_t count_rx_packets; + uint32_t count_rx_packet_errors; + uint32_t count_rx_decryption_failures; + uint32_t count_rx_mic_failures; + uint32_t count_rx_no_key_failures; + uint32_t count_tx_multicast_frames; + uint32_t count_tx_frames_success; + uint32_t count_tx_frame_failures; + uint32_t count_tx_frames_retried; + uint32_t count_tx_frames_multi_retried; + uint32_t count_rx_frame_duplicates; + uint32_t count_rts_success; + uint32_t count_rts_failures; + uint32_t count_ack_failures; + uint32_t count_rx_multicast_frames; + uint32_t count_rx_frames_success; + uint32_t count_rx_cmacicv_errors; + uint32_t count_rx_cmac_replays; + uint32_t count_rx_mgmt_ccmp_replays; + uint32_t count_rx_bipmic_errors; + uint32_t count_rx_beacon; + uint32_t count_miss_beacon; + uint32_t reserved[15]; +} sl_wfx_get_counters_cnf_body_t; + +typedef struct __attribute__((__packed__)) sl_wfx_get_counters_cnf_s +{ + /** Common message header. */ + sl_wfx_header_t header; + /** Confirmation message body. */ + sl_wfx_get_counters_cnf_body_t body; +} sl_wfx_get_counters_cnf_t; + +typedef struct __attribute__((__packed__)) sl_wfx_mib_req_body_s +{ + uint16_t mib_id; ///< ID of the MIB to be read. + uint16_t reserved; +} sl_wfx_mib_req_body_t; + +typedef struct __attribute__((__packed__)) sl_wfx_header_mib_s +{ + uint16_t length; ///< Message length in bytes including this uint16_t. + ///< Maximum value is 8188 but maximum Request size is FW dependent and reported in the + ///< ::sl_wfx_startup_ind_body_t::size_inp_ch_buf. + uint8_t id; ///< Contains the message Id indexed by sl_wfx_general_commands_ids_t or sl_wfx_message_ids_t. + uint8_t reserved : 1; + uint8_t interface : 2; + uint8_t seqnum : 3; + uint8_t encrypted : 2; +} sl_wfx_header_mib_t; + +typedef struct __attribute__((__packed__)) sl_wfx_mib_req_s +{ + /** Common message header. */ + sl_wfx_header_mib_t header; + /** Request message body. */ + sl_wfx_mib_req_body_t body; +} sl_wfx_mib_req_t; + +sl_wfx_get_counters_cnf_t * counters; + +/**************************************************************************** + * @brief + * get the wifi state + * @return returns wificonetext state + *****************************************************************************/ +sl_wfx_state_t wfx_get_wifi_state(void) +{ + return wifiContext.state; +} + +sl_status_t get_all_counters(void) +{ + sl_status_t result; + uint8_t command_id = 0x05; + uint16_t mib_id = 0x2035; + sl_wfx_mib_req_t * request = nullptr; + uint32_t request_length = SL_WFX_ROUND_UP_EVEN(sizeof(sl_wfx_header_mib_t) + sizeof(sl_wfx_mib_req_body_t)); + + result = + sl_wfx_allocate_command_buffer((sl_wfx_generic_message_t **) &request, command_id, SL_WFX_CONTROL_BUFFER, request_length); + + VerifyOrReturnError(request != nullptr, SL_STATUS_NULL_POINTER); + + request->body.mib_id = mib_id; + request->header.interface = 0x2; + request->header.encrypted = 0x0; + + result = sl_wfx_send_request(command_id, (sl_wfx_generic_message_t *) request, request_length); + SL_WFX_ERROR_CHECK(result); + + result = sl_wfx_host_wait_for_confirmation(command_id, SL_WFX_DEFAULT_REQUEST_TIMEOUT_MS, (void **) &counters); + SL_WFX_ERROR_CHECK(result); + + ChipLogDetail(DeviceLayer, "%-24s %12s ", "", "Debug Counters Content"); + ChipLogDetail(DeviceLayer, "%-24s %lu", "rcpi", (unsigned long) counters->body.rcpi); + PUT_COUNTER(plcp_errors); + PUT_COUNTER(fcs_errors); + PUT_COUNTER(tx_packets); + PUT_COUNTER(rx_packets); + PUT_COUNTER(rx_packet_errors); + PUT_COUNTER(rx_decryption_failures); + PUT_COUNTER(rx_mic_failures); + PUT_COUNTER(rx_no_key_failures); + PUT_COUNTER(tx_multicast_frames); + PUT_COUNTER(tx_frames_success); + PUT_COUNTER(tx_frame_failures); + PUT_COUNTER(tx_frames_retried); + PUT_COUNTER(tx_frames_multi_retried); + PUT_COUNTER(rx_frame_duplicates); + PUT_COUNTER(rts_success); + PUT_COUNTER(rts_failures); + PUT_COUNTER(ack_failures); + PUT_COUNTER(rx_multicast_frames); + PUT_COUNTER(rx_frames_success); + PUT_COUNTER(rx_cmacicv_errors); + PUT_COUNTER(rx_cmac_replays); + PUT_COUNTER(rx_mgmt_ccmp_replays); + PUT_COUNTER(rx_bipmic_errors); + PUT_COUNTER(rx_beacon); + PUT_COUNTER(miss_beacon); + +error_handler: + + if (result == SL_STATUS_TIMEOUT) + { + if (sl_wfx_context->used_buffers > 0) + { + sl_wfx_context->used_buffers--; + } + } + if (request != nullptr) + { + sl_wfx_free_command_buffer((sl_wfx_generic_message_t *) request, command_id, SL_WFX_CONTROL_BUFFER); + } + + return result; +} + +} // namespace + /*************************************************************************** * @brief * Creates WFX events processing task. @@ -278,7 +449,7 @@ static void sl_wfx_scan_result_callback(sl_wfx_scan_result_ind_body_t * scan_res /* don't save if filter only wants specific ssid */ if (scan_ssid != nullptr) { - if (strcmp(scan_ssid, (char *) &scan_result->ssid_def.ssid[0]) != CMP_SUCCESS) + if (strcmp(scan_ssid, (char *) &scan_result->ssid_def.ssid[0]) != 0) return; } if ((ap = (struct scan_result_holder *) (chip::Platform::MemoryAlloc(sizeof(*ap)))) == (struct scan_result_holder *) 0) @@ -779,74 +950,6 @@ int32_t wfx_get_ap_ext(wfx_wifi_scan_ext_t * extra_info) return status; } -sl_status_t get_all_counters(void) -{ - sl_status_t result; - uint8_t command_id = 0x05; - uint16_t mib_id = 0x2035; - sl_wfx_mib_req_t * request = nullptr; - uint32_t request_length = SL_WFX_ROUND_UP_EVEN(sizeof(sl_wfx_header_mib_t) + sizeof(sl_wfx_mib_req_body_t)); - - result = - sl_wfx_allocate_command_buffer((sl_wfx_generic_message_t **) &request, command_id, SL_WFX_CONTROL_BUFFER, request_length); - - VerifyOrReturnError(request != nullptr, SL_STATUS_NULL_POINTER); - - request->body.mib_id = mib_id; - request->header.interface = 0x2; - request->header.encrypted = 0x0; - - result = sl_wfx_send_request(command_id, (sl_wfx_generic_message_t *) request, request_length); - SL_WFX_ERROR_CHECK(result); - - result = sl_wfx_host_wait_for_confirmation(command_id, SL_WFX_DEFAULT_REQUEST_TIMEOUT_MS, (void **) &counters); - SL_WFX_ERROR_CHECK(result); - - ChipLogDetail(DeviceLayer, "%-24s %12s ", "", "Debug Counters Content"); - ChipLogDetail(DeviceLayer, "%-24s %lu", "rcpi", (unsigned long) counters->body.rcpi); - PUT_COUNTER(plcp_errors); - PUT_COUNTER(fcs_errors); - PUT_COUNTER(tx_packets); - PUT_COUNTER(rx_packets); - PUT_COUNTER(rx_packet_errors); - PUT_COUNTER(rx_decryption_failures); - PUT_COUNTER(rx_mic_failures); - PUT_COUNTER(rx_no_key_failures); - PUT_COUNTER(tx_multicast_frames); - PUT_COUNTER(tx_frames_success); - PUT_COUNTER(tx_frame_failures); - PUT_COUNTER(tx_frames_retried); - PUT_COUNTER(tx_frames_multi_retried); - PUT_COUNTER(rx_frame_duplicates); - PUT_COUNTER(rts_success); - PUT_COUNTER(rts_failures); - PUT_COUNTER(ack_failures); - PUT_COUNTER(rx_multicast_frames); - PUT_COUNTER(rx_frames_success); - PUT_COUNTER(rx_cmacicv_errors); - PUT_COUNTER(rx_cmac_replays); - PUT_COUNTER(rx_mgmt_ccmp_replays); - PUT_COUNTER(rx_bipmic_errors); - PUT_COUNTER(rx_beacon); - PUT_COUNTER(miss_beacon); - -error_handler: - - if (result == SL_STATUS_TIMEOUT) - { - if (sl_wfx_context->used_buffers > 0) - { - sl_wfx_context->used_buffers--; - } - } - if (request != nullptr) - { - sl_wfx_free_command_buffer((sl_wfx_generic_message_t *) request, command_id, SL_WFX_CONTROL_BUFFER); - } - - return result; -} - /************************************************************************ * @brief * reset the count @@ -877,16 +980,6 @@ sl_status_t wfx_wifi_start(void) return SL_STATUS_OK; } -/**************************************************************************** - * @brief - * get the wifi state - * @return returns wificonetext state - *****************************************************************************/ -sl_wfx_state_t wfx_get_wifi_state(void) -{ - return wifiContext.state; -} - /**************************************************************************** * @brief * getnetif using interface @@ -909,19 +1002,6 @@ struct netif * wfx_GetNetif(sl_wfx_interface_t interface) return SelectedNetif; } -/**************************************************************************** - * @brief - * get the wifi mac address using interface - * @param[in] interface: - * @return returns wificontext.mac_addr_o if successful, - * wificontext.mac_addr_1 otherwise - *****************************************************************************/ -sl_wfx_mac_address_t wfx_get_wifi_mac_addr(sl_wfx_interface_t interface) -{ - // return Mac address used by WFX SL_WFX_STA_INTERFACE or SL_WFX_SOFTAP_INTERFACE, - return (interface == SL_WFX_STA_INTERFACE) ? wifiContext.mac_addr_0 : wifiContext.mac_addr_1; -} - /**************************************************************************** * @brief * set the wifi provision @@ -960,17 +1040,6 @@ void wfx_clear_wifi_provision(void) memset(&wifi_provision, 0, sizeof(wifi_provision)); } -/**************************************************************************** - * @brief - * driver STA provisioned - * @return returns true if successful, - * false otherwise - *****************************************************************************/ -bool wfx_is_sta_provisioned(void) -{ - return (wifi_provision.ssid[0]) ? true : false; -} - /**************************************************************************** * @fn sl_status_t wfx_connect_to_ap(void) * @brief @@ -1147,10 +1216,10 @@ void wfx_dhcp_got_ipv4(uint32_t ip) */ uint8_t ip4_addr[4]; - ip4_addr[0] = (ip) &HEX_VALUE_FF; - ip4_addr[1] = (ip >> 8) & HEX_VALUE_FF; - ip4_addr[2] = (ip >> 16) & HEX_VALUE_FF; - ip4_addr[3] = (ip >> 24) & HEX_VALUE_FF; + ip4_addr[0] = (ip) &0xFF; + ip4_addr[1] = (ip >> 8) & 0xFF; + ip4_addr[2] = (ip >> 16) & 0xFF; + ip4_addr[3] = (ip >> 24) & 0xFF; ChipLogDetail(DeviceLayer, "DHCP IP=%d.%d.%d.%d", ip4_addr[0], ip4_addr[1], ip4_addr[2], ip4_addr[3]); sta_ip = ip; diff --git a/examples/platform/silabs/efr32/wf200/efr_spi.c b/examples/platform/silabs/efr32/wf200/efr_spi.c index 3ef34c928e0363..b5a31cbaafd22c 100644 --- a/examples/platform/silabs/efr32/wf200/efr_spi.c +++ b/examples/platform/silabs/efr32/wf200/efr_spi.c @@ -40,7 +40,6 @@ #include "spidrv.h" #include "spi_multiplex.h" -#include "wfx_host_events.h" #if defined(SL_CATALOG_POWER_MANAGER_PRESENT) #include "sl_power_manager.h" diff --git a/examples/platform/silabs/efr32/wf200/wf200_init.c b/examples/platform/silabs/efr32/wf200/wf200_init.c index 3631216e767a0c..40f1aaf08af6bb 100644 --- a/examples/platform/silabs/efr32/wf200/wf200_init.c +++ b/examples/platform/silabs/efr32/wf200/wf200_init.c @@ -40,7 +40,6 @@ #include "AppConfig.h" #include "sl_wfx_host.h" #include "sl_wfx_task.h" -#include "wfx_host_events.h" #include "sl_spidrv_instances.h" #include "spidrv.h" @@ -258,7 +257,7 @@ sl_status_t sl_wfx_host_set_wake_up_pin(uint8_t state) CORE_DECLARE_IRQ_STATE; CORE_ENTER_ATOMIC(); - if (state > PINOUT_CLEAR_STATUS) + if (state > 0) { #ifdef SLEEP_ENABLED #ifdef SL_WFX_USE_SDIO @@ -320,8 +319,7 @@ sl_status_t sl_wfx_host_reset_chip(void) *****************************************************************************/ sl_status_t sl_wfx_host_wait_for_wake_up(void) { - xSemaphoreTake(wfx_wakeup_sem, pdMS_TO_TICKS(TICKS_TO_WAIT_0)); - xSemaphoreTake(wfx_wakeup_sem, pdMS_TO_TICKS(TICKS_TO_WAIT_3)); + xSemaphoreTake(wfx_wakeup_sem, pdMS_TO_TICKS(3)); return SL_STATUS_OK; } @@ -388,7 +386,7 @@ sl_status_t sl_wfx_host_wait_for_confirmation(uint8_t confirmation_id, uint32_t for (uint32_t i = 0; i < timeout; i++) { /* Wait for an event posted by the function sl_wfx_host_post_event() */ - if (xQueueReceive(wfx_event_Q, &posted_event_id, TICKS_TO_WAIT_1) == pdTRUE) + if (xQueueReceive(wfx_event_Q, &posted_event_id, 1) == pdTRUE) { /* Once a message is received, check if it is the expected ID */ if (confirmation_id == posted_event_id) @@ -418,7 +416,7 @@ sl_status_t sl_wfx_host_lock(void) sl_status_t status = SL_STATUS_OK; - if (xSemaphoreTake(wfx_mutex, pdMS_TO_TICKS(TICKS_TO_WAIT_500)) != pdTRUE) + if (xSemaphoreTake(wfx_mutex, pdMS_TO_TICKS(500)) != pdTRUE) { SILABS_LOG("*ERR*Wi-Fi driver mutex timo"); status = SL_STATUS_TIMEOUT; diff --git a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp index 7c1a9d233b0d55..cd041d452ffe64 100644 --- a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp +++ b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.cpp @@ -22,7 +22,6 @@ #include "wfx_host_events.h" #include #include -#include #include #include #include @@ -34,7 +33,7 @@ using namespace chip; using namespace chip::DeviceLayer; -using WifiStateFlags = chip::BitFlags; +#define CONVERT_SEC_TO_MS(TimeInS) (TimeInS * 1000) namespace { @@ -44,22 +43,6 @@ constexpr uint8_t kWlanRetryIntervalInSec = 5; uint8_t retryInterval = kWlanMinRetryIntervalsInSec; osTimerId_t sRetryTimer; -// TODO: Remove this when the full abstraction is implemented -#ifdef RS911X_WIFI -// Thread for the WLAN RSI -osThreadId_t sWlanThread; -constexpr uint32_t kWlanTaskSize = 2048; -uint8_t wlanStack[kWlanTaskSize]; -osThread_t sWlanTaskControlBlock; -constexpr osThreadAttr_t kWlanTaskAttr = { .name = "wlan_rsi", - .attr_bits = osThreadDetached, - .cb_mem = &sWlanTaskControlBlock, - .cb_size = osThreadCbSize, - .stack_mem = wlanStack, - .stack_size = kWlanTaskSize, - .priority = osPriorityAboveNormal7 }; -#endif // RS911X_WIFI - /* * Notifications to the upper-layer * All done in the context of the RSI/WiFi task (rsi_if.c) @@ -77,354 +60,6 @@ void RetryConnectionTimerHandler(void * arg) } // namespace -// TODO: Remove this when the full abstraction is implemented -#ifdef RS911X_WIFI -/********************************************************************* - * @fn sl_status_t wfx_wifi_start(void) - * @brief - * Called from ConnectivityManagerImpl.cpp - to enable the device - * Create the RSI task and let it deal with life. - * @param[in] None - * @return Returns SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - ***********************************************************************/ -sl_status_t wfx_wifi_start(void) -{ - VerifyOrReturnError(!(wfx_rsi.dev_state.Has(WifiState::kStationStarted)), SL_STATUS_OK); - wfx_rsi.dev_state.Set(WifiState::kStationStarted); - - // Creating a Wi-Fi driver thread - sWlanThread = osThreadNew(sl_matter_wifi_task, NULL, &kWlanTaskAttr); - - VerifyOrReturnError(sWlanThread != NULL, SL_STATUS_FAIL); - - ChipLogProgress(DeviceLayer, "sl_matter_wifi_task created successfully"); - return SL_STATUS_OK; -} - -/********************************************************************* - * @fn void wfx_enable_sta_mode(void) - * @brief - * driver enable the STA mode - * @param[in] None - * @return None - ***********************************************************************/ -void wfx_enable_sta_mode(void) -{ - wfx_rsi.dev_state.Set(WifiState::kStationMode); -} - -/********************************************************************* - * @fn bool wfx_is_sta_mode_enabled(void) - * @brief - * driver enabled the STA mode - * @param[in] None - * @return mode - ***********************************************************************/ -bool wfx_is_sta_mode_enabled(void) -{ - return wfx_rsi.dev_state.Has(WifiState::kStationMode); -} - -/********************************************************************* - * @fn void wfx_get_wifi_mac_addr(sl_wfx_interface_t interface, sl_wfx_mac_address_t *addr) - * @brief - * get the wifi mac address - * @param[in] Interface: - * @param[in] addr : address - * @return - * None - ***********************************************************************/ -void wfx_get_wifi_mac_addr(sl_wfx_interface_t interface, sl_wfx_mac_address_t * addr) -{ - VerifyOrReturn(addr != nullptr); -#ifdef SL_WFX_CONFIG_SOFTAP - *addr = (interface == SL_WFX_SOFTAP_INTERFACE) ? wfx_rsi.softap_mac : wfx_rsi.sta_mac; -#else - *addr = wfx_rsi.sta_mac; -#endif -} - -/********************************************************************* - * @fn void wfx_set_wifi_provision(wfx_wifi_provision_t *cfg) - * @brief - * Driver set the wifi provision - * @param[in] cfg: wifi configuration - * @return - * None - ***********************************************************************/ -void wfx_set_wifi_provision(wfx_wifi_provision_t * cfg) -{ - VerifyOrReturn(cfg != nullptr); - wfx_rsi.sec = *cfg; - wfx_rsi.dev_state.Set(WifiState::kStationProvisioned); -} - -/********************************************************************* - * @fn bool wfx_get_wifi_provision(wfx_wifi_provision_t *wifiConfig) - * @brief - * Driver get the wifi provision - * @param[in] wifiConfig: wifi configuration - * @return return false if successful, - * true otherwise - ***********************************************************************/ -bool wfx_get_wifi_provision(wfx_wifi_provision_t * wifiConfig) -{ - VerifyOrReturnError(wifiConfig != nullptr, false); - VerifyOrReturnError(wfx_rsi.dev_state.Has(WifiState::kStationProvisioned), false); - *wifiConfig = wfx_rsi.sec; - return true; -} - -/********************************************************************* - * @fn void wfx_clear_wifi_provision(void) - * @brief - * Driver is clear the wifi provision - * @param[in] None - * @return None - ***********************************************************************/ -void wfx_clear_wifi_provision(void) -{ - memset(&wfx_rsi.sec, 0, sizeof(wfx_rsi.sec)); - wfx_rsi.dev_state.Clear(WifiState::kStationProvisioned); - ChipLogProgress(DeviceLayer, "Clear WiFi Provision"); -} - -/************************************************************************* - * @fn sl_status_t wfx_connect_to_ap(void) - * @brief - * Start a JOIN command to the AP - Done by the wfx_rsi task - * @param[in] None - * @return returns SL_STATUS_OK if successful - ****************************************************************************/ -sl_status_t wfx_connect_to_ap(void) -{ - VerifyOrReturnError(wfx_rsi.dev_state.Has(WifiState::kStationProvisioned), SL_STATUS_INVALID_CONFIGURATION); - VerifyOrReturnError(wfx_rsi.sec.ssid_length, SL_STATUS_INVALID_CREDENTIALS); - VerifyOrReturnError(wfx_rsi.sec.ssid_length <= WFX_MAX_SSID_LENGTH, SL_STATUS_HAS_OVERFLOWED); - ChipLogProgress(DeviceLayer, "connect to access point: %s", wfx_rsi.sec.ssid); - - WifiEvent event = WifiEvent::kStationStartJoin; - sl_matter_wifi_post_event(event); - return SL_STATUS_OK; -} - -#if SL_ICD_ENABLED -#if SLI_SI917 -/********************************************************************* - * @fn sl_status_t wfx_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_si91x_performance_profile_t - sl_si91x_wifi_state) - * @brief - * Implements the power save in sleepy application - * @param[in] sl_si91x_ble_state : State to set for the BLE - sl_si91x_wifi_state : State to set for the WiFi - * @return SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - ***********************************************************************/ -sl_status_t wfx_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_si91x_performance_profile_t sl_si91x_wifi_state) -{ - return (wfx_rsi_power_save(sl_si91x_ble_state, sl_si91x_wifi_state) ? SL_STATUS_FAIL : SL_STATUS_OK); -} -#else // For RS9116 -/********************************************************************* - * @fn sl_status_t wfx_power_save(void) - * @brief - * Implements the power save in sleepy application - * @param[in] None - * @return SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - ***********************************************************************/ -sl_status_t wfx_power_save(void) -{ - return (wfx_rsi_power_save() ? SL_STATUS_FAIL : SL_STATUS_OK); -} -#endif /* SLI_SI917 */ -#endif /* SL_ICD_ENABLED */ - -/********************************************************************* - * @fn void wfx_setup_ip6_link_local(sl_wfx_interface_t whichif) - * @brief - * Implement the ipv6 setup - * @param[in] whichif: - * @return None - ***********************************************************************/ -void wfx_setup_ip6_link_local(sl_wfx_interface_t whichif) -{ - /* - * TODO: Implement IPV6 setup, currently in sl_matter_wifi_task() - * This is hooked with MATTER code. - */ -} - -/********************************************************************* - * @fn bool wfx_is_sta_connected(void) - * @brief - * called fuction when driver is connected to STA - * @param[in] None - * @return returns ture if successful, - * false otherwise - ***********************************************************************/ -bool wfx_is_sta_connected(void) -{ - return wfx_rsi.dev_state.Has(WifiState::kStationConnected); -} - -/********************************************************************* - * @fn wifi_mode_t wfx_get_wifi_mode(void) - * @brief - * get the wifi mode - * @param[in] None - * @return return WIFI_MODE_NULL if successful, - * WIFI_MODE_STA otherwise - ***********************************************************************/ -wifi_mode_t wfx_get_wifi_mode(void) -{ - if (wfx_rsi.dev_state.Has(WifiState::kStationInit)) - return WIFI_MODE_STA; - return WIFI_MODE_NULL; -} - -/********************************************************************* - * @fn sl_status_t sl_matter_wifi_disconnect(void) - * @brief - * called fuction when STA disconnected - * @param[in] None - * @return return SL_STATUS_OK if successful, - * SL_STATUS_FAIL otherwise - ***********************************************************************/ -sl_status_t sl_matter_wifi_disconnect(void) -{ - sl_status_t status; - status = sl_wifi_platform_disconnect(); - wfx_rsi.dev_state.Clear(WifiState::kStationConnected); - return status; -} -#if CHIP_DEVICE_CONFIG_ENABLE_IPV4 -/********************************************************************* - * @fn bool wfx_have_ipv4_addr(sl_wfx_interface_t which_if) - * @brief - * called fuction when driver have ipv4 address - * @param[in] which_if: - * @return returns ture if successful, - * false otherwise - ***********************************************************************/ -bool wfx_have_ipv4_addr(sl_wfx_interface_t which_if) -{ - VerifyOrReturnError(which_if == SL_WFX_STA_INTERFACE, false); - return wfx_rsi.dev_state.Has(WifiState::kStationDhcpDone); -} -#endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ - -/********************************************************************* - * @fn bool wfx_have_ipv6_addr(sl_wfx_interface_t which_if) - * @brief - * called fuction when driver have ipv6 address - * @param[in] which_if: - * @return returns ture if successful, - * false otherwise - ***********************************************************************/ -bool wfx_have_ipv6_addr(sl_wfx_interface_t which_if) -{ - VerifyOrReturnError(which_if == SL_WFX_STA_INTERFACE, false); - // TODO: WifiState::kStationConnected does not guarantee SLAAC IPv6 LLA, maybe use a different FLAG - return wfx_rsi.dev_state.Has(WifiState::kStationConnected); -} - -/********************************************************************* - * @fn bool wfx_hw_ready(void) - * @brief - * called fuction when driver ready - * @param[in] None - * @return returns ture if successful, - * false otherwise - ***********************************************************************/ -bool wfx_hw_ready(void) -{ - return wfx_rsi.dev_state.Has(WifiState::kStationInit); -} - -/********************************************************************* - * @fn int32_t wfx_get_ap_info(wfx_wifi_scan_result_t *ap) - * @brief - * get the access point information - * @param[in] ap: access point - * @return - * access point information - ***********************************************************************/ -int32_t wfx_get_ap_info(wfx_wifi_scan_result_t * ap) -{ - return wfx_rsi_get_ap_info(ap); -} - -/********************************************************************* - * @fn int32_t wfx_get_ap_ext(wfx_wifi_scan_ext_t *extra_info) - * @brief - * get the access point extra information - * @param[in] extra_info:access point extra information - * @return - * access point extra information - ***********************************************************************/ -int32_t wfx_get_ap_ext(wfx_wifi_scan_ext_t * extra_info) -{ - return wfx_rsi_get_ap_ext(extra_info); -} - -/*************************************************************************** - * @fn int32_t wfx_reset_counts(void) - * @brief - * get the driver reset count - * @param[in] None - * @return - * reset count - *****************************************************************************/ -int32_t wfx_reset_counts(void) -{ - return wfx_rsi_reset_count(); -} - -#ifdef SL_WFX_CONFIG_SCAN -/******************************************************************************* - * @fn bool wfx_start_scan(char *ssid, void (*callback)(wfx_wifi_scan_result_t *)) - * @brief - * called fuction when driver start scaning - * @param[in] ssid: - * @return returns ture if successful, - * false otherwise - *******************************************************************************/ -bool wfx_start_scan(char * ssid, void (*callback)(wfx_wifi_scan_result_t *)) -{ - // check if already in progress - VerifyOrReturnError(wfx_rsi.scan_cb != nullptr, false); - wfx_rsi.scan_cb = callback; - - VerifyOrReturnError(ssid != nullptr, false); - wfx_rsi.scan_ssid_length = strnlen(ssid, std::min(sizeof(ssid), WFX_MAX_SSID_LENGTH)); - wfx_rsi.scan_ssid = reinterpret_cast(chip::Platform::MemoryAlloc(wfx_rsi.scan_ssid_length)); - VerifyOrReturnError(wfx_rsi.scan_ssid != nullptr, false); - chip::Platform::CopyString(wfx_rsi.scan_ssid, wfx_rsi.scan_ssid_length, ssid); - - WifiEvent event = WifiEvent::kScan; - sl_matter_wifi_post_event(event); - - return true; -} - -/*************************************************************************** - * @fn void wfx_cancel_scan(void) - * @brief - * called function when driver cancel scaning - * @param[in] None - * @return - * None - *****************************************************************************/ -void wfx_cancel_scan(void) -{ - /* Not possible */ - ChipLogError(DeviceLayer, "cannot cancel scan"); -} -#endif /* SL_WFX_CONFIG_SCAN */ -#endif // RS911X_WIFI - /*********************************************************************************** * @fn sl_matter_wifi_task_started(void) * @brief diff --git a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h index 99ac5fdf88a4bd..1d4b2163c77abe 100644 --- a/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h +++ b/examples/platform/silabs/wifi/WifiInterfaceAbstraction.h @@ -27,6 +27,22 @@ */ #define WFX_RSI_DHCP_POLL_INTERVAL (250) /* Poll interval in ms for DHCP */ +#define MAX_JOIN_RETRIES_COUNT (5) + +enum class WifiState : uint16_t +{ + kStationInit = (1 << 0), + kAPReady = (1 << 1), + kStationProvisioned = (1 << 2), + kStationConnecting = (1 << 3), + kStationConnected = (1 << 4), + kStationDhcpDone = (1 << 6), /* Requested to do DHCP after conn */ + kStationMode = (1 << 7), /* Enable Station Mode */ + kAPMode = (1 << 8), /* Enable AP Mode */ + kStationReady = (kStationConnected | kStationDhcpDone), + kStationStarted = (1 << 9), /* RSI task started */ + kScanStarted = (1 << 10), /* Scan Started */ +}; enum class WifiEvent : uint8_t { @@ -41,25 +57,9 @@ enum class WifiEvent : uint8_t kStationDhcpPoll = 8 }; -enum class WifiState : uint16_t -{ - kStationInit = (1 << 0), - kAPReady = (1 << 1), - kStationProvisioned = (1 << 2), - kStationConnecting = (1 << 3), - kStationConnected = (1 << 4), - kStationDhcpDone = (1 << 6), /* Requested to do DHCP after conn */ - kStationMode = (1 << 7), /* Enable Station Mode */ - kAPMode = (1 << 8), /* Enable AP Mode */ - kStationReady = (kStationConnected | kStationDhcpDone), - kStationStarted = (1 << 9), /* RSI task started */ - kScanStarted = (1 << 10), /* Scan Started */ -}; -using WifiStateFlags = chip::BitFlags; - typedef struct wfx_rsi_s { - WifiStateFlags dev_state; + chip::BitFlags dev_state; uint16_t ap_chan; /* The chan our STA is using */ wfx_wifi_provision_t sec; #ifdef SL_WFX_CONFIG_SCAN @@ -90,13 +90,6 @@ int32_t wfx_rsi_get_ap_ext(wfx_wifi_scan_ext_t * extra_info); int32_t wfx_rsi_reset_count(); int32_t sl_wifi_platform_disconnect(); -// TODO : this needs to be extern otherwise we get a linking error. We need to figure out why in the header clean up -// NCP files are including this while being c files -#ifdef __cplusplus -extern "C" { -#endif -sl_status_t sl_matter_wifi_platform_init(void); - #if CHIP_CONFIG_ENABLE_ICD_SERVER #if SLI_SI917 int32_t wfx_rsi_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_si91x_performance_profile_t sl_si91x_wifi_state); @@ -104,9 +97,6 @@ int32_t wfx_rsi_power_save(rsi_power_save_profile_mode_t sl_si91x_ble_state, sl_ int32_t wfx_rsi_power_save(); #endif /* SLI_SI917 */ #endif /* SL_ICD_ENABLED */ -#ifdef __cplusplus -} -#endif /** * @brief Posts an event to the Wi-Fi task diff --git a/examples/platform/silabs/wifi/WiseconnectInterfaceAbstraction.cpp b/examples/platform/silabs/wifi/WiseconnectInterfaceAbstraction.cpp new file mode 100644 index 00000000000000..3c2ec032a8ca3b --- /dev/null +++ b/examples/platform/silabs/wifi/WiseconnectInterfaceAbstraction.cpp @@ -0,0 +1,350 @@ +/* + * + * Copyright (c) 2024 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, + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "WiseconnectInterfaceAbstraction.h" +#include +#include +#include + +namespace { + +// Thread for the WLAN RSI +osThreadId_t sWlanThread; +constexpr uint32_t kWlanTaskSize = 2048; +uint8_t wlanStack[kWlanTaskSize]; +osThread_t sWlanTaskControlBlock; +constexpr osThreadAttr_t kWlanTaskAttr = { .name = "wlan_rsi", + .attr_bits = osThreadDetached, + .cb_mem = &sWlanTaskControlBlock, + .cb_size = osThreadCbSize, + .stack_mem = wlanStack, + .stack_size = kWlanTaskSize, + .priority = osPriorityAboveNormal7 }; + +} // namespace + +/********************************************************************* + * @fn sl_status_t wfx_wifi_start(void) + * @brief + * Called from ConnectivityManagerImpl.cpp - to enable the device + * Create the RSI task and let it deal with life. + * @param[in] None + * @return Returns SL_STATUS_OK if successful, + * SL_STATUS_FAIL otherwise + ***********************************************************************/ +sl_status_t wfx_wifi_start(void) +{ + VerifyOrReturnError(!(wfx_rsi.dev_state.Has(WifiState::kStationStarted)), SL_STATUS_OK); + wfx_rsi.dev_state.Set(WifiState::kStationStarted); + + // Creating a Wi-Fi driver thread + sWlanThread = osThreadNew(sl_matter_wifi_task, NULL, &kWlanTaskAttr); + + VerifyOrReturnError(sWlanThread != NULL, SL_STATUS_FAIL); + + ChipLogProgress(DeviceLayer, "sl_matter_wifi_task created successfully"); + return SL_STATUS_OK; +} + +/********************************************************************* + * @fn void wfx_enable_sta_mode(void) + * @brief + * driver enable the STA mode + * @param[in] None + * @return None + ***********************************************************************/ +void wfx_enable_sta_mode(void) +{ + wfx_rsi.dev_state.Set(WifiState::kStationMode); +} + +/********************************************************************* + * @fn bool wfx_is_sta_mode_enabled(void) + * @brief + * driver enabled the STA mode + * @param[in] None + * @return mode + ***********************************************************************/ +bool wfx_is_sta_mode_enabled(void) +{ + return wfx_rsi.dev_state.Has(WifiState::kStationMode); +} + +/********************************************************************* + * @fn void wfx_get_wifi_mac_addr(sl_wfx_interface_t interface, sl_wfx_mac_address_t *addr) + * @brief + * get the wifi mac address + * @param[in] Interface: + * @param[in] addr : address + * @return + * None + ***********************************************************************/ +void wfx_get_wifi_mac_addr(sl_wfx_interface_t interface, sl_wfx_mac_address_t * addr) +{ + VerifyOrReturn(addr != nullptr); +#ifdef SL_WFX_CONFIG_SOFTAP + *addr = (interface == SL_WFX_SOFTAP_INTERFACE) ? wfx_rsi.softap_mac : wfx_rsi.sta_mac; +#else + *addr = wfx_rsi.sta_mac; +#endif +} + +/********************************************************************* + * @fn void wfx_set_wifi_provision(wfx_wifi_provision_t *cfg) + * @brief + * Driver set the wifi provision + * @param[in] cfg: wifi configuration + * @return + * None + ***********************************************************************/ +void wfx_set_wifi_provision(wfx_wifi_provision_t * cfg) +{ + VerifyOrReturn(cfg != nullptr); + wfx_rsi.sec = *cfg; + wfx_rsi.dev_state.Set(WifiState::kStationProvisioned); +} + +/********************************************************************* + * @fn bool wfx_get_wifi_provision(wfx_wifi_provision_t *wifiConfig) + * @brief + * Driver get the wifi provision + * @param[in] wifiConfig: wifi configuration + * @return return false if successful, + * true otherwise + ***********************************************************************/ +bool wfx_get_wifi_provision(wfx_wifi_provision_t * wifiConfig) +{ + VerifyOrReturnError(wifiConfig != nullptr, false); + VerifyOrReturnError(wfx_rsi.dev_state.Has(WifiState::kStationProvisioned), false); + *wifiConfig = wfx_rsi.sec; + return true; +} + +/********************************************************************* + * @fn void wfx_clear_wifi_provision(void) + * @brief + * Driver is clear the wifi provision + * @param[in] None + * @return None + ***********************************************************************/ +void wfx_clear_wifi_provision(void) +{ + memset(&wfx_rsi.sec, 0, sizeof(wfx_rsi.sec)); + wfx_rsi.dev_state.Clear(WifiState::kStationProvisioned); + ChipLogProgress(DeviceLayer, "Clear WiFi Provision"); +} + +/************************************************************************* + * @fn sl_status_t wfx_connect_to_ap(void) + * @brief + * Start a JOIN command to the AP - Done by the wfx_rsi task + * @param[in] None + * @return returns SL_STATUS_OK if successful + ****************************************************************************/ +sl_status_t wfx_connect_to_ap(void) +{ + VerifyOrReturnError(wfx_rsi.dev_state.Has(WifiState::kStationProvisioned), SL_STATUS_INVALID_CONFIGURATION); + VerifyOrReturnError(wfx_rsi.sec.ssid_length, SL_STATUS_INVALID_CREDENTIALS); + VerifyOrReturnError(wfx_rsi.sec.ssid_length <= WFX_MAX_SSID_LENGTH, SL_STATUS_HAS_OVERFLOWED); + ChipLogProgress(DeviceLayer, "connect to access point: %s", wfx_rsi.sec.ssid); + + WifiEvent event = WifiEvent::kStationStartJoin; + sl_matter_wifi_post_event(event); + return SL_STATUS_OK; +} + +/********************************************************************* + * @fn void wfx_setup_ip6_link_local(sl_wfx_interface_t whichif) + * @brief + * Implement the ipv6 setup + * @param[in] whichif: + * @return None + ***********************************************************************/ +void wfx_setup_ip6_link_local(sl_wfx_interface_t whichif) +{ + /* + * TODO: Implement IPV6 setup, currently in sl_matter_wifi_task() + * This is hooked with MATTER code. + */ +} + +/********************************************************************* + * @fn bool wfx_is_sta_connected(void) + * @brief + * called fuction when driver is connected to STA + * @param[in] None + * @return returns ture if successful, + * false otherwise + ***********************************************************************/ +bool wfx_is_sta_connected(void) +{ + return wfx_rsi.dev_state.Has(WifiState::kStationConnected); +} + +/********************************************************************* + * @fn wifi_mode_t wfx_get_wifi_mode(void) + * @brief + * get the wifi mode + * @param[in] None + * @return return WIFI_MODE_NULL if successful, + * WIFI_MODE_STA otherwise + ***********************************************************************/ +wifi_mode_t wfx_get_wifi_mode(void) +{ + if (wfx_rsi.dev_state.Has(WifiState::kStationInit)) + return WIFI_MODE_STA; + return WIFI_MODE_NULL; +} + +/********************************************************************* + * @fn sl_status_t sl_matter_wifi_disconnect(void) + * @brief + * called fuction when STA disconnected + * @param[in] None + * @return return SL_STATUS_OK if successful, + * SL_STATUS_FAIL otherwise + ***********************************************************************/ +sl_status_t sl_matter_wifi_disconnect(void) +{ + sl_status_t status; + status = sl_wifi_platform_disconnect(); + wfx_rsi.dev_state.Clear(WifiState::kStationConnected); + return status; +} +#if CHIP_DEVICE_CONFIG_ENABLE_IPV4 +/********************************************************************* + * @fn bool wfx_have_ipv4_addr(sl_wfx_interface_t which_if) + * @brief + * called fuction when driver have ipv4 address + * @param[in] which_if: + * @return returns ture if successful, + * false otherwise + ***********************************************************************/ +bool wfx_have_ipv4_addr(sl_wfx_interface_t which_if) +{ + VerifyOrReturnError(which_if == SL_WFX_STA_INTERFACE, false); + return wfx_rsi.dev_state.Has(WifiState::kStationDhcpDone); +} +#endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ + +/********************************************************************* + * @fn bool wfx_have_ipv6_addr(sl_wfx_interface_t which_if) + * @brief + * called fuction when driver have ipv6 address + * @param[in] which_if: + * @return returns ture if successful, + * false otherwise + ***********************************************************************/ +bool wfx_have_ipv6_addr(sl_wfx_interface_t which_if) +{ + VerifyOrReturnError(which_if == SL_WFX_STA_INTERFACE, false); + // TODO: WifiState::kStationConnected does not guarantee SLAAC IPv6 LLA, maybe use a different FLAG + return wfx_rsi.dev_state.Has(WifiState::kStationConnected); +} + +/********************************************************************* + * @fn bool wfx_hw_ready(void) + * @brief + * called fuction when driver ready + * @param[in] None + * @return returns ture if successful, + * false otherwise + ***********************************************************************/ +bool wfx_hw_ready(void) +{ + return wfx_rsi.dev_state.Has(WifiState::kStationInit); +} + +/********************************************************************* + * @fn int32_t wfx_get_ap_info(wfx_wifi_scan_result_t *ap) + * @brief + * get the access point information + * @param[in] ap: access point + * @return + * access point information + ***********************************************************************/ +int32_t wfx_get_ap_info(wfx_wifi_scan_result_t * ap) +{ + return wfx_rsi_get_ap_info(ap); +} + +/********************************************************************* + * @fn int32_t wfx_get_ap_ext(wfx_wifi_scan_ext_t *extra_info) + * @brief + * get the access point extra information + * @param[in] extra_info:access point extra information + * @return + * access point extra information + ***********************************************************************/ +int32_t wfx_get_ap_ext(wfx_wifi_scan_ext_t * extra_info) +{ + return wfx_rsi_get_ap_ext(extra_info); +} + +/*************************************************************************** + * @fn int32_t wfx_reset_counts(void) + * @brief + * get the driver reset count + * @param[in] None + * @return + * reset count + *****************************************************************************/ +int32_t wfx_reset_counts(void) +{ + return wfx_rsi_reset_count(); +} + +#ifdef SL_WFX_CONFIG_SCAN +/******************************************************************************* + * @fn bool wfx_start_scan(char *ssid, void (*callback)(wfx_wifi_scan_result_t *)) + * @brief + * called fuction when driver start scaning + * @param[in] ssid: + * @return returns ture if successful, + * false otherwise + *******************************************************************************/ +bool wfx_start_scan(char * ssid, void (*callback)(wfx_wifi_scan_result_t *)) +{ + // check if already in progress + VerifyOrReturnError(wfx_rsi.scan_cb != nullptr, false); + wfx_rsi.scan_cb = callback; + + VerifyOrReturnError(ssid != nullptr, false); + wfx_rsi.scan_ssid_length = strnlen(ssid, std::min(sizeof(ssid), WFX_MAX_SSID_LENGTH)); + wfx_rsi.scan_ssid = reinterpret_cast(chip::Platform::MemoryAlloc(wfx_rsi.scan_ssid_length)); + VerifyOrReturnError(wfx_rsi.scan_ssid != nullptr, false); + chip::Platform::CopyString(wfx_rsi.scan_ssid, wfx_rsi.scan_ssid_length, ssid); + + WifiEvent event = WifiEvent::kScan; + sl_matter_wifi_post_event(event); + + return true; +} + +/*************************************************************************** + * @fn void wfx_cancel_scan(void) + * @brief + * called function when driver cancel scaning + * @param[in] None + * @return + * None + *****************************************************************************/ +void wfx_cancel_scan(void) +{ + /* Not possible */ + ChipLogError(DeviceLayer, "cannot cancel scan"); +} +#endif /* SL_WFX_CONFIG_SCAN */ diff --git a/examples/platform/silabs/wifi/WiseconnectInterfaceAbstraction.h b/examples/platform/silabs/wifi/WiseconnectInterfaceAbstraction.h new file mode 100644 index 00000000000000..d847e99fb575a5 --- /dev/null +++ b/examples/platform/silabs/wifi/WiseconnectInterfaceAbstraction.h @@ -0,0 +1,48 @@ +/* + * + * Copyright (c) 2024 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, + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include "WifiInterfaceAbstraction.h" +#include +#include +#include +#include +#include + +#define WFX_RSI_DHCP_POLL_INTERVAL (250) /* Poll interval in ms for DHCP */ +#define GET_IPV6_SUCCESS (1) + +extern WfxRsi_t wfx_rsi; + +void sl_matter_wifi_task(void * arg); + +#if CHIP_DEVICE_CONFIG_ENABLE_IPV4 +void wfx_ip_changed_notify(int got_ip); +#endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ + +int32_t wfx_rsi_get_ap_info(wfx_wifi_scan_result_t * ap); +int32_t wfx_rsi_get_ap_ext(wfx_wifi_scan_ext_t * extra_info); +int32_t wfx_rsi_reset_count(); +int32_t sl_wifi_platform_disconnect(); + +sl_status_t sl_matter_wifi_platform_init(void); + +/** + * @brief Posts an event to the Wi-Fi task + * + * @param[in] event Event to process. + */ +void sl_matter_wifi_post_event(WifiEvent event); diff --git a/src/platform/silabs/BLEManagerImpl.h b/src/platform/silabs/BLEManagerImpl.h index 9ebf113c4f8afa..6c639a7a777faf 100644 --- a/src/platform/silabs/BLEManagerImpl.h +++ b/src/platform/silabs/BLEManagerImpl.h @@ -27,13 +27,7 @@ #include "FreeRTOS.h" #include "timers.h" #if (SLI_SI91X_ENABLE_BLE || RSI_BLE_ENABLE) -#ifdef __cplusplus -extern "C" { -#endif // __cplusplus #include "wfx_sl_ble_init.h" -#ifdef __cplusplus -} -#endif // __cplusplus #else #include "gatt_db.h" #include "sl_bgapi.h" diff --git a/src/platform/silabs/efr32/wifi/ethernetif.cpp b/src/platform/silabs/efr32/wifi/ethernetif.cpp index 5993cf90cc631a..d6123d2ead0301 100644 --- a/src/platform/silabs/efr32/wifi/ethernetif.cpp +++ b/src/platform/silabs/efr32/wifi/ethernetif.cpp @@ -162,7 +162,7 @@ static void low_level_input(struct netif * netif, uint8_t * b, uint16_t len) /* We allocate a pbuf chain of pbufs from the Lwip buffer pool * and copy the data to the pbuf chain */ - if ((p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL)) != STRUCT_PBUF) + if ((p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL)) != NULL) { for (q = p, bufferoffset = 0; q != NULL; q = q->next) { @@ -268,7 +268,7 @@ static err_t low_level_output(struct netif * netif, struct pbuf * p) /* send the generated frame over Wifi network */ while ((result != SL_STATUS_OK) && (i++ < 10)) { - result = sl_wfx_send_ethernet_frame(tx_buffer, framelength, SL_WFX_STA_INTERFACE, PRIORITY_0); + result = sl_wfx_send_ethernet_frame(tx_buffer, framelength, SL_WFX_STA_INTERFACE, 0 /* priority */); } sl_wfx_host_free_buffer(tx_buffer, SL_WFX_TX_FRAME_BUFFER); diff --git a/src/platform/silabs/efr32/wifi/ethernetif.h b/src/platform/silabs/efr32/wifi/ethernetif.h index dfea1ea6ad3540..56e564d30b6767 100644 --- a/src/platform/silabs/efr32/wifi/ethernetif.h +++ b/src/platform/silabs/efr32/wifi/ethernetif.h @@ -19,9 +19,16 @@ #include "lwip/err.h" #include "lwip/netif.h" + +#ifdef WF200_WIFI +#include "sl_wfx_api.h" +#include "sl_wfx_constants.h" +#endif // WF200_WIFI + #ifdef __cplusplus extern "C" { #endif + /*************************************************************************** * @fn err_t sta_ethernetif_init(struct netif *netif) * @brief @@ -47,6 +54,7 @@ void sl_wfx_host_received_frame_callback(sl_wfx_received_ind_t * rx_buffer); #else void wfx_host_received_sta_frame_cb(uint8_t * buf, int len); #endif /* WF200_WIFI */ + #ifdef __cplusplus } #endif diff --git a/src/platform/silabs/efr32/wifi/lwip_netif.cpp b/src/platform/silabs/efr32/wifi/lwip_netif.cpp index f8d719b387fb09..b6c523c636a2a5 100644 --- a/src/platform/silabs/efr32/wifi/lwip_netif.cpp +++ b/src/platform/silabs/efr32/wifi/lwip_netif.cpp @@ -38,12 +38,17 @@ #include using namespace ::chip; using namespace ::chip::DeviceLayer; + static struct netif sta_netif; #ifdef SL_WFX_CONFIG_SOFTAP static struct netif ap_netif; #endif +#define LINK_UP (1) +#define LINK_DOWN (0) +#define MAC_48_BIT_SET (1) + /**************************************************************************** * @fn static void netif_config(struct netif *sta_if, struct netif *ap_if) * @brief diff --git a/src/platform/silabs/efr32/wifi/wfx_msgs.h b/src/platform/silabs/efr32/wifi/wfx_msgs.h index edf0aec5828fa7..af167a1f2c2f95 100644 --- a/src/platform/silabs/efr32/wifi/wfx_msgs.h +++ b/src/platform/silabs/efr32/wifi/wfx_msgs.h @@ -15,13 +15,17 @@ * limitations under the License. */ +// TODO: Delete this file after moving the wifi abstraction files to the src directory. +// Nothing should be added to this file anymore. +// File is kept due to the current header inclusion structure. + #ifndef _WFX_MSGS_H_ #define _WFX_MSGS_H_ -/* - * Taken from sl_wfx firmware - so I can re-use. - * I need to do a better job than to use this stuff - * in the CPP files of Matter - */ + +#ifdef WF200_WIFI +#include "sl_wfx_api.h" +#include "sl_wfx_constants.h" +#else typedef struct { uint8_t octet[6]; ///< Table to store a MAC address @@ -62,29 +66,7 @@ typedef struct __attribute__((__packed__)) sl_wfx_startup_ind_body_s uint32_t status; ///< Initialization status. A value of zero indicates the boot is completed successfully (see enum sl_wfx_status_t) uint16_t hardware_id; ///<=RO misc_read_reg7 register value -#if 0 /* Not used in RS911x for now - use stuff here for the port */ - uint8_t opn[SL_WFX_OPN_SIZE]; ///<=OTP part_OPN - uint8_t uid[SL_WFX_UID_SIZE]; ///<=OTP UID - uint16_t num_inp_ch_bufs; /// #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE -#include - +#include "wfx_sl_ble_init.h" #include +#include #include #include #include #include +#include #if CHIP_ENABLE_ADDITIONAL_DATA_ADVERTISING #include #endif -#include -#ifdef __cplusplus extern "C" { -#endif -#include "wfx_sl_ble_init.h" #if !(SLI_SI91X_MCU_INTERFACE | EXP_BOARD) #include #endif #include -#ifdef __cplusplus } -#endif #define BLE_MIN_CONNECTION_INTERVAL_MS 24 #define BLE_MAX_CONNECTION_INTERVAL_MS 40 diff --git a/src/platform/silabs/rs911x/rsi_ble_config.h b/src/platform/silabs/rs911x/rsi_ble_config.h index f508c3396f4e09..b28c810679081a 100644 --- a/src/platform/silabs/rs911x/rsi_ble_config.h +++ b/src/platform/silabs/rs911x/rsi_ble_config.h @@ -16,6 +16,10 @@ ******************************************************************************/ #pragma once +#ifdef __cplusplus +extern "C" { +#endif + #include "rsi_ble_apis.h" #if (SLI_SI91X_MCU_INTERFACE | EXP_BOARD) #include "rsi_bt_common_apis.h" @@ -24,6 +28,10 @@ #include #endif +#ifdef __cplusplus +} +#endif + #if SL_MATTER_GN_BUILD == 0 #include "sl_matter_wifi_config.h" #endif // SL_MATTER_GN_BUILD diff --git a/src/platform/silabs/rs911x/wfx_sl_ble_init.cpp b/src/platform/silabs/rs911x/wfx_sl_ble_init.cpp index 971852592c3e2e..89169993810ef7 100644 --- a/src/platform/silabs/rs911x/wfx_sl_ble_init.cpp +++ b/src/platform/silabs/rs911x/wfx_sl_ble_init.cpp @@ -20,9 +20,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include #include #include +#include using namespace chip::DeviceLayer::Internal; diff --git a/src/platform/silabs/rs911x/wfx_sl_ble_init.h b/src/platform/silabs/rs911x/wfx_sl_ble_init.h index 7fd9fc94b9d58e..4eaff9c0677444 100644 --- a/src/platform/silabs/rs911x/wfx_sl_ble_init.h +++ b/src/platform/silabs/rs911x/wfx_sl_ble_init.h @@ -25,15 +25,17 @@ // BLE include file to refer BLE APIs #include "ble_config.h" #include "cmsis_os2.h" -#include "wfx_host_events.h" +#include +#include + +extern "C" { #include #include #include #include #include #include -#include -#include +} #define ATT_REC_IN_HOST (0) #define WFX_QUEUE_SIZE 10 diff --git a/src/platform/silabs/wifi/wfx_host_events.h b/src/platform/silabs/wifi/wfx_host_events.h index d3d8de6ec78569..38808610ee74fe 100644 --- a/src/platform/silabs/wifi/wfx_host_events.h +++ b/src/platform/silabs/wifi/wfx_host_events.h @@ -26,6 +26,8 @@ #include "lwip/netifapi.h" #include "lwip/tcpip.h" +#include "wfx_msgs.h" + #if (SLI_SI91X_MCU_INTERFACE | EXP_BOARD) #include "rsi_common_apis.h" #include "sl_si91x_types.h" @@ -44,106 +46,27 @@ #define WFX_MAX_PASSKEY_LENGTH (64) #endif // (SLI_SI91X_MCU_INTERFACE | EXP_BOARD) -#define CONVERT_SEC_TO_MS(TimeInS) (TimeInS * 1000) - -/* Wi-Fi bitmask events - for the task */ -#define SL_WFX_CONNECT (1 << 1) -#define SL_WFX_DISCONNECT (1 << 2) -#define SL_WFX_START_AP (1 << 3) -#define SL_WFX_STOP_AP (1 << 4) -#define SL_WFX_SCAN_START (1 << 5) -#define SL_WFX_SCAN_COMPLETE (1 << 6) -#define SL_WFX_RETRY_CONNECT (1 << 7) - -// WLAN MAX retry -#define MAX_JOIN_RETRIES_COUNT (5) - -#define WLAN_TASK_STACK_SIZE (1024) - -// WLAN related Macros -#define ETH_FRAME (0) -#define CMP_SUCCESS (0) #define BSSID_LEN (6) #define MAC_ADDRESS_FIRST_OCTET (6) -#define AP_START_SUCCESS (0) -#define BITS_TO_WAIT (0) #define CONNECTION_STATUS_SUCCESS (1) #define IP_STATUS_FAIL (0) -#define GET_IPV6_SUCCESS (1) #define GET_IPV6_FAIL (0) -#define BEACON_1 (0) -#define CHANNEL_LIST ((const uint8_t *) 0) -#define CHANNEL_COUNT (0) -#define IE_DATA ((const uint8_t *) 0) -#define IE_DATA_LENGTH (0) -#define BSSID_SCAN ((const uint8_t *) 0) -#define CHANNEL_0 (0) -#define PREVENT_ROAMING (1) -#define DISABLE_PMF_MODE (0) -#define STA_IP_FAIL (0) #define IP_STATUS_SUCCESS (1) -#define ACTIVE_CHANNEL_TIME_100 (100) -#define PASSIVE_CHANNEL_TIME_0 (0) -#define PROBE_NUM_REQ_1 (1) -#define PINOUT_CLEAR_STATUS (0) -#define TICKS_TO_WAIT_0 (0) -#define TICKS_TO_WAIT_3 (3) -#define TICKS_TO_WAIT_1 (1) -#define TICKS_TO_WAIT_500 (500) +#define SL_WFX_STARTUP_IND_ID (1) +#define SL_WFX_CONNECT_IND_ID (2) +#define SL_WFX_DISCONNECT_IND_ID (3) +#define SL_WFX_SCAN_COMPLETE_ID (4) // TASK and Interrupt Macros #define SUCCESS_STATUS (1) -#define LINK_UP (1) -#define LINK_DOWN (0) -#define MAC_48_BIT_SET (1) -#define STRUCT_PBUF ((struct pbuf *) 0) -#define PRIORITY_0 (0) -#define HEX_VALUE_FF (0XFF) -// Timer Delay -#define MAX_XLEN (16) -#define MIN_XLEN (0) -#define PINOUT_CLEAR (0) -#define PINOUT_SET (1) -#define WFX_SPI_NVIC_PRIORITY (5) -#define WFX_GPIO_NVIC_PRIORITY (5) -#define CB_VALUE ((DMADRV_Callback_t) 0) - -/* TIMER_TICKS_TO_WAIT Specifies the time, in ticks, that the calling task should - * be held in the Blocked state to wait for the start command to be successfully - * sent to the timer command queue. - */ -#define TIMER_TICKS_TO_WAIT_0 pdMS_TO_TICKS(0) - -#define CONVERT_SEC_TO_MSEC (1000) -#define CONVERT_USEC_TO_MSEC (1 / 1000) - -#define RSI_RESPONSE_MAX_SIZE (28) -#define RSI_RESPONSE_HOLD_BUFF_SIZE (128) -#define RSI_DRIVER_STATUS (0) -#define OPER_MODE_0 (0) -#define COEX_MODE_0 (0) -#define RESP_BUFF_SIZE (6) -#define AP_CHANNEL_NO_0 (0) -#define SCAN_BITMAP_OPTN_1 (1) -#define IP_CONF_RSP_BUFF_LENGTH_4 (4) -#define STATION (0) - -#define SPI_CONFIG_SUCCESS (0) typedef enum { WIFI_EVENT, IP_EVENT, } wfx_event_base_t; -typedef enum -{ - IP_EVENT_STA_GOT_IP, - IP_EVENT_GOT_IP6, - IP_EVENT_STA_LOST_IP, -} ip_event_id_t; - /* Note that these are same as RSI_security */ typedef enum { @@ -195,6 +118,13 @@ typedef struct wfx_wifi_scan_ext uint32_t overrun_count; } wfx_wifi_scan_ext_t; +typedef enum +{ + IP_EVENT_STA_GOT_IP, + IP_EVENT_GOT_IP6, + IP_EVENT_STA_LOST_IP, +} ip_event_id_t; + #ifdef RS911X_WIFI /* * This Sh%t is here to support WFXUtils - and the Matter stuff that uses it @@ -205,121 +135,27 @@ typedef enum SL_WFX_STA_INTERFACE = 0, ///< Interface 0, linked to the station SL_WFX_SOFTAP_INTERFACE = 1, ///< Interface 1, linked to the softap } sl_wfx_interface_t; -#endif /* RS911X_WIFI */ - -#ifdef WF200_WIFI -#include "FreeRTOS.h" -#include "event_groups.h" -#include "semphr.h" -#include "sl_wfx_cmd_api.h" -#include "sl_wfx_constants.h" -#include "task.h" -#include "timers.h" - -#define WLAN_TASK_PRIORITY (1) -typedef struct __attribute__((__packed__)) sl_wfx_get_counters_cnf_body_s -{ - uint32_t status; - uint16_t mib_id; - uint16_t length; - uint32_t rcpi; - uint32_t count_plcp_errors; - uint32_t count_fcs_errors; - uint32_t count_tx_packets; - uint32_t count_rx_packets; - uint32_t count_rx_packet_errors; - uint32_t count_rx_decryption_failures; - uint32_t count_rx_mic_failures; - uint32_t count_rx_no_key_failures; - uint32_t count_tx_multicast_frames; - uint32_t count_tx_frames_success; - uint32_t count_tx_frame_failures; - uint32_t count_tx_frames_retried; - uint32_t count_tx_frames_multi_retried; - uint32_t count_rx_frame_duplicates; - uint32_t count_rts_success; - uint32_t count_rts_failures; - uint32_t count_ack_failures; - uint32_t count_rx_multicast_frames; - uint32_t count_rx_frames_success; - uint32_t count_rx_cmacicv_errors; - uint32_t count_rx_cmac_replays; - uint32_t count_rx_mgmt_ccmp_replays; - uint32_t count_rx_bipmic_errors; - uint32_t count_rx_beacon; - uint32_t count_miss_beacon; - uint32_t reserved[15]; -} sl_wfx_get_counters_cnf_body_t; - -typedef struct __attribute__((__packed__)) sl_wfx_get_counters_cnf_s -{ - /** Common message header. */ - sl_wfx_header_t header; - /** Confirmation message body. */ - sl_wfx_get_counters_cnf_body_t body; -} sl_wfx_get_counters_cnf_t; - -typedef struct __attribute__((__packed__)) sl_wfx_mib_req_body_s -{ - uint16_t mib_id; ///< ID of the MIB to be read. - uint16_t reserved; -} sl_wfx_mib_req_body_t; - -typedef struct __attribute__((__packed__)) sl_wfx_header_mib_s -{ - uint16_t length; ///< Message length in bytes including this uint16_t. - ///< Maximum value is 8188 but maximum Request size is FW dependent and reported in the - ///< ::sl_wfx_startup_ind_body_t::size_inp_ch_buf. - uint8_t id; ///< Contains the message Id indexed by sl_wfx_general_commands_ids_t or sl_wfx_message_ids_t. - uint8_t reserved : 1; - uint8_t interface : 2; - uint8_t seqnum : 3; - uint8_t encrypted : 2; -} sl_wfx_header_mib_t; - -typedef struct __attribute__((__packed__)) sl_wfx_mib_req_s -{ - /** Common message header. */ - sl_wfx_header_mib_t header; - /** Request message body. */ - sl_wfx_mib_req_body_t body; -} sl_wfx_mib_req_t; - -#else /* End WF200 else RS9116,917 NCP and 917 SoC */ - -#include "wfx_msgs.h" -/* Wi-Fi events*/ -#define SL_WFX_STARTUP_IND_ID (1) -#define SL_WFX_CONNECT_IND_ID (2) -#define SL_WFX_DISCONNECT_IND_ID (3) -#define SL_WFX_SCAN_COMPLETE_ID (4) -#endif /* WF200_WIFI */ - -#ifdef __cplusplus -extern "C" { #endif -void sl_wfx_host_gpio_init(void); sl_status_t wfx_wifi_start(void); void wfx_enable_sta_mode(void); - void wfx_get_wifi_mac_addr(sl_wfx_interface_t interface, sl_wfx_mac_address_t * addr); void wfx_set_wifi_provision(wfx_wifi_provision_t * wifiConfig); bool wfx_get_wifi_provision(wfx_wifi_provision_t * wifiConfig); - bool wfx_is_sta_mode_enabled(void); int32_t wfx_get_ap_info(wfx_wifi_scan_result_t * ap); int32_t wfx_get_ap_ext(wfx_wifi_scan_ext_t * extra_info); int32_t wfx_reset_counts(); - void wfx_clear_wifi_provision(void); sl_status_t wfx_connect_to_ap(void); void wfx_setup_ip6_link_local(sl_wfx_interface_t); bool wfx_is_sta_connected(void); sl_status_t sl_matter_wifi_disconnect(void); + #if CHIP_DEVICE_CONFIG_ENABLE_IPV4 bool wfx_have_ipv4_addr(sl_wfx_interface_t); #endif /* CHIP_DEVICE_CONFIG_ENABLE_IPV4 */ + bool wfx_have_ipv6_addr(sl_wfx_interface_t); wifi_mode_t wfx_get_wifi_mode(void); bool wfx_start_scan(char * ssid, void (*scan_cb)(wfx_wifi_scan_result_t *)); /* true returned if successfully started */ @@ -338,7 +174,6 @@ void wfx_lwip_set_sta_link_down(void); void sl_matter_lwip_start(void); struct netif * wfx_get_netif(sl_wfx_interface_t interface); -bool wfx_hw_ready(void); #if CHIP_DEVICE_CONFIG_ENABLE_IPV4 void wfx_dhcp_got_ipv4(uint32_t); void wfx_ip_changed_notify(int got_ip); @@ -355,6 +190,8 @@ int32_t wfx_rsi_send_data(void * p, uint16_t len); #endif //!(EXP_BOARD) #endif // RS911X_WIFI +bool wfx_hw_ready(void); + #ifdef RS911X_WIFI // for RS9116, 917 NCP and 917 SoC /* RSI Power Save */ #if SL_ICD_ENABLED @@ -366,21 +203,23 @@ sl_status_t wfx_power_save(); #endif /* SL_ICD_ENABLED */ #endif /* RS911X_WIFI */ -#ifdef WF200_WIFI -bool wfx_is_sta_provisioned(void); -sl_wfx_state_t wfx_get_wifi_state(void); -void wfx_bus_start(void); -sl_status_t get_all_counters(void); -void sl_wfx_host_gpio_init(void); -sl_status_t sl_wfx_host_process_event(sl_wfx_generic_message_t * event_payload); -#endif /* WF200_WIFI */ +#ifdef __cplusplus +extern "C" { +#endif #if (SLI_SI91X_MCU_INTERFACE) #if SL_ICD_ENABLED +// TODO : This should be moved outside of the Wifi interface functions void sl_button_on_change(uint8_t btn, uint8_t btnAction); #endif /* SL_ICD_ENABLED */ #endif /* SLI_SI91X_MCU_INTERFACE */ +#ifdef WF200_WIFI +void sl_wfx_host_gpio_init(void); +void wfx_bus_start(void); +sl_status_t sl_wfx_host_process_event(sl_wfx_generic_message_t * event_payload); +#endif /* WF200_WIFI */ + #ifdef __cplusplus } #endif From aba23838e012b88736565830cc64f6e357cf9666 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Mon, 11 Nov 2024 16:53:21 -0500 Subject: [PATCH 116/121] Ensure that the generic NumericAttributeTraits is only used for types it supports. (#36459) It turned out to be easy to use it for some struct type and get weird behavior; we should not allow that to compile. --- .../CodegenDataModelProvider_Read.cpp | 1 + src/app/util/attribute-storage-null-handling.h | 11 ++++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp index aa357ce4dfb5cb..a558b8e986298a 100644 --- a/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp +++ b/src/app/codegen-data-model-provider/CodegenDataModelProvider_Read.cpp @@ -48,6 +48,7 @@ namespace chip { namespace app { + namespace { using namespace chip::app::Compatibility::Internal; diff --git a/src/app/util/attribute-storage-null-handling.h b/src/app/util/attribute-storage-null-handling.h index 22dd0e6dab5ce3..ace14c48c8517b 100644 --- a/src/app/util/attribute-storage-null-handling.h +++ b/src/app/util/attribute-storage-null-handling.h @@ -60,22 +60,27 @@ struct NumericAttributeTraits static constexpr WorkingType StorageToWorking(StorageType storageValue) { return storageValue; } private: + // Ensure that this generic NumericAttributeTraits implementation is being used for some type for which it + // actually works. + static_assert(std::is_floating_point_v || std::is_integral_v || std::is_enum_v, + "NumericAttributeTraits specialization needed for this type"); + // We need to make sure we never look like we are assigning NaN to an // integer, even in a not-reached branch. Without "if constexpr", the best // we can do is these functions using enable_if. - template ::value, int> = 0> + template , int> = 0> static constexpr StorageType GetNullValue() { return std::numeric_limits::quiet_NaN(); } - template ::value, int> = 0> + template , int> = 0> static constexpr StorageType GetNullValue() { return std::is_signed::value ? std::numeric_limits::min() : std::numeric_limits::max(); } - template ::value, int> = 0> + template , int> = 0> static constexpr StorageType GetNullValue() { static_assert(!std::is_signed>::value, "Enums must be unsigned"); From 47780adb559ad9e161620f2e56b9d1449b2d35b3 Mon Sep 17 00:00:00 2001 From: Amine Alami <43780877+Alami-Amine@users.noreply.github.com> Date: Tue, 12 Nov 2024 09:59:41 +0100 Subject: [PATCH 117/121] Migrating deprecated GN flag: export-compile-commands (#35429) * changing deprecated GN flag * Restyled by shfmt * Restyled by autopep8 * removeing quotes from wildcard * more conversions * Updating dry-run golden standard files --------- Co-authored-by: Restyled.io --- .github/workflows/build.yaml | 6 +++--- config/qpg/chip-gn/build.sh | 2 +- examples/chef/chef.py | 2 +- examples/lighting-app/tizen/README.md | 2 +- scripts/build/builders/efr32.py | 2 +- scripts/build/builders/gn.py | 2 +- scripts/build/builders/nxp.py | 2 +- ...dry_run_efr32-brd4187c-light-rpc-no-version.txt | 2 +- ...ry_run_linux-arm64-chip-tool-ipv6only-clang.txt | 2 +- ...n_linux-arm64-ota-requestor-nodeps-ipv6only.txt | 2 +- .../dry_run_linux-x64-all-clusters-coverage.txt | 2 +- scripts/examples/gn_bouffalolab_example.sh | 2 +- scripts/examples/gn_silabs_example.sh | 2 +- scripts/examples/gn_stm32_example.sh | 6 +++--- scripts/helpers/update_compile_commands.sh | 14 +++++++------- 15 files changed, 25 insertions(+), 25 deletions(-) diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 85bb7955810aae..92acd73acef165 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -205,14 +205,14 @@ jobs: esac rm -rf ./out/sanitizers - BUILD_TYPE=sanitizers scripts/build/gn_gen.sh --args="$GN_ARGS" --export-compile-commands + BUILD_TYPE=sanitizers scripts/build/gn_gen.sh --args="$GN_ARGS" --add-export-compile-commands=* BUILD_TYPE=sanitizers scripts/tests/gn_tests.sh done - name: Generate tests with sanitizers (for tidy) if: github.event.pull_request.number != null run: | rm -rf ./out/sanitizers - BUILD_TYPE=sanitizers scripts/build/gn_gen.sh --args="is_clang=true is_asan=true" --export-compile-commands + BUILD_TYPE=sanitizers scripts/build/gn_gen.sh --args="is_clang=true is_asan=true" --add-export-compile-commands=* - name: Ensure codegen is done for sanitize run: | ./scripts/run_in_build_env.sh "./scripts/run_codegen_targets.sh out/sanitizers" @@ -439,7 +439,7 @@ jobs: # We want to build various standalone example apps (similar to what examples-linux-standalone.yaml # does), so use target_os="all" to get those picked up as part of the "unified" build. But then # to save CI resources we want to exclude the "host clang" build, which uses the pigweed clang. - scripts/build/gn_gen.sh --args='target_os="all" is_asan=true enable_host_clang_build=false' --export-compile-commands + scripts/build/gn_gen.sh --args='target_os="all" is_asan=true enable_host_clang_build=false' --add-export-compile-commands=* scripts/run_in_build_env.sh "ninja -C ./out/$BUILD_TYPE" scripts/tests/gn_tests.sh - name: Ensure codegen is done for default diff --git a/config/qpg/chip-gn/build.sh b/config/qpg/chip-gn/build.sh index 541da2625253eb..974caaaf0ac2f9 100755 --- a/config/qpg/chip-gn/build.sh +++ b/config/qpg/chip-gn/build.sh @@ -31,7 +31,7 @@ gn \ --root-target=//config/qpg/chip-gn \ --dotfile="$GN_ROOT_TARGET/.gn" \ --script-executable=python3 \ - --export-compile-commands \ + --add-export-compile-commands="*" \ gen \ --check \ --args="$GN_ARGS" \ diff --git a/examples/chef/chef.py b/examples/chef/chef.py index cecbf646ffeedf..8c54ee8dbbc6fb 100755 --- a/examples/chef/chef.py +++ b/examples/chef/chef.py @@ -884,7 +884,7 @@ def main() -> int: """)) if options.do_clean: shell.run_cmd("rm -rf out") - shell.run_cmd("gn gen --export-compile-commands out") + shell.run_cmd("gn gen --add-export-compile-commands=* out") shell.run_cmd("ninja -C out") # diff --git a/examples/lighting-app/tizen/README.md b/examples/lighting-app/tizen/README.md index 28e0d9b2c0b22b..d1b2fe474e9220 100644 --- a/examples/lighting-app/tizen/README.md +++ b/examples/lighting-app/tizen/README.md @@ -13,7 +13,7 @@ Generating tizen-arm-light ```sh gn gen --check \ --fail-on-unused-args \ - --export-compile-commands \ + --add-export-compile-commands=* \ --root=$PW_PROJECT_ROOT/examples/lighting-app/tizen \ "--args=target_os=\"tizen\" target_cpu=\"arm\" tizen_sdk_root=\"$TIZEN_SDK_ROOT\" tizen_sdk_sysroot=\"$TIZEN_SDK_SYSROOT\"" \ $PW_PROJECT_ROOT/out/tizen-arm-light diff --git a/scripts/build/builders/efr32.py b/scripts/build/builders/efr32.py index cb80eab890495d..871785fd2c9db8 100644 --- a/scripts/build/builders/efr32.py +++ b/scripts/build/builders/efr32.py @@ -337,7 +337,7 @@ def bundle_outputs(self): def generate(self): cmd = [ 'gn', 'gen', '--check', '--fail-on-unused-args', - '--export-compile-commands', + '--add-export-compile-commands=*', '--root=%s' % self.root ] if self.dotfile: diff --git a/scripts/build/builders/gn.py b/scripts/build/builders/gn.py index 6d9385bd4fc2aa..f65d8878c2ba60 100644 --- a/scripts/build/builders/gn.py +++ b/scripts/build/builders/gn.py @@ -55,7 +55,7 @@ def PostBuildCommand(self): def generate(self): cmd = [ 'gn', 'gen', '--check', '--fail-on-unused-args', - '--export-compile-commands', + '--add-export-compile-commands=*', '--root=%s' % self.root ] diff --git a/scripts/build/builders/nxp.py b/scripts/build/builders/nxp.py index fa24ef2d2d13ce..202c4e87ff4c98 100644 --- a/scripts/build/builders/nxp.py +++ b/scripts/build/builders/nxp.py @@ -421,7 +421,7 @@ def generate(self): elif self.build_system == NxpBuildSystem.GN: # add empty space at the end to avoid concatenation issue when there is no --args - cmd += 'gn gen --check --fail-on-unused-args --export-compile-commands --root=%s ' % self.root + cmd += 'gn gen --check --fail-on-unused-args --add-export-compile-commands=* --root=%s ' % self.root extra_args = [] diff --git a/scripts/build/testdata/dry_run_efr32-brd4187c-light-rpc-no-version.txt b/scripts/build/testdata/dry_run_efr32-brd4187c-light-rpc-no-version.txt index d75eeabc3b6996..8d367e045510fb 100644 --- a/scripts/build/testdata/dry_run_efr32-brd4187c-light-rpc-no-version.txt +++ b/scripts/build/testdata/dry_run_efr32-brd4187c-light-rpc-no-version.txt @@ -2,7 +2,7 @@ cd "{root}" # Generating efr32-brd4187c-light-rpc-no-version -gn gen --check --fail-on-unused-args --export-compile-commands --root={root}/examples/lighting-app/silabs '--args=silabs_board="BRD4187C" is_debug=false import("//with_pw_rpc.gni") efr32_sdk_root="TEST_GSDK_ROOT" openthread_root="TEST_GSDK_ROOT/util/third_party/openthread" wiseconnect_sdk_root="TEST_WISECONNECT_SDK_ROOT" wifi_sdk_root="TEST_WIFI_SDK_ROOT"' {out}/efr32-brd4187c-light-rpc-no-version +gn gen --check --fail-on-unused-args '--add-export-compile-commands=*' --root={root}/examples/lighting-app/silabs '--args=silabs_board="BRD4187C" is_debug=false import("//with_pw_rpc.gni") efr32_sdk_root="TEST_GSDK_ROOT" openthread_root="TEST_GSDK_ROOT/util/third_party/openthread" wiseconnect_sdk_root="TEST_WISECONNECT_SDK_ROOT" wifi_sdk_root="TEST_WIFI_SDK_ROOT"' {out}/efr32-brd4187c-light-rpc-no-version # Building efr32-brd4187c-light-rpc-no-version ninja -C {out}/efr32-brd4187c-light-rpc-no-version diff --git a/scripts/build/testdata/dry_run_linux-arm64-chip-tool-ipv6only-clang.txt b/scripts/build/testdata/dry_run_linux-arm64-chip-tool-ipv6only-clang.txt index 58e095837e9a97..bcfce65eec65d8 100644 --- a/scripts/build/testdata/dry_run_linux-arm64-chip-tool-ipv6only-clang.txt +++ b/scripts/build/testdata/dry_run_linux-arm64-chip-tool-ipv6only-clang.txt @@ -4,7 +4,7 @@ cd "{root}" # Generating linux-arm64-chip-tool-ipv6only-clang bash -c ' PKG_CONFIG_PATH="SYSROOT_AARCH64/lib/aarch64-linux-gnu/pkgconfig" \ - gn gen --check --fail-on-unused-args --export-compile-commands --root={root}/examples/chip-tool '"'"'--args=chip_inet_config_enable_ipv4=false is_clang=true target_cpu="arm64" sysroot="SYSROOT_AARCH64"'"'"' {out}/linux-arm64-chip-tool-ipv6only-clang' + gn gen --check --fail-on-unused-args '"'"'--add-export-compile-commands=*'"'"' --root={root}/examples/chip-tool '"'"'--args=chip_inet_config_enable_ipv4=false is_clang=true target_cpu="arm64" sysroot="SYSROOT_AARCH64"'"'"' {out}/linux-arm64-chip-tool-ipv6only-clang' # Setting up Java deps third_party/java_deps/set_up_java_deps.sh diff --git a/scripts/build/testdata/dry_run_linux-arm64-ota-requestor-nodeps-ipv6only.txt b/scripts/build/testdata/dry_run_linux-arm64-ota-requestor-nodeps-ipv6only.txt index a1f9beb5eb6f60..dd9fd5f8e9622c 100644 --- a/scripts/build/testdata/dry_run_linux-arm64-ota-requestor-nodeps-ipv6only.txt +++ b/scripts/build/testdata/dry_run_linux-arm64-ota-requestor-nodeps-ipv6only.txt @@ -4,7 +4,7 @@ cd "{root}" # Generating linux-arm64-ota-requestor-nodeps-ipv6only bash -c ' PKG_CONFIG_PATH="SYSROOT_AARCH64/lib/aarch64-linux-gnu/pkgconfig" \ - gn gen --check --fail-on-unused-args --export-compile-commands --root={root}/examples/ota-requestor-app/linux '"'"'--args=chip_inet_config_enable_ipv4=false chip_config_network_layer_ble=false chip_enable_ble=false chip_enable_wifi=false chip_enable_openthread=false is_clang=true chip_crypto="mbedtls" target_cpu="arm64" sysroot="SYSROOT_AARCH64"'"'"' {out}/linux-arm64-ota-requestor-nodeps-ipv6only' + gn gen --check --fail-on-unused-args '"'"'--add-export-compile-commands=*'"'"' --root={root}/examples/ota-requestor-app/linux '"'"'--args=chip_inet_config_enable_ipv4=false chip_config_network_layer_ble=false chip_enable_ble=false chip_enable_wifi=false chip_enable_openthread=false is_clang=true chip_crypto="mbedtls" target_cpu="arm64" sysroot="SYSROOT_AARCH64"'"'"' {out}/linux-arm64-ota-requestor-nodeps-ipv6only' # Setting up Java deps third_party/java_deps/set_up_java_deps.sh diff --git a/scripts/build/testdata/dry_run_linux-x64-all-clusters-coverage.txt b/scripts/build/testdata/dry_run_linux-x64-all-clusters-coverage.txt index d2960f35542eba..00c4027603d13e 100644 --- a/scripts/build/testdata/dry_run_linux-x64-all-clusters-coverage.txt +++ b/scripts/build/testdata/dry_run_linux-x64-all-clusters-coverage.txt @@ -2,7 +2,7 @@ cd "{root}" # Generating linux-x64-all-clusters-coverage -gn gen --check --fail-on-unused-args --export-compile-commands --root={root}/examples/all-clusters-app/linux --args=use_coverage=true {out}/linux-x64-all-clusters-coverage +gn gen --check --fail-on-unused-args '--add-export-compile-commands=*' --root={root}/examples/all-clusters-app/linux --args=use_coverage=true {out}/linux-x64-all-clusters-coverage # Setting up Java deps third_party/java_deps/set_up_java_deps.sh diff --git a/scripts/examples/gn_bouffalolab_example.sh b/scripts/examples/gn_bouffalolab_example.sh index 3942d796896027..79ccda9ae1f755 100755 --- a/scripts/examples/gn_bouffalolab_example.sh +++ b/scripts/examples/gn_bouffalolab_example.sh @@ -200,7 +200,7 @@ else example_dir=$MATTER_ROOT/examples/$example_name/bouffalolab/$bouffalo_chip output_dir=$MATTER_ROOT/$output_folder - gn gen --check --fail-on-unused-args --export-compile-commands --root="$example_dir" "$output_dir" --args="${optArgs[*]}" + gn gen --check --fail-on-unused-args --add-export-compile-commands=* --root="$example_dir" "$output_dir" --args="${optArgs[*]}" ninja -C "$output_dir" fi diff --git a/scripts/examples/gn_silabs_example.sh b/scripts/examples/gn_silabs_example.sh index bc06f8b2d28b0c..f68c938e579c45 100755 --- a/scripts/examples/gn_silabs_example.sh +++ b/scripts/examples/gn_silabs_example.sh @@ -340,7 +340,7 @@ else optArgs+="openthread_root=\"$GSDK_ROOT/util/third_party/openthread\" " fi - "$GN_PATH" gen --check --script-executable="$PYTHON_PATH" --fail-on-unused-args --export-compile-commands --root="$ROOT" --dotfile="$DOTFILE" --args="silabs_board=\"$SILABS_BOARD\" $optArgs" "$BUILD_DIR" + "$GN_PATH" gen --check --script-executable="$PYTHON_PATH" --fail-on-unused-args --add-export-compile-commands=* --root="$ROOT" --dotfile="$DOTFILE" --args="silabs_board=\"$SILABS_BOARD\" $optArgs" "$BUILD_DIR" if [ "$USE_SLC" == true ]; then # Activation needs to be after SLC generation which is done in gn gen. diff --git a/scripts/examples/gn_stm32_example.sh b/scripts/examples/gn_stm32_example.sh index 62c19cc3470de6..1167bd721dd54a 100755 --- a/scripts/examples/gn_stm32_example.sh +++ b/scripts/examples/gn_stm32_example.sh @@ -176,14 +176,14 @@ else BUILD_DIR=$OUTDIR/$STM32_BOARD echo BUILD_DIR="$BUILD_DIR" if [ "$USE_WIFI" == true ]; then - gn gen --check --fail-on-unused-args --export-compile-commands --root="$ROOT" --dotfile="$ROOT"/build_for_wifi_gnfile.gn --args="stm32_board=\"$STM32_BOARD\" $optArgs" "$BUILD_DIR" + gn gen --check --fail-on-unused-args --add-export-compile-commands=* --root="$ROOT" --dotfile="$ROOT"/build_for_wifi_gnfile.gn --args="stm32_board=\"$STM32_BOARD\" $optArgs" "$BUILD_DIR" else # thread build # if [ -z "$optArgs" ]; then - gn gen --check --fail-on-unused-args --export-compile-commands --root="$ROOT" --args="stm32_board=\"$STM32_BOARD\" treat_warnings_as_errors=false" --ide=json "$BUILD_DIR" + gn gen --check --fail-on-unused-args --add-export-compile-commands=* --root="$ROOT" --args="stm32_board=\"$STM32_BOARD\" treat_warnings_as_errors=false" --ide=json "$BUILD_DIR" else - gn gen --check --fail-on-unused-args --export-compile-commands --root="$ROOT" --args="stm32_board=\"$STM32_BOARD\" $optArgs treat_warnings_as_errors=false" --ide=json "$BUILD_DIR" + gn gen --check --fail-on-unused-args --add-export-compile-commands=* --root="$ROOT" --args="stm32_board=\"$STM32_BOARD\" $optArgs treat_warnings_as_errors=false" --ide=json "$BUILD_DIR" fi fi ninja -v -C "$BUILD_DIR"/ diff --git a/scripts/helpers/update_compile_commands.sh b/scripts/helpers/update_compile_commands.sh index 15b03c1799a0d7..d103a2a4183789 100755 --- a/scripts/helpers/update_compile_commands.sh +++ b/scripts/helpers/update_compile_commands.sh @@ -23,23 +23,23 @@ CHIP_ROOT="$(dirname "$0")/../.." source "$CHIP_ROOT/scripts/activate.sh" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=host_gcc +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:host_gcc" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.gcc.json" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=host_clang +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:host_clang" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.clang.json" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=host_gcc_mbedtls +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:host_gcc_mbedtls" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.mbedtls.json" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=android_x64 +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:android_x64" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.android_x64.json" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=android_arm64 +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:android_arm64" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.android_arm64.json" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=efr32_lock_app +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:efr32_lock_app" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.efr32.json" -gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --export-compile-commands=tizen_lighting_app +gn --root="$CHIP_ROOT" gen "$CHIP_ROOT/out/debug" --add-export-compile-commands="//:tizen_lighting_app" mv "$CHIP_ROOT/out/debug/compile_commands.json" "$CHIP_ROOT/out/debug/compile_commands.tizen_arm.json" From 9e0ab5826add363b1e72de16c3e235157f49ada8 Mon Sep 17 00:00:00 2001 From: Shubham Patil Date: Tue, 12 Nov 2024 16:14:02 +0530 Subject: [PATCH 118/121] da_revocation: align the revocation set generation algorithm with spec changes (#36225) * da_revocation: align the revocation set generation algorithm with spec changes * Add types to few methods * address review comments * add the vid/pid checks for PAI delegated crl signer * get_paa_cert_for_crl_issuer is actually fetching the issuer cert rather than the PAA --- credentials/generate-revocation-set.py | 309 +++++++++++++++++-------- 1 file changed, 208 insertions(+), 101 deletions(-) diff --git a/credentials/generate-revocation-set.py b/credentials/generate-revocation-set.py index e0d0cb611fa072..4cdcfdbad1ae26 100644 --- a/credentials/generate-revocation-set.py +++ b/credentials/generate-revocation-set.py @@ -26,6 +26,7 @@ import subprocess import sys from enum import Enum +from typing import Optional import click import requests @@ -91,6 +92,112 @@ def parse_vid_pid_from_distinguished_name(distinguished_name): return vid, pid +def get_akid(cert: x509.Certificate) -> Optional[bytes]: + try: + return cert.extensions.get_extension_for_oid(x509.OID_AUTHORITY_KEY_IDENTIFIER).value.key_identifier + except Exception: + logging.warning("AKID not found in certificate") + return None + + +def get_skid(cert: x509.Certificate) -> Optional[bytes]: + try: + return cert.extensions.get_extension_for_oid(x509.OID_SUBJECT_KEY_IDENTIFIER).value.key_identifier + except Exception: + logging.warning("SKID not found in certificate") + return None + + +def get_subject_b64(cert: x509.Certificate) -> str: + return base64.b64encode(cert.subject.public_bytes()).decode('utf-8') + + +def get_issuer_b64(cert: x509.Certificate) -> str: + return base64.b64encode(cert.issuer.public_bytes()).decode('utf-8') + + +def verify_cert(cert: x509.Certificate, root: x509.Certificate) -> bool: + ''' + Verifies if the cert is signed by root. + ''' + + cert_akid = get_akid(cert) + root_skid = get_skid(root) + if cert_akid is None or root_skid is None or cert_akid != root_skid: + return False + + if cert.issuer != root.subject: + return False + + # public_key().verify() do not return anything if signature is valid, + # will raise an exception if signature is invalid + try: + root.public_key().verify(cert.signature, cert.tbs_certificate_bytes, ec.ECDSA(cert.signature_hash_algorithm)) + except Exception: + logging.warning(f"Signature verification failed for cert subject: {get_subject_b64(cert)}, issuer: {get_issuer_b64(cert)}") + return False + + return True + + +def is_self_signed_certificate(cert: x509.Certificate) -> bool: + return verify_cert(cert, cert) + + +# delegator is optional so can be None, but crl_signer and paa has to be present +def validate_cert_chain(crl_signer: x509.Certificate, crl_signer_delegator: x509.Certificate, paa: x509.Certificate): + ''' + There could be four scenarios: + 1. CRL Signer is PAA itself, hence its self-signed certificate + 2. CRL Signer is PAI certificate, and we can validate (crl_signer -> paa) chain + 3. CRL Signer delegator is PAA, and we can validate (crl_signer -> crl_signer_delegator(paa) -> paa) chain + 4. CRL Signer delegator is PAI, and we can validate (crl_signer -> crl_signer_delegator -> paa) chain + ''' + + if crl_signer_delegator: + return verify_cert(crl_signer, crl_signer_delegator) and verify_cert(crl_signer_delegator, paa) + else: + return verify_cert(crl_signer, paa) + + +def validate_vid_pid(revocation_point: dict, crl_signer_certificate: x509.Certificate, crl_signer_delegator_certificate: x509.Certificate) -> bool: + crl_signer_vid, crl_signer_pid = parse_vid_pid_from_distinguished_name(crl_signer_certificate.subject) + + if revocation_point["isPAA"]: + if crl_signer_vid is not None: + if revocation_point["vid"] != crl_signer_vid: + logging.warning("VID in CRL Signer Certificate does not match with VID in revocation point, continue...") + return False + else: + vid_to_match = crl_signer_vid + pid_to_match = crl_signer_pid + + # if the CRL Signer is delegated then match the VID and PID of the CRL Signer Delegator + if crl_signer_delegator_certificate: + vid_to_match, pid_to_match = parse_vid_pid_from_distinguished_name(crl_signer_delegator_certificate.subject) + + if vid_to_match is None or revocation_point["vid"] != vid_to_match: + logging.warning("VID in CRL Signer Certificate does not match with VID in revocation point, continue...") + return False + + if pid_to_match is not None: + if revocation_point["pid"] != pid_to_match: + logging.warning("PID in CRL Signer Certificate does not match with PID in revocation point, continue...") + return False + + return True + + +def fetch_crl_from_url(url: str, timeout: int) -> x509.CertificateRevocationList: + logging.debug(f"Fetching CRL from {url}") + + try: + r = requests.get(url, timeout=timeout) + return x509.load_der_x509_crl(r.content) + except Exception: + logging.error('Failed to fetch a valid CRL') + + class DCLDClient: ''' A client for interacting with DCLD using either the REST API or command line interface (CLI). @@ -172,30 +279,50 @@ def get_revocation_points(self) -> list[dict]: return response["PkiRevocationDistributionPoint"] - def get_paa_cert_for_crl_issuer(self, crl_signer_issuer_name_b64, crl_signer_authority_key_id) -> str: + def get_issuer_cert(self, cert: x509.Certificate) -> Optional[x509.Certificate]: ''' - Get PAA certificate for CRL issuer + Get the issuer certificate for Parameters ---------- - crl_signer_issuer_name_b64: str - The issuer name of the CRL signer. - crl_signer_authority_key_id: str - The authority key ID of the CRL signer. + cert: x509.Certificate + Certificate Returns ------- str - PAA certificate in PEM format + Issuer certificate in PEM format ''' + issuer_name_b64 = get_issuer_b64(cert) + akid = get_akid(cert) + if akid is None: + return + + # Convert CRL Signer AKID to colon separated hex + akid_hex = akid.hex().upper() + akid_hex = ':'.join([akid_hex[i:i+2] for i in range(0, len(akid_hex), 2)]) + + logging.debug( + f"Fetching issuer from:{self.rest_node_url}/dcl/pki/certificates/{issuer_name_b64}/{akid_hex}") + if self.use_rest: response = requests.get( - f"{self.rest_node_url}/dcl/pki/certificates/{crl_signer_issuer_name_b64}/{crl_signer_authority_key_id}").json() + f"{self.rest_node_url}/dcl/pki/certificates/{issuer_name_b64}/{akid_hex}").json() else: response = self.get_dcld_cmd_output_json( - ['query', 'pki', 'x509-cert', '-u', crl_signer_issuer_name_b64, '-k', crl_signer_authority_key_id]) + ['query', 'pki', 'x509-cert', '-u', issuer_name_b64, '-k', akid_hex]) + + issuer_certificate = response["approvedCertificates"]["certs"][0]["pemCert"] + + logging.debug(f"issuer: {issuer_certificate}") - return response["approvedCertificates"]["certs"][0]["pemCert"] + try: + issuer_certificate_object = x509.load_pem_x509_certificate(bytes(issuer_certificate, 'utf-8')) + except Exception: + logging.error('Failed to parse PAA certificate') + return + + return issuer_certificate_object def get_revocations_points_by_skid(self, issuer_subject_key_id) -> list[dict]: ''' @@ -211,6 +338,7 @@ def get_revocations_points_by_skid(self, issuer_subject_key_id) -> list[dict]: list[dict] List of revocation points ''' + if self.use_rest: response = requests.get(f"{self.rest_node_url}/dcl/pki/revocation-points/{issuer_subject_key_id}").json() else: @@ -268,97 +396,55 @@ def main(use_main_net_dcld: str, use_test_net_dcld: str, use_main_net_http: bool continue # 2. Parse the certificate - crl_signer_certificate = x509.load_pem_x509_certificate(bytes(revocation_point["crlSignerCertificate"], 'utf-8')) - - vid = revocation_point["vid"] - pid = revocation_point["pid"] - is_paa = revocation_point["isPAA"] - - # 3. && 4. Validate VID/PID - crl_vid, crl_pid = parse_vid_pid_from_distinguished_name(crl_signer_certificate.subject) - - if is_paa: - if crl_vid is not None: - if vid != crl_vid: - logging.warning("VID is not CRL VID, continue...") - continue - else: - if crl_vid is None or vid != crl_vid: - logging.warning("VID is not CRL VID, continue...") - continue - if crl_pid is not None: - if pid != crl_pid: - logging.warning("PID is not CRL PID, continue...") - continue - - # 5. Validate the certification path containing CRLSignerCertificate. - crl_signer_issuer_name = base64.b64encode(crl_signer_certificate.issuer.public_bytes()).decode('utf-8') - - crl_signer_authority_key_id = crl_signer_certificate.extensions.get_extension_for_oid( - x509.OID_AUTHORITY_KEY_IDENTIFIER).value.key_identifier - - # Convert CRL Signer AKID to colon separated hex - crl_signer_authority_key_id = crl_signer_authority_key_id.hex().upper() - crl_signer_authority_key_id = ':'.join([crl_signer_authority_key_id[i:i+2] - for i in range(0, len(crl_signer_authority_key_id), 2)]) - - paa_certificate = dcld_client.get_paa_cert_for_crl_issuer(crl_signer_issuer_name, crl_signer_authority_key_id) - - if paa_certificate is None: - logging.warning("PAA Certificate not found, continue...") + try: + crl_signer_certificate = x509.load_pem_x509_certificate(bytes(revocation_point["crlSignerCertificate"], 'utf-8')) + except Exception: + logging.warning("CRL Signer Certificate is not valid, continue...") continue - paa_certificate_object = x509.load_pem_x509_certificate(bytes(paa_certificate, 'utf-8')) + # Parse the crl signer delegator + crl_signer_delegator_cert = None + if "crlSignerDelegator" in revocation_point: + crl_signer_delegator_cert_pem = revocation_point["crlSignerDelegator"] + logging.debug(f"CRLSignerDelegator: {crl_signer_delegator_cert_pem}") + try: + crl_signer_delegator_cert = x509.load_pem_x509_certificate(bytes(crl_signer_delegator_cert_pem, 'utf-8')) + except Exception: + logging.warning("CRL Signer Delegator Certificate not found...") - # TODO: use verify_directly_issued_by() method when we upgrade cryptography to v40.0.0 - # Verify issuer matches with subject - if crl_signer_certificate.issuer != paa_certificate_object.subject: - logging.warning("CRL Signer Certificate issuer does not match with PAA Certificate subject, continue...") + # 3. and 4. Validate VID/PID + if not validate_vid_pid(revocation_point, crl_signer_certificate, crl_signer_delegator_cert): + logging.warning("Failed to validate VID/PID, continue...") continue - # Check crl signers AKID matches with SKID of paa_certificate_object's AKID - paa_skid = paa_certificate_object.extensions.get_extension_for_oid(x509.OID_SUBJECT_KEY_IDENTIFIER).value.key_identifier - crl_akid = crl_signer_certificate.extensions.get_extension_for_oid(x509.OID_AUTHORITY_KEY_IDENTIFIER).value.key_identifier - if paa_skid != crl_akid: - logging.warning("CRL Signer's AKID does not match with PAA Certificate SKID, continue...") + # 5. Validate the certification path containing CRLSignerCertificate. + paa_certificate_object = dcld_client.get_issuer_cert(crl_signer_certificate) + if paa_certificate_object is None: + logging.warning("PAA Certificate not found, continue...") continue - # verify if PAA singed the crl signer certificate - try: - paa_certificate_object.public_key().verify(crl_signer_certificate.signature, - crl_signer_certificate.tbs_certificate_bytes, - ec.ECDSA(crl_signer_certificate.signature_hash_algorithm)) - except Exception: - logging.warning("CRL Signer Certificate is not signed by PAA Certificate, continue...") + if validate_cert_chain(crl_signer_certificate, crl_signer_delegator_cert, paa_certificate_object) is False: + logging.warning("Failed to validate CRL Signer Certificate chain, continue...") continue # 6. Obtain the CRL - logging.debug(f"Fetching CRL from {revocation_point['dataURL']}") - try: - r = requests.get(revocation_point["dataURL"], timeout=5) - except Exception: - logging.error('Failed to fetch CRL') - continue - - try: - crl_file = x509.load_der_x509_crl(r.content) - except Exception: - logging.error('Failed to load CRL') + crl_file = fetch_crl_from_url(revocation_point["dataURL"], 5) # timeout in seconds + if crl_file is None: continue # 7. Perform CRL File Validation - crl_authority_key_id = crl_file.extensions.get_extension_for_oid(x509.OID_AUTHORITY_KEY_IDENTIFIER).value.key_identifier - crl_signer_subject_key_id = crl_signer_certificate.extensions.get_extension_for_oid( - x509.OID_SUBJECT_KEY_IDENTIFIER).value.key_identifier - if crl_authority_key_id != crl_signer_subject_key_id: - logging.warning("CRL Authority Key ID is not CRL Signer Subject Key ID, continue...") + # a. + crl_signer_skid = get_skid(crl_signer_certificate) + crl_akid = get_akid(crl_file) + if crl_akid != crl_signer_skid: + logging.warning("CRL AKID is not CRL Signer SKID, continue...") continue - issuer_subject_key_id = ''.join('{:02X}'.format(x) for x in crl_authority_key_id) + crl_akid_hex = ''.join('{:02X}'.format(x) for x in crl_akid) # b. - same_issuer_points = dcld_client.get_revocations_points_by_skid(issuer_subject_key_id) - count_with_matching_vid_issuer_skid = sum(item.get('vid') == vid for item in same_issuer_points) + same_issuer_points = dcld_client.get_revocations_points_by_skid(crl_akid_hex) + count_with_matching_vid_issuer_skid = sum(item.get('vid') == revocation_point["vid"] for item in same_issuer_points) if count_with_matching_vid_issuer_skid > 1: try: @@ -377,40 +463,61 @@ def main(use_main_net_dcld: str, use_test_net_dcld: str, use_main_net_http: bool logging.warning("CRL Issuing Distribution Point URI is not CRL URL, continue...") continue - # 9. Assign CRL File Issuer - certificate_authority_name = base64.b64encode(crl_file.issuer.public_bytes()).decode('utf-8') - logging.debug(f"CRL File Issuer: {certificate_authority_name}") + # TODO: 8. Validate CRL as per Section 6.3 of RFC 5280 + + # 9. decide on certificate authority name and AKID + if revocation_point["isPAA"] and not is_self_signed_certificate(crl_signer_certificate): + certificate_authority_name_b64 = get_subject_b64(paa_certificate_object) + certificate_akid = get_skid(paa_certificate_object) + elif crl_signer_delegator_cert: + certificate_authority_name_b64 = get_subject_b64(crl_signer_delegator_cert) + certificate_akid = get_skid(crl_signer_delegator_cert) + else: + certificate_authority_name_b64 = get_subject_b64(crl_signer_certificate) + certificate_akid = get_skid(crl_signer_certificate) + + # validate issuer skid matchces with the one in revocation points + certificate_akid_hex = ''.join('{:02X}'.format(x) for x in certificate_akid) + + logging.debug(f"Certificate Authority Name: {certificate_authority_name_b64}") + logging.debug(f"Certificate AKID: {certificate_akid_hex}") + logging.debug(f"revocation_point['issuerSubjectKeyID']: {revocation_point['issuerSubjectKeyID']}") + + if revocation_point["issuerSubjectKeyID"] != certificate_akid_hex: + logging.warning("CRL Issuer Subject Key ID is not CRL Signer Subject Key ID, continue...") + continue serialnumber_list = [] # 10. Iterate through the Revoked Certificates List for revoked_cert in crl_file: - # a. try: revoked_cert_issuer = revoked_cert.extensions.get_extension_for_oid( x509.CRLEntryExtensionOID.CERTIFICATE_ISSUER).value.get_values_for_type(x509.DirectoryName).value if revoked_cert_issuer is not None: - if revoked_cert_issuer != certificate_authority_name: + # check if this really are the same thing + if revoked_cert_issuer != certificate_authority_name_b64: logging.warning("CRL Issuer is not CRL File Issuer, continue...") continue except Exception: + logging.warning("certificateIssuer entry extension not found in CRL") pass - # b. - # TODO: Verify that the certificate chain of the entry is linking to the same PAA - # that issued the CRLSignerCertificate for this entry, including path through - # CRLSignerDelegator if present. If the PAAs under which were issued the certificate - # and the CRLSignerCertificate are different, ignore the entry. - - # c. and d. serialnumber_list.append(bytes(str('{:02X}'.format(revoked_cert.serial_number)), 'utf-8').decode('utf-8')) - issuer_name = base64.b64encode(crl_file.issuer.public_bytes()).decode('utf-8') + entry = { + "type": "revocation_set", + "issuer_subject_key_id": certificate_akid_hex, + "issuer_name": certificate_authority_name_b64, + "revoked_serial_numbers": serialnumber_list, + "crl_signer_cert": revocation_point["crlSignerCertificate"], + } + + if "crlSignerDelegator" in revocation_point: + entry["crl_signer_delegator"] = revocation_point["crlSignerDelegator"] - revocation_set.append({"type": "revocation_set", - "issuer_subject_key_id": issuer_subject_key_id, - "issuer_name": issuer_name, - "revoked_serial_numbers": serialnumber_list}) + logging.debug(f"Entry to append: {entry}") + revocation_set.append(entry) with open(output, 'w+') as outfile: json.dump(revocation_set, outfile, indent=4) From b2ebece04b747a9d0e9fdd1f558cc5aa5d942b4f Mon Sep 17 00:00:00 2001 From: Amine Alami <43780877+Alami-Amine@users.noreply.github.com> Date: Tue, 12 Nov 2024 13:30:20 +0100 Subject: [PATCH 119/121] [VSCode] Add Debugging targets for pw_fuzzer FuzzTests: (#36453) Two Targets are added: 1- Unit Test Mode: which executes all FuzzTests in a single binary for a few seconds 2- Continous Fuzzing Mode: we choose a specific FuzzTest, it will only stop execution once a crash occurs or user explicitly Interrupts it --- .vscode/launch.json | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/.vscode/launch.json b/.vscode/launch.json index fc821c76eb802c..97ba95d77f0bad 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -34,6 +34,25 @@ "args": [], "cwd": "${workspaceFolder}" }, + + { + "name": "Run pw FuzzTest (Linux x64) UnitTest Mode", + "type": "cppdbg", + "request": "launch", + "program": "${workspaceFolder}/out/${input:outPWFuzzTestLinux}", + "cwd": "${workspaceFolder}" + }, + + { + "name": "Run pw FuzzTest (Linux x64) Continuous Fuzzing Mode", + "type": "cppdbg", + "request": "launch", + "program": "${workspaceFolder}/out/${input:outPWFuzzTestLinux}", + "args": ["-fuzz=${input:fuzzTestName}"], + "cwd": "${workspaceFolder}", + "preLaunchTask": "" + }, + { "name": "QRCode Tests", "type": "cppdbg", @@ -528,6 +547,24 @@ "description": "Select the test to run" } }, + { + "type": "command", + "id": "outPWFuzzTestLinux", + "command": "shellCommand.execute", + "args": { + "command": "find ${workspaceFolder}/out/linux-x64-*/chip_pw_fuzztest/tests -type f -executable |sort |sed 's$${workspaceFolder}/out/$$'", + "description": "Select the FuzzTest to run" + } + }, + { + "id": "fuzzTestName", + "type": "command", + "command": "shellCommand.execute", + "args": { + "command": "./out/${input:outPWFuzzTestLinux} --list_fuzz_tests | grep 'Fuzz test:' | awk -F ': ' '{print $2}'", + "description": "Select the specific FuzzTest to fuzz continuously" + } + }, { "type": "pickString", "id": "mbedDebugProfile", From a0992d0fbb4880082135ff6b7d6430853c4ce789 Mon Sep 17 00:00:00 2001 From: fesseha-eve <88329315+fessehaeve@users.noreply.github.com> Date: Tue, 12 Nov 2024 15:01:08 +0000 Subject: [PATCH 120/121] improve naming and description of parameters in CHIPCryptoPAL functions (#36470) - w0s and w1s are not exactly identical to w0 and w1 --- src/crypto/CHIPCryptoPAL.cpp | 8 ++--- src/crypto/CHIPCryptoPAL.h | 32 +++++++++---------- src/crypto/CHIPCryptoPALOpenSSL.cpp | 6 ++-- src/crypto/CHIPCryptoPALPSA.cpp | 4 +-- src/crypto/CHIPCryptoPALmbedTLS.cpp | 4 +-- src/crypto/PSASpake2p.cpp | 14 ++++---- src/crypto/PSASpake2p.h | 11 ++++--- .../crypto/trustm/CHIPCryptoPALHost.cpp | 4 +-- .../common/crypto/CHIPCryptoPALTinyCrypt.cpp | 4 +-- .../nxp/common/crypto/CHIPCryptoPalS200.cpp | 4 +-- .../nxp/crypto/se05x/CHIPCryptoPALHost.cpp | 4 +-- .../se05x/CHIPCryptoPALHsm_se05x_spake2p.cpp | 12 +++---- .../crypto/CHIPCryptoPALNXPUltrafastP256.cpp | 4 +-- .../silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp | 4 +-- .../silabs/efr32/CHIPCryptoPALPsaEfr32.cpp | 4 +-- 15 files changed, 60 insertions(+), 59 deletions(-) diff --git a/src/crypto/CHIPCryptoPAL.cpp b/src/crypto/CHIPCryptoPAL.cpp index 2caecbcb156779..1ac01d033dbcdf 100644 --- a/src/crypto/CHIPCryptoPAL.cpp +++ b/src/crypto/CHIPCryptoPAL.cpp @@ -330,16 +330,16 @@ CHIP_ERROR Spake2p::BeginVerifier(const uint8_t * my_identity, size_t my_identit } CHIP_ERROR Spake2p::BeginProver(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity, - size_t peer_identity_len, const uint8_t * w0in, size_t w0in_len, const uint8_t * w1in, - size_t w1in_len) + size_t peer_identity_len, const uint8_t * w0sin, size_t w0sin_len, const uint8_t * w1sin, + size_t w1sin_len) { VerifyOrReturnError(state == CHIP_SPAKE2P_STATE::INIT, CHIP_ERROR_INTERNAL); ReturnErrorOnFailure(InternalHash(my_identity, my_identity_len)); ReturnErrorOnFailure(InternalHash(peer_identity, peer_identity_len)); ReturnErrorOnFailure(WriteMN()); - ReturnErrorOnFailure(FELoad(w0in, w0in_len, w0)); - ReturnErrorOnFailure(FELoad(w1in, w1in_len, w1)); + ReturnErrorOnFailure(FELoad(w0sin, w0sin_len, w0)); + ReturnErrorOnFailure(FELoad(w1sin, w1sin_len, w1)); state = CHIP_SPAKE2P_STATE::STARTED; role = CHIP_SPAKE2P_ROLE::PROVER; diff --git a/src/crypto/CHIPCryptoPAL.h b/src/crypto/CHIPCryptoPAL.h index b0790f85deb54f..45e13f26bb782c 100644 --- a/src/crypto/CHIPCryptoPAL.h +++ b/src/crypto/CHIPCryptoPAL.h @@ -1163,16 +1163,16 @@ class Spake2p * @param my_identity_len The prover identity length. * @param peer_identity The peer identity. May be NULL if identities are not established. * @param peer_identity_len The peer identity length. - * @param w0in The input w0 (an output from the PBKDF). - * @param w0in_len The input w0 length. - * @param w1in The input w1 (an output from the PBKDF). - * @param w1in_len The input w1 length. + * @param w0sin The input w0s (an output from the PBKDF). + * @param w0sin_len The input w0s length. + * @param w1sin The input w1s (an output from the PBKDF). + * @param w1sin_len The input w1s length. * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ virtual CHIP_ERROR BeginProver(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity, - size_t peer_identity_len, const uint8_t * w0in, size_t w0in_len, const uint8_t * w1in, - size_t w1in_len); + size_t peer_identity_len, const uint8_t * w0sin, size_t w0sin_len, const uint8_t * w1sin, + size_t w1sin_len); /** * @brief Compute the first round of the protocol. @@ -1347,26 +1347,26 @@ class Spake2p /* * @synopsis Compute w0sin mod p * - * @param w0out Output field element (modulo p) + * @param w0out Output field element w0 * @param w0_len Output field element length - * @param w1sin Input field element - * @param w1sin_len Input field element length + * @param w0sin Input field element + * @param w0sin_len Input field element length * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ virtual CHIP_ERROR ComputeW0(uint8_t * w0out, size_t * w0_len, const uint8_t * w0sin, size_t w0sin_len) = 0; /* - * @synopsis Compute w1in*G + * @synopsis Compute w1in*G where w1in is w1sin mod p * * @param Lout Output point in 0x04 || X || Y format. * @param L_len Output point length - * @param w1in Input field element - * @param w1in_len Input field element size + * @param w1sin Input field element + * @param w1sin_len Input field element size * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ - virtual CHIP_ERROR ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) = 0; + virtual CHIP_ERROR ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) = 0; void * M; void * N; @@ -1521,7 +1521,7 @@ class Spake2p_P256_SHA256_HKDF_HMAC : public Spake2p CHIP_ERROR PointIsValid(void * R) override; CHIP_ERROR ComputeW0(uint8_t * w0out, size_t * w0_len, const uint8_t * w0sin, size_t w0sin_len) override; - CHIP_ERROR ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) override; + CHIP_ERROR ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) override; protected: CHIP_ERROR InitImpl() override; @@ -1561,12 +1561,12 @@ class Spake2pVerifier CHIP_ERROR Generate(uint32_t pbkdf2IterCount, const ByteSpan & salt, uint32_t setupPin); /** - * @brief Compute the initiator values (w0, w1) used for PAKE input. + * @brief Compute the initiator values (w0s, w1s) used for PAKE input. * * @param pbkdf2IterCount Iteration count for PBKDF2 function * @param salt Salt to be used for Spake2+ operation * @param setupPin Provided setup PIN (passcode) - * @param ws The output pair (w0, w1) stored sequentially + * @param ws The output pair (w0s, w1s) stored sequentially * @param ws_len The output length * * @return CHIP_ERROR The result from running PBKDF2 diff --git a/src/crypto/CHIPCryptoPALOpenSSL.cpp b/src/crypto/CHIPCryptoPALOpenSSL.cpp index 56e8bf9fc40922..033be4488844b3 100644 --- a/src/crypto/CHIPCryptoPALOpenSSL.cpp +++ b/src/crypto/CHIPCryptoPALOpenSSL.cpp @@ -1608,7 +1608,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_ERROR_INTERNAL; int error_openssl = 0; @@ -1623,8 +1623,8 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le Lout_point = EC_POINT_new(context->curve); VerifyOrExit(Lout_point != nullptr, error = CHIP_ERROR_INTERNAL); - VerifyOrExit(CanCastTo(w1in_len), error = CHIP_ERROR_INTERNAL); - BN_bin2bn(Uint8::to_const_uchar(w1in), static_cast(w1in_len), w1_bn); + VerifyOrExit(CanCastTo(w1sin_len), error = CHIP_ERROR_INTERNAL); + BN_bin2bn(Uint8::to_const_uchar(w1sin), static_cast(w1sin_len), w1_bn); error_openssl = BN_mod(w1_bn, w1_bn, (BIGNUM *) order, context->bn_ctx); VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL); diff --git a/src/crypto/CHIPCryptoPALPSA.cpp b/src/crypto/CHIPCryptoPALPSA.cpp index ba34669a51ba94..eb67240232240a 100644 --- a/src/crypto/CHIPCryptoPALPSA.cpp +++ b/src/crypto/CHIPCryptoPALPSA.cpp @@ -1042,7 +1042,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -1058,7 +1058,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le result = mbedtls_ecp_group_load(&curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); + result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1sin), w1sin_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &curve.N); diff --git a/src/crypto/CHIPCryptoPALmbedTLS.cpp b/src/crypto/CHIPCryptoPALmbedTLS.cpp index 4df0ce97e30989..b2726424abc016 100644 --- a/src/crypto/CHIPCryptoPALmbedTLS.cpp +++ b/src/crypto/CHIPCryptoPALmbedTLS.cpp @@ -1092,7 +1092,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -1108,7 +1108,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le result = mbedtls_ecp_group_load(&curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); + result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1sin), w1sin_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &curve.N); diff --git a/src/crypto/PSASpake2p.cpp b/src/crypto/PSASpake2p.cpp index ae98b083c8a812..6625f970db92e8 100644 --- a/src/crypto/PSASpake2p.cpp +++ b/src/crypto/PSASpake2p.cpp @@ -94,11 +94,11 @@ CHIP_ERROR PSASpake2p_P256_SHA256_HKDF_HMAC::BeginVerifier(const uint8_t * my_id CHIP_ERROR PSASpake2p_P256_SHA256_HKDF_HMAC::BeginProver(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity, size_t peer_identity_len, - const uint8_t * w0in, size_t w0in_len, const uint8_t * w1in, - size_t w1in_len) + const uint8_t * w0sin, size_t w0sin_len, const uint8_t * w1sin, + size_t w1sin_len) { - VerifyOrReturnError(w0in_len <= kSpake2p_WS_Length, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(w1in_len <= kSpake2p_WS_Length, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(w0sin_len <= kSpake2p_WS_Length, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(w1sin_len <= kSpake2p_WS_Length, CHIP_ERROR_INVALID_ARGUMENT); uint8_t password[kSpake2p_WS_Length * 2]; psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; @@ -107,13 +107,13 @@ CHIP_ERROR PSASpake2p_P256_SHA256_HKDF_HMAC::BeginProver(const uint8_t * my_iden psa_pake_cs_set_algorithm(&cp, PSA_ALG_SPAKE2P_MATTER); psa_pake_cs_set_primitive(&cp, PSA_PAKE_PRIMITIVE(PSA_PAKE_PRIMITIVE_TYPE_ECC, PSA_ECC_FAMILY_SECP_R1, 256)); - memcpy(password + 0, w0in, w0in_len); - memcpy(password + w0in_len, w1in, w1in_len); + memcpy(password + 0, w0sin, w0sin_len); + memcpy(password + w0sin_len, w1sin, w1sin_len); psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE); psa_set_key_algorithm(&attributes, PSA_ALG_SPAKE2P_MATTER); psa_set_key_type(&attributes, PSA_KEY_TYPE_SPAKE2P_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1)); - psa_status_t status = psa_import_key(&attributes, password, w0in_len + w1in_len, &mKey); + psa_status_t status = psa_import_key(&attributes, password, w0sin_len + w1sin_len, &mKey); psa_reset_key_attributes(&attributes); VerifyOrReturnError(status == PSA_SUCCESS, CHIP_ERROR_INTERNAL); diff --git a/src/crypto/PSASpake2p.h b/src/crypto/PSASpake2p.h index 9907b1ec09a5bc..163769037005d5 100644 --- a/src/crypto/PSASpake2p.h +++ b/src/crypto/PSASpake2p.h @@ -89,15 +89,16 @@ class PSASpake2p_P256_SHA256_HKDF_HMAC * @param my_identity_len The prover identity length. * @param peer_identity The peer identity. May be NULL if identities are not established. * @param peer_identity_len The peer identity length. - * @param w0in The input w0 (an output from the PBKDF). - * @param w0in_len The input w0 length. - * @param w1in The input w1 (an output from the PBKDF). - * @param w1in_len The input w1 length. + * @param w0sin The input w0s (an output from the PBKDF). + * @param w0sin_len The input w0s length. + * @param w1sin The input w1s (an output from the PBKDF). + * @param w1sin_len The input w1s length. * * @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise **/ CHIP_ERROR BeginProver(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity, - size_t peer_identity_len, const uint8_t * w0in, size_t w0in_len, const uint8_t * w1in, size_t w1in_len); + size_t peer_identity_len, const uint8_t * w0sin, size_t w0sin_len, const uint8_t * w1sin, + size_t w1sin_len); /** * @brief Compute the first round of the protocol. diff --git a/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHost.cpp b/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHost.cpp index f33058f8e9af99..0332b687fcdfde 100644 --- a/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHost.cpp +++ b/src/platform/Infineon/crypto/trustm/CHIPCryptoPALHost.cpp @@ -838,7 +838,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -854,7 +854,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le result = mbedtls_ecp_group_load(&curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); + result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1sin), w1sin_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &curve.N); diff --git a/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp b/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp index 9c6334bded2da6..e23453eb97b1df 100644 --- a/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp +++ b/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp @@ -1051,7 +1051,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -1061,7 +1061,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le uECC_word_t w1_bn[NUM_ECC_WORDS]; uECC_word_t L_tmp[2 * NUM_ECC_WORDS]; - uECC_vli_bytesToNative(tmp, w1in, NUM_ECC_BYTES); + uECC_vli_bytesToNative(tmp, w1sin, NUM_ECC_BYTES); uECC_vli_mmod(w1_bn, tmp, curve_n); diff --git a/src/platform/nxp/common/crypto/CHIPCryptoPalS200.cpp b/src/platform/nxp/common/crypto/CHIPCryptoPalS200.cpp index 6e9342658c7ddd..21e76c69d79b92 100644 --- a/src/platform/nxp/common/crypto/CHIPCryptoPalS200.cpp +++ b/src/platform/nxp/common/crypto/CHIPCryptoPalS200.cpp @@ -1138,13 +1138,13 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { secEcp256Status_t result; ecp256Point_t gen_point; uint32_t W1[SEC_ECP256_COORDINATE_WLEN]; - result = ECP256_ModularReductionN(W1, w1in, w1in_len); + result = ECP256_ModularReductionN(W1, w1sin, w1sin_len); VerifyOrReturnError(result == gSecEcp256Success_c, CHIP_ERROR_INTERNAL); result = ECP256_GeneratePublicKey((uint8_t *) &gen_point, (uint8_t *) &W1, NULL); diff --git a/src/platform/nxp/crypto/se05x/CHIPCryptoPALHost.cpp b/src/platform/nxp/crypto/se05x/CHIPCryptoPALHost.cpp index ffc626c201d373..68a38a98f405d6 100644 --- a/src/platform/nxp/crypto/se05x/CHIPCryptoPALHost.cpp +++ b/src/platform/nxp/crypto/se05x/CHIPCryptoPALHost.cpp @@ -712,7 +712,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -728,7 +728,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le result = mbedtls_ecp_group_load(&curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); - result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); + result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1sin), w1sin_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &curve.N); diff --git a/src/platform/nxp/crypto/se05x/CHIPCryptoPALHsm_se05x_spake2p.cpp b/src/platform/nxp/crypto/se05x/CHIPCryptoPALHsm_se05x_spake2p.cpp index 84216185a68f6e..ee2bb79b1a02d0 100644 --- a/src/platform/nxp/crypto/se05x/CHIPCryptoPALHsm_se05x_spake2p.cpp +++ b/src/platform/nxp/crypto/se05x/CHIPCryptoPALHsm_se05x_spake2p.cpp @@ -283,8 +283,8 @@ CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::BeginVerifier(const uint8_t * my_id #if ENABLE_SE05X_SPAKE_PROVER CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::BeginProver(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity, size_t peer_identity_len, - const uint8_t * w0in, size_t w0in_len, const uint8_t * w1in, - size_t w1in_len) + const uint8_t * w0sin, size_t w0sin_len, const uint8_t * w1sin, + size_t w1sin_len) { smStatus_t smstatus = SM_NOT_OK; uint8_t w0in_mod[32] = { @@ -296,8 +296,8 @@ CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::BeginProver(const uint8_t * my_iden }; size_t w1in_mod_len = 32; - VerifyOrReturnError(w0in != nullptr, CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(w1in != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(w0sin != nullptr, CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(w1sin != nullptr, CHIP_ERROR_INVALID_ARGUMENT); if (my_identity_len > 0) { VerifyOrReturnError(my_identity != nullptr, CHIP_ERROR_INVALID_ARGUMENT); @@ -311,9 +311,9 @@ CHIP_ERROR Spake2pHSM_P256_SHA256_HKDF_HMAC::BeginProver(const uint8_t * my_iden ChipLogProgress(Crypto, "SE05x: HSM - BeginProver"); - ReturnErrorOnFailure(FELoad(w0in, w0in_len, w0)); + ReturnErrorOnFailure(FELoad(w0sin, w0sin_len, w0)); ReturnErrorOnFailure(FEWrite(w0, w0in_mod, w0in_mod_len)); - ReturnErrorOnFailure(FELoad(w1in, w1in_len, w1)); + ReturnErrorOnFailure(FELoad(w1sin, w1sin_len, w1)); ReturnErrorOnFailure(FEWrite(w1, w1in_mod, w1in_mod_len)); ReturnErrorOnFailure(create_init_crypto_obj(chip::Crypto::CHIP_SPAKE2P_ROLE::PROVER, &hsm_pake_context)); diff --git a/src/platform/nxp/k32w0/crypto/CHIPCryptoPALNXPUltrafastP256.cpp b/src/platform/nxp/k32w0/crypto/CHIPCryptoPALNXPUltrafastP256.cpp index 8b30cdd0ce7b78..25aa5313ec1e5e 100644 --- a/src/platform/nxp/k32w0/crypto/CHIPCryptoPALNXPUltrafastP256.cpp +++ b/src/platform/nxp/k32w0/crypto/CHIPCryptoPALNXPUltrafastP256.cpp @@ -1017,7 +1017,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; @@ -1026,7 +1026,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le uint32_t W1[SEC_ECP256_COORDINATE_WLEN]; do { - result = ECP256_ModularReductionN(W1, w1in, w1in_len); + result = ECP256_ModularReductionN(W1, w1sin, w1sin_len); if (result != gSecEcp256Success_c) break; ecp256Point_t gen_point; diff --git a/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp b/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp index 05fa10c5832ac2..b8278b359d5233 100644 --- a/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp +++ b/src/platform/silabs/SiWx917/CHIPCryptoPALTinyCrypt.cpp @@ -1070,7 +1070,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -1080,7 +1080,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le uECC_word_t w1_bn[NUM_ECC_WORDS]; uECC_word_t L_tmp[2 * NUM_ECC_WORDS]; - uECC_vli_bytesToNative(tmp, w1in, NUM_ECC_BYTES); + uECC_vli_bytesToNative(tmp, w1sin, NUM_ECC_BYTES); uECC_vli_mmod(w1_bn, tmp, curve_n); diff --git a/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp b/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp index 8028d84d92c40c..a1811a1093337a 100644 --- a/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp +++ b/src/platform/silabs/efr32/CHIPCryptoPALPsaEfr32.cpp @@ -1406,7 +1406,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) return CHIP_NO_ERROR; } -CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) +CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1sin, size_t w1sin_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; @@ -1418,7 +1418,7 @@ CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_le mbedtls_mpi_init(&w1_bn); mbedtls_ecp_point_init(&Ltemp); - result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); + result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1sin), w1sin_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &context->curve.N); From ebfd212d61b8a0610805a0108af28cde164ca959 Mon Sep 17 00:00:00 2001 From: Pradip De Date: Tue, 12 Nov 2024 15:55:28 +0000 Subject: [PATCH 121/121] Camera AVStreamMgmt SDK changes for spec updates (#36447) * Incorporate Spec updates to CameraAVStreamMgmt cluster - Use Alchemy to re-generate the xml. - Add feature tag to attributes and commands. - Remove SetViewport and ImageRotation commands. * Autogenerated files after running zap_regen_all.py. --- .../camera-av-stream-management-cluster.xml | 436 ++++-- .../data_model/controller-clusters.matter | 76 +- .../chip/devicecontroller/ChipClusters.java | 330 +---- .../devicecontroller/ClusterIDMapping.java | 112 +- .../devicecontroller/ClusterInfoMapping.java | 66 - .../devicecontroller/ClusterReadMapping.java | 44 - .../devicecontroller/ClusterWriteMapping.java | 208 +-- .../CameraAvStreamManagementCluster.kt | 1062 +++----------- .../CHIPAttributeTLVValueDecoder.cpp | 64 - .../python/chip/clusters/CHIPClusters.py | 112 +- .../python/chip/clusters/Objects.py | 216 +-- .../MTRAttributeSpecifiedCheck.mm | 12 - .../MTRAttributeTLVValueDecoder.mm | 44 - .../CHIP/zap-generated/MTRBaseClusters.h | 84 +- .../CHIP/zap-generated/MTRBaseClusters.mm | 537 ++------ .../CHIP/zap-generated/MTRClusterConstants.h | 42 +- .../CHIP/zap-generated/MTRClusterNames.mm | 32 - .../CHIP/zap-generated/MTRClusters.h | 36 +- .../CHIP/zap-generated/MTRClusters.mm | 250 +--- .../zap-generated/MTRCommandPayloadsObjc.h | 120 -- .../zap-generated/MTRCommandPayloadsObjc.mm | 319 ----- .../MTRCommandPayloads_Internal.h | 24 - .../zap-generated/attributes/Accessors.cpp | 190 --- .../zap-generated/attributes/Accessors.h | 26 - .../app-common/zap-generated/callback.h | 24 - .../app-common/zap-generated/cluster-enums.h | 12 +- .../zap-generated/cluster-objects.cpp | 144 -- .../zap-generated/cluster-objects.h | 201 --- .../app-common/zap-generated/ids/Attributes.h | 50 +- .../app-common/zap-generated/ids/Commands.h | 16 - .../zap-generated/cluster/Commands.h | 275 +--- .../cluster/logging/DataModelLogger.cpp | 20 - .../cluster/logging/EntryToText.cpp | 16 - .../zap-generated/cluster/Commands.h | 1225 ++++------------- 34 files changed, 1240 insertions(+), 5185 deletions(-) diff --git a/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml b/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml index 67761b41e8efc2..24c66bcc7a7a9c 100644 --- a/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml +++ b/src/app/zap-templates/zcl/data-model/chip/camera-av-stream-management-cluster.xml @@ -18,10 +18,10 @@ limitations under the License. XML generated by Alchemy; DO NOT EDIT. Source: src/app_clusters/CameraAVStreamManagement.adoc Parameters: in-progress -Git: 0.9-fall2024-411-g9835b5cd7 +Git: 1.3-3824-g29c49ca54 --> - + @@ -144,152 +144,323 @@ Git: 0.9-fall2024-411-g9835b5cd7
- + Cameras Camera AV Stream Management 0x0551 CAMERA_AV_STREAM_MANAGEMENT_CLUSTER The Camera AV Stream Management cluster is used to allow clients to manage, control, and configure various audio, video, and snapshot streams on a camera. true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - MaxConcurrentVideoEncoders - MaxEncodedPixelRate - VideoSensorParams - NightVisionCapable - MinViewport - RateDistortionTradeOffPoints - MaxContentBufferSize - MicrophoneCapabilities - SpeakerCapabilities - TwoWayTalkSupport - SupportedSnapshotParams - MaxNetworkBandwidth - CurrentFrameRate - + + MaxConcurrentVideoEncoders + + + + + + MaxEncodedPixelRate + + + + + + VideoSensorParams + + + + + + NightVisionCapable + + + + + + MinViewport + + + + + + RateDistortionTradeOffPoints + + + + + + MaxContentBufferSize + + + + + + MicrophoneCapabilities + + + + + + SpeakerCapabilities + + + + + + + + + TwoWayTalkSupport + + + + + + + + + SupportedSnapshotParams + + + + + MaxNetworkBandwidth + + CurrentFrameRate + + + + + + HDRModeEnabled + + + + + + CurrentVideoCodecs + + + + + + CurrentSnapshotConfig + + + + + FabricsUsingCamera + + AllocatedVideoStreams + + + + + + AllocatedAudioStreams + + + + + + AllocatedSnapshotStreams + + + - CurrentVideoCodecs - CurrentSnapshotConfig - FabricsUsingCamera - AllocatedVideoStreams - AllocatedAudioStreams - AllocatedSnapshotStreams - + + RankedVideoStreamPrioritiesList + + + - SoftRecordingPrivacyModeEnabled - SoftLivestreamPrivacyModeEnabled - HardPrivacyModeOn - + + SoftRecordingPrivacyModeEnabled + + + + + + SoftLivestreamPrivacyModeEnabled + + + + + + HardPrivacyModeOn + + + + NightVision + + + + + + - + + NightVisionIllum + + + + + + - + + Viewport + + + - + + SpeakerMuted + + + + + + - + + SpeakerVolumeLevel + + + + + + - Viewport - + + SpeakerMaxLevel - + + + + + + - + + SpeakerMinLevel - + + + + + + - + + MicrophoneMuted + + + - + + MicrophoneVolumeLevel + + + - + + MicrophoneMaxLevel - + + + - + + MicrophoneMinLevel - + + + - + + MicrophoneAGCEnabled + + + - + + ImageRotation + + + - + + ImageFlipHorizontal + + + - ImageRotation - ImageFlipHorizontal - ImageFlipVertical - + + ImageFlipVertical + + + - + + LocalVideoRecordingEnabled + + + + + + - + + LocalSnapshotRecordingEnabled + + + + + + - + + StatusLightEnabled + - + + StatusLightBrightness + This command SHALL allocate an audio stream on the camera and return an allocated audio stream identifier. @@ -300,17 +471,26 @@ Git: 0.9-fall2024-411-g9835b5cd7 + + + This command SHALL be sent by the camera in response to the AudioStreamAllocate command, carrying the newly allocated audio stream identifier. + + + This command SHALL deallocate an audio stream on the camera, corresponding to the given audio stream identifier. + + + @@ -328,11 +508,17 @@ Git: 0.9-fall2024-411-g9835b5cd7 + + + This command SHALL be sent by the camera in response to the VideoStreamAllocate command, carrying the newly allocated video stream identifier. + + + @@ -342,12 +528,18 @@ Git: 0.9-fall2024-411-g9835b5cd7 + + + This command SHALL deallocate a video stream on the camera, corresponding to the given video stream identifier. + + + @@ -359,17 +551,26 @@ Git: 0.9-fall2024-411-g9835b5cd7 + + + This command SHALL be sent by the device in response to the SnapshotStreamAllocate command, carrying the newly allocated snapshot stream identifier. + + + This command SHALL deallocate an snapshot stream on the camera, corresponding to the given snapshot stream identifier. + + + @@ -381,9 +582,11 @@ Git: 0.9-fall2024-411-g9835b5cd7 This command SHALL return a Snapshot from the camera. - + + + @@ -392,30 +595,9 @@ Git: 0.9-fall2024-411-g9835b5cd7 - - - - This command sets the viewport in all video streams. - - - - - - The data fields for this command SHALL be as follows: - - - - - - The data fields for this command SHALL be as follows: - - - - - - The data fields for this command SHALL be as follows: - - + + + @@ -431,6 +613,9 @@ Git: 0.9-fall2024-411-g9835b5cd7 This event SHALL be generated when there is a modification in the corresponding video stream. + + + @@ -442,6 +627,9 @@ Git: 0.9-fall2024-411-g9835b5cd7 This event SHALL be generated when there is a modification in the corresponding audio stream. + + + @@ -453,7 +641,39 @@ Git: 0.9-fall2024-411-g9835b5cd7 This event SHALL be generated when there is a modification in the corresponding snapshot stream. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/controller/data_model/controller-clusters.matter b/src/controller/data_model/controller-clusters.matter index 24c7e00c623b53..9e788d02825831 100644 --- a/src/controller/data_model/controller-clusters.matter +++ b/src/controller/data_model/controller-clusters.matter @@ -9566,12 +9566,12 @@ provisional cluster CameraAvStreamManagement = 1361 { } bitmap Feature : bitmap32 { - kPrivacy = 0x1; - kAudio = 0x2; - kSpeaker = 0x4; - kImageControl = 0x8; - kVideo = 0x10; - kSnapshot = 0x20; + kAudio = 0x1; + kVideo = 0x2; + kSnapshot = 0x4; + kPrivacy = 0x8; + kSpeaker = 0x10; + kImageControl = 0x20; kWatermark = 0x40; kOnScreenDisplay = 0x80; kLocalStorage = 0x100; @@ -9715,27 +9715,23 @@ provisional cluster CameraAvStreamManagement = 1361 { readonly attribute optional boolean hardPrivacyModeOn = 23; attribute access(read: manage, write: manage) optional TriStateAutoEnum nightVision = 24; attribute access(read: manage, write: manage) optional TriStateAutoEnum nightVisionIllum = 25; - attribute access(read: manage, write: manage) optional boolean AWBEnabled = 26; - attribute access(read: manage, write: manage) optional boolean autoShutterSpeedEnabled = 27; - attribute access(read: manage, write: manage) optional boolean autoISOEnabled = 28; - readonly attribute optional ViewportStruct viewport = 29; - attribute access(read: manage, write: manage) optional boolean speakerMuted = 30; - attribute access(read: manage, write: manage) optional int8u speakerVolumeLevel = 31; - attribute access(read: manage, write: manage) optional int8u speakerMaxLevel = 32; - attribute access(read: manage, write: manage) optional int8u speakerMinLevel = 33; - attribute access(read: manage, write: manage) optional boolean microphoneMuted = 34; - attribute access(read: manage, write: manage) optional int8u microphoneVolumeLevel = 35; - attribute access(read: manage, write: manage) optional int8u microphoneMaxLevel = 36; - attribute access(read: manage, write: manage) optional int8u microphoneMinLevel = 37; - attribute access(read: manage, write: manage) optional boolean microphoneAGCEnabled = 38; - readonly attribute optional int16u imageRotation = 39; - readonly attribute optional boolean imageFlipHorizontal = 40; - readonly attribute optional boolean imageFlipVertical = 41; - attribute access(read: manage, write: manage) optional boolean localVideoRecordingEnabled = 42; - attribute access(read: manage, write: manage) optional boolean localSnapshotRecordingEnabled = 43; - attribute access(read: manage, write: manage) optional boolean statusLightEnabled = 44; - attribute access(read: manage, write: manage) optional ThreeLevelAutoEnum statusLightBrightness = 45; - attribute access(read: manage, write: manage) optional TriStateAutoEnum depthSensorStatus = 46; + attribute access(read: manage, write: manage) optional ViewportStruct viewport = 26; + attribute access(read: manage, write: manage) optional boolean speakerMuted = 27; + attribute access(read: manage, write: manage) optional int8u speakerVolumeLevel = 28; + readonly attribute access(read: manage) optional int8u speakerMaxLevel = 29; + readonly attribute access(read: manage) optional int8u speakerMinLevel = 30; + attribute access(read: manage, write: manage) optional boolean microphoneMuted = 31; + attribute access(read: manage, write: manage) optional int8u microphoneVolumeLevel = 32; + readonly attribute access(read: manage) optional int8u microphoneMaxLevel = 33; + readonly attribute access(read: manage) optional int8u microphoneMinLevel = 34; + attribute access(read: manage, write: manage) optional boolean microphoneAGCEnabled = 35; + attribute access(read: manage, write: manage) optional int16u imageRotation = 36; + attribute access(read: manage, write: manage) optional boolean imageFlipHorizontal = 37; + attribute access(read: manage, write: manage) optional boolean imageFlipVertical = 38; + attribute access(read: manage, write: manage) optional boolean localVideoRecordingEnabled = 39; + attribute access(read: manage, write: manage) optional boolean localSnapshotRecordingEnabled = 40; + attribute access(read: manage, write: manage) optional boolean statusLightEnabled = 41; + attribute access(read: manage, write: manage) optional ThreeLevelAutoEnum statusLightBrightness = 42; readonly attribute command_id generatedCommandList[] = 65528; readonly attribute command_id acceptedCommandList[] = 65529; readonly attribute event_id eventList[] = 65530; @@ -9822,22 +9818,6 @@ provisional cluster CameraAvStreamManagement = 1361 { VideoResolutionStruct resolution = 2; } - request struct SetViewportRequest { - ViewportStruct viewport = 0; - } - - request struct SetImageRotationRequest { - int16u angle = 0; - } - - request struct SetImageFlipHorizontalRequest { - boolean enabled = 0; - } - - request struct SetImageFlipVerticalRequest { - boolean enabled = 0; - } - /** This command SHALL allocate an audio stream on the camera and return an allocated audio stream identifier. */ command access(invoke: manage) AudioStreamAllocate(AudioStreamAllocateRequest): AudioStreamAllocateResponse = 0; /** This command SHALL deallocate an audio stream on the camera, corresponding to the given audio stream identifier. */ @@ -9855,15 +9835,7 @@ provisional cluster CameraAvStreamManagement = 1361 { /** This command SHALL set the relative priorities of the various stream types on the camera. */ command access(invoke: administer) SetStreamPriorities(SetStreamPrioritiesRequest): DefaultSuccess = 10; /** This command SHALL return a Snapshot from the camera. */ - command access(invoke: manage) CaptureSnapshot(CaptureSnapshotRequest): DefaultSuccess = 11; - /** This command sets the viewport in all video streams. */ - command access(invoke: manage) SetViewport(SetViewportRequest): DefaultSuccess = 13; - /** The data fields for this command SHALL be as follows: */ - command access(invoke: manage) SetImageRotation(SetImageRotationRequest): DefaultSuccess = 14; - /** The data fields for this command SHALL be as follows: */ - command access(invoke: manage) SetImageFlipHorizontal(SetImageFlipHorizontalRequest): DefaultSuccess = 15; - /** The data fields for this command SHALL be as follows: */ - command access(invoke: manage) SetImageFlipVertical(SetImageFlipVerticalRequest): DefaultSuccess = 16; + command CaptureSnapshot(CaptureSnapshotRequest): DefaultSuccess = 11; } /** The WebRTC transport provider cluster provides a way for stream providers (e.g. Cameras) to stream or receive their data through WebRTC. */ diff --git a/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java b/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java index 06b8dd8ff0b54c..a01affadc9c807 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ChipClusters.java @@ -59750,27 +59750,23 @@ public static class CameraAvStreamManagementCluster extends BaseChipCluster { private static final long HARD_PRIVACY_MODE_ON_ATTRIBUTE_ID = 23L; private static final long NIGHT_VISION_ATTRIBUTE_ID = 24L; private static final long NIGHT_VISION_ILLUM_ATTRIBUTE_ID = 25L; - private static final long AWB_ENABLED_ATTRIBUTE_ID = 26L; - private static final long AUTO_SHUTTER_SPEED_ENABLED_ATTRIBUTE_ID = 27L; - private static final long AUTO_ISO_ENABLED_ATTRIBUTE_ID = 28L; - private static final long VIEWPORT_ATTRIBUTE_ID = 29L; - private static final long SPEAKER_MUTED_ATTRIBUTE_ID = 30L; - private static final long SPEAKER_VOLUME_LEVEL_ATTRIBUTE_ID = 31L; - private static final long SPEAKER_MAX_LEVEL_ATTRIBUTE_ID = 32L; - private static final long SPEAKER_MIN_LEVEL_ATTRIBUTE_ID = 33L; - private static final long MICROPHONE_MUTED_ATTRIBUTE_ID = 34L; - private static final long MICROPHONE_VOLUME_LEVEL_ATTRIBUTE_ID = 35L; - private static final long MICROPHONE_MAX_LEVEL_ATTRIBUTE_ID = 36L; - private static final long MICROPHONE_MIN_LEVEL_ATTRIBUTE_ID = 37L; - private static final long MICROPHONE_AGC_ENABLED_ATTRIBUTE_ID = 38L; - private static final long IMAGE_ROTATION_ATTRIBUTE_ID = 39L; - private static final long IMAGE_FLIP_HORIZONTAL_ATTRIBUTE_ID = 40L; - private static final long IMAGE_FLIP_VERTICAL_ATTRIBUTE_ID = 41L; - private static final long LOCAL_VIDEO_RECORDING_ENABLED_ATTRIBUTE_ID = 42L; - private static final long LOCAL_SNAPSHOT_RECORDING_ENABLED_ATTRIBUTE_ID = 43L; - private static final long STATUS_LIGHT_ENABLED_ATTRIBUTE_ID = 44L; - private static final long STATUS_LIGHT_BRIGHTNESS_ATTRIBUTE_ID = 45L; - private static final long DEPTH_SENSOR_STATUS_ATTRIBUTE_ID = 46L; + private static final long VIEWPORT_ATTRIBUTE_ID = 26L; + private static final long SPEAKER_MUTED_ATTRIBUTE_ID = 27L; + private static final long SPEAKER_VOLUME_LEVEL_ATTRIBUTE_ID = 28L; + private static final long SPEAKER_MAX_LEVEL_ATTRIBUTE_ID = 29L; + private static final long SPEAKER_MIN_LEVEL_ATTRIBUTE_ID = 30L; + private static final long MICROPHONE_MUTED_ATTRIBUTE_ID = 31L; + private static final long MICROPHONE_VOLUME_LEVEL_ATTRIBUTE_ID = 32L; + private static final long MICROPHONE_MAX_LEVEL_ATTRIBUTE_ID = 33L; + private static final long MICROPHONE_MIN_LEVEL_ATTRIBUTE_ID = 34L; + private static final long MICROPHONE_AGC_ENABLED_ATTRIBUTE_ID = 35L; + private static final long IMAGE_ROTATION_ATTRIBUTE_ID = 36L; + private static final long IMAGE_FLIP_HORIZONTAL_ATTRIBUTE_ID = 37L; + private static final long IMAGE_FLIP_VERTICAL_ATTRIBUTE_ID = 38L; + private static final long LOCAL_VIDEO_RECORDING_ENABLED_ATTRIBUTE_ID = 39L; + private static final long LOCAL_SNAPSHOT_RECORDING_ENABLED_ATTRIBUTE_ID = 40L; + private static final long STATUS_LIGHT_ENABLED_ATTRIBUTE_ID = 41L; + private static final long STATUS_LIGHT_BRIGHTNESS_ATTRIBUTE_ID = 42L; private static final long GENERATED_COMMAND_LIST_ATTRIBUTE_ID = 65528L; private static final long ACCEPTED_COMMAND_LIST_ATTRIBUTE_ID = 65529L; private static final long EVENT_LIST_ATTRIBUTE_ID = 65530L; @@ -60098,86 +60094,6 @@ public void onResponse(StructType invokeStructValue) { }}, commandId, commandArgs, timedInvokeTimeoutMs); } - public void setViewport(DefaultClusterCallback callback, ChipStructs.CameraAvStreamManagementClusterViewportStruct viewport) { - setViewport(callback, viewport, 0); - } - - public void setViewport(DefaultClusterCallback callback, ChipStructs.CameraAvStreamManagementClusterViewportStruct viewport, int timedInvokeTimeoutMs) { - final long commandId = 13L; - - ArrayList elements = new ArrayList<>(); - final long viewportFieldID = 0L; - BaseTLVType viewporttlvValue = viewport.encodeTlv(); - elements.add(new StructElement(viewportFieldID, viewporttlvValue)); - - StructType commandArgs = new StructType(elements); - invoke(new InvokeCallbackImpl(callback) { - @Override - public void onResponse(StructType invokeStructValue) { - callback.onSuccess(); - }}, commandId, commandArgs, timedInvokeTimeoutMs); - } - - public void setImageRotation(DefaultClusterCallback callback, Integer angle) { - setImageRotation(callback, angle, 0); - } - - public void setImageRotation(DefaultClusterCallback callback, Integer angle, int timedInvokeTimeoutMs) { - final long commandId = 14L; - - ArrayList elements = new ArrayList<>(); - final long angleFieldID = 0L; - BaseTLVType angletlvValue = new UIntType(angle); - elements.add(new StructElement(angleFieldID, angletlvValue)); - - StructType commandArgs = new StructType(elements); - invoke(new InvokeCallbackImpl(callback) { - @Override - public void onResponse(StructType invokeStructValue) { - callback.onSuccess(); - }}, commandId, commandArgs, timedInvokeTimeoutMs); - } - - public void setImageFlipHorizontal(DefaultClusterCallback callback, Boolean enabled) { - setImageFlipHorizontal(callback, enabled, 0); - } - - public void setImageFlipHorizontal(DefaultClusterCallback callback, Boolean enabled, int timedInvokeTimeoutMs) { - final long commandId = 15L; - - ArrayList elements = new ArrayList<>(); - final long enabledFieldID = 0L; - BaseTLVType enabledtlvValue = new BooleanType(enabled); - elements.add(new StructElement(enabledFieldID, enabledtlvValue)); - - StructType commandArgs = new StructType(elements); - invoke(new InvokeCallbackImpl(callback) { - @Override - public void onResponse(StructType invokeStructValue) { - callback.onSuccess(); - }}, commandId, commandArgs, timedInvokeTimeoutMs); - } - - public void setImageFlipVertical(DefaultClusterCallback callback, Boolean enabled) { - setImageFlipVertical(callback, enabled, 0); - } - - public void setImageFlipVertical(DefaultClusterCallback callback, Boolean enabled, int timedInvokeTimeoutMs) { - final long commandId = 16L; - - ArrayList elements = new ArrayList<>(); - final long enabledFieldID = 0L; - BaseTLVType enabledtlvValue = new BooleanType(enabled); - elements.add(new StructElement(enabledFieldID, enabledtlvValue)); - - StructType commandArgs = new StructType(elements); - invoke(new InvokeCallbackImpl(callback) { - @Override - public void onResponse(StructType invokeStructValue) { - callback.onSuccess(); - }}, commandId, commandArgs, timedInvokeTimeoutMs); - } - public interface AudioStreamAllocateResponseCallback extends BaseClusterCallback { void onSuccess(Integer audioStreamID); } @@ -60992,111 +60908,6 @@ public void onSuccess(byte[] tlv) { }, NIGHT_VISION_ILLUM_ATTRIBUTE_ID, minInterval, maxInterval); } - public void readAWBEnabledAttribute( - BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AWB_ENABLED_ATTRIBUTE_ID); - - readAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, AWB_ENABLED_ATTRIBUTE_ID, true); - } - - public void writeAWBEnabledAttribute(DefaultClusterCallback callback, Boolean value) { - writeAWBEnabledAttribute(callback, value, 0); - } - - public void writeAWBEnabledAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new BooleanType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), AWB_ENABLED_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - - public void subscribeAWBEnabledAttribute( - BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AWB_ENABLED_ATTRIBUTE_ID); - - subscribeAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, AWB_ENABLED_ATTRIBUTE_ID, minInterval, maxInterval); - } - - public void readAutoShutterSpeedEnabledAttribute( - BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AUTO_SHUTTER_SPEED_ENABLED_ATTRIBUTE_ID); - - readAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, AUTO_SHUTTER_SPEED_ENABLED_ATTRIBUTE_ID, true); - } - - public void writeAutoShutterSpeedEnabledAttribute(DefaultClusterCallback callback, Boolean value) { - writeAutoShutterSpeedEnabledAttribute(callback, value, 0); - } - - public void writeAutoShutterSpeedEnabledAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new BooleanType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), AUTO_SHUTTER_SPEED_ENABLED_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - - public void subscribeAutoShutterSpeedEnabledAttribute( - BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AUTO_SHUTTER_SPEED_ENABLED_ATTRIBUTE_ID); - - subscribeAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, AUTO_SHUTTER_SPEED_ENABLED_ATTRIBUTE_ID, minInterval, maxInterval); - } - - public void readAutoISOEnabledAttribute( - BooleanAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AUTO_ISO_ENABLED_ATTRIBUTE_ID); - - readAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, AUTO_ISO_ENABLED_ATTRIBUTE_ID, true); - } - - public void writeAutoISOEnabledAttribute(DefaultClusterCallback callback, Boolean value) { - writeAutoISOEnabledAttribute(callback, value, 0); - } - - public void writeAutoISOEnabledAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new BooleanType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), AUTO_ISO_ENABLED_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - - public void subscribeAutoISOEnabledAttribute( - BooleanAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, AUTO_ISO_ENABLED_ATTRIBUTE_ID); - - subscribeAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Boolean value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, AUTO_ISO_ENABLED_ATTRIBUTE_ID, minInterval, maxInterval); - } - public void readViewportAttribute( ViewportAttributeCallback callback) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VIEWPORT_ATTRIBUTE_ID); @@ -61110,6 +60921,15 @@ public void onSuccess(byte[] tlv) { }, VIEWPORT_ATTRIBUTE_ID, true); } + public void writeViewportAttribute(DefaultClusterCallback callback, ChipStructs.CameraAvStreamManagementClusterViewportStruct value) { + writeViewportAttribute(callback, value, 0); + } + + public void writeViewportAttribute(DefaultClusterCallback callback, ChipStructs.CameraAvStreamManagementClusterViewportStruct value, int timedWriteTimeoutMs) { + BaseTLVType tlvValue = value.encodeTlv(); + writeAttribute(new WriteAttributesCallbackImpl(callback), VIEWPORT_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + } + public void subscribeViewportAttribute( ViewportAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, VIEWPORT_ATTRIBUTE_ID); @@ -61206,15 +61026,6 @@ public void onSuccess(byte[] tlv) { }, SPEAKER_MAX_LEVEL_ATTRIBUTE_ID, true); } - public void writeSpeakerMaxLevelAttribute(DefaultClusterCallback callback, Integer value) { - writeSpeakerMaxLevelAttribute(callback, value, 0); - } - - public void writeSpeakerMaxLevelAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), SPEAKER_MAX_LEVEL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - public void subscribeSpeakerMaxLevelAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SPEAKER_MAX_LEVEL_ATTRIBUTE_ID); @@ -61241,15 +61052,6 @@ public void onSuccess(byte[] tlv) { }, SPEAKER_MIN_LEVEL_ATTRIBUTE_ID, true); } - public void writeSpeakerMinLevelAttribute(DefaultClusterCallback callback, Integer value) { - writeSpeakerMinLevelAttribute(callback, value, 0); - } - - public void writeSpeakerMinLevelAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), SPEAKER_MIN_LEVEL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - public void subscribeSpeakerMinLevelAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, SPEAKER_MIN_LEVEL_ATTRIBUTE_ID); @@ -61346,15 +61148,6 @@ public void onSuccess(byte[] tlv) { }, MICROPHONE_MAX_LEVEL_ATTRIBUTE_ID, true); } - public void writeMicrophoneMaxLevelAttribute(DefaultClusterCallback callback, Integer value) { - writeMicrophoneMaxLevelAttribute(callback, value, 0); - } - - public void writeMicrophoneMaxLevelAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), MICROPHONE_MAX_LEVEL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - public void subscribeMicrophoneMaxLevelAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MICROPHONE_MAX_LEVEL_ATTRIBUTE_ID); @@ -61381,15 +61174,6 @@ public void onSuccess(byte[] tlv) { }, MICROPHONE_MIN_LEVEL_ATTRIBUTE_ID, true); } - public void writeMicrophoneMinLevelAttribute(DefaultClusterCallback callback, Integer value) { - writeMicrophoneMinLevelAttribute(callback, value, 0); - } - - public void writeMicrophoneMinLevelAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), MICROPHONE_MIN_LEVEL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - public void subscribeMicrophoneMinLevelAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, MICROPHONE_MIN_LEVEL_ATTRIBUTE_ID); @@ -61451,6 +61235,15 @@ public void onSuccess(byte[] tlv) { }, IMAGE_ROTATION_ATTRIBUTE_ID, true); } + public void writeImageRotationAttribute(DefaultClusterCallback callback, Integer value) { + writeImageRotationAttribute(callback, value, 0); + } + + public void writeImageRotationAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { + BaseTLVType tlvValue = new UIntType(value); + writeAttribute(new WriteAttributesCallbackImpl(callback), IMAGE_ROTATION_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + } + public void subscribeImageRotationAttribute( IntegerAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, IMAGE_ROTATION_ATTRIBUTE_ID); @@ -61477,6 +61270,15 @@ public void onSuccess(byte[] tlv) { }, IMAGE_FLIP_HORIZONTAL_ATTRIBUTE_ID, true); } + public void writeImageFlipHorizontalAttribute(DefaultClusterCallback callback, Boolean value) { + writeImageFlipHorizontalAttribute(callback, value, 0); + } + + public void writeImageFlipHorizontalAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { + BaseTLVType tlvValue = new BooleanType(value); + writeAttribute(new WriteAttributesCallbackImpl(callback), IMAGE_FLIP_HORIZONTAL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + } + public void subscribeImageFlipHorizontalAttribute( BooleanAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, IMAGE_FLIP_HORIZONTAL_ATTRIBUTE_ID); @@ -61503,6 +61305,15 @@ public void onSuccess(byte[] tlv) { }, IMAGE_FLIP_VERTICAL_ATTRIBUTE_ID, true); } + public void writeImageFlipVerticalAttribute(DefaultClusterCallback callback, Boolean value) { + writeImageFlipVerticalAttribute(callback, value, 0); + } + + public void writeImageFlipVerticalAttribute(DefaultClusterCallback callback, Boolean value, int timedWriteTimeoutMs) { + BaseTLVType tlvValue = new BooleanType(value); + writeAttribute(new WriteAttributesCallbackImpl(callback), IMAGE_FLIP_VERTICAL_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); + } + public void subscribeImageFlipVerticalAttribute( BooleanAttributeCallback callback, int minInterval, int maxInterval) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, IMAGE_FLIP_VERTICAL_ATTRIBUTE_ID); @@ -61656,41 +61467,6 @@ public void onSuccess(byte[] tlv) { }, STATUS_LIGHT_BRIGHTNESS_ATTRIBUTE_ID, minInterval, maxInterval); } - public void readDepthSensorStatusAttribute( - IntegerAttributeCallback callback) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DEPTH_SENSOR_STATUS_ATTRIBUTE_ID); - - readAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, DEPTH_SENSOR_STATUS_ATTRIBUTE_ID, true); - } - - public void writeDepthSensorStatusAttribute(DefaultClusterCallback callback, Integer value) { - writeDepthSensorStatusAttribute(callback, value, 0); - } - - public void writeDepthSensorStatusAttribute(DefaultClusterCallback callback, Integer value, int timedWriteTimeoutMs) { - BaseTLVType tlvValue = new UIntType(value); - writeAttribute(new WriteAttributesCallbackImpl(callback), DEPTH_SENSOR_STATUS_ATTRIBUTE_ID, tlvValue, timedWriteTimeoutMs); - } - - public void subscribeDepthSensorStatusAttribute( - IntegerAttributeCallback callback, int minInterval, int maxInterval) { - ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, DEPTH_SENSOR_STATUS_ATTRIBUTE_ID); - - subscribeAttribute(new ReportCallbackImpl(callback, path) { - @Override - public void onSuccess(byte[] tlv) { - Integer value = ChipTLVValueDecoder.decodeAttributeValue(path, tlv); - callback.onSuccess(value); - } - }, DEPTH_SENSOR_STATUS_ATTRIBUTE_ID, minInterval, maxInterval); - } - public void readGeneratedCommandListAttribute( GeneratedCommandListAttributeCallback callback) { ChipAttributePath path = ChipAttributePath.newInstance(endpointId, clusterId, GENERATED_COMMAND_LIST_ATTRIBUTE_ID); diff --git a/src/controller/java/generated/java/chip/devicecontroller/ClusterIDMapping.java b/src/controller/java/generated/java/chip/devicecontroller/ClusterIDMapping.java index 354f49ed6caa5d..79e891ade9fba4 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ClusterIDMapping.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ClusterIDMapping.java @@ -17099,27 +17099,23 @@ public enum Attribute { HardPrivacyModeOn(23L), NightVision(24L), NightVisionIllum(25L), - AWBEnabled(26L), - AutoShutterSpeedEnabled(27L), - AutoISOEnabled(28L), - Viewport(29L), - SpeakerMuted(30L), - SpeakerVolumeLevel(31L), - SpeakerMaxLevel(32L), - SpeakerMinLevel(33L), - MicrophoneMuted(34L), - MicrophoneVolumeLevel(35L), - MicrophoneMaxLevel(36L), - MicrophoneMinLevel(37L), - MicrophoneAGCEnabled(38L), - ImageRotation(39L), - ImageFlipHorizontal(40L), - ImageFlipVertical(41L), - LocalVideoRecordingEnabled(42L), - LocalSnapshotRecordingEnabled(43L), - StatusLightEnabled(44L), - StatusLightBrightness(45L), - DepthSensorStatus(46L), + Viewport(26L), + SpeakerMuted(27L), + SpeakerVolumeLevel(28L), + SpeakerMaxLevel(29L), + SpeakerMinLevel(30L), + MicrophoneMuted(31L), + MicrophoneVolumeLevel(32L), + MicrophoneMaxLevel(33L), + MicrophoneMinLevel(34L), + MicrophoneAGCEnabled(35L), + ImageRotation(36L), + ImageFlipHorizontal(37L), + ImageFlipVertical(38L), + LocalVideoRecordingEnabled(39L), + LocalSnapshotRecordingEnabled(40L), + StatusLightEnabled(41L), + StatusLightBrightness(42L), GeneratedCommandList(65528L), AcceptedCommandList(65529L), EventList(65530L), @@ -17177,11 +17173,7 @@ public enum Command { SnapshotStreamAllocate(7L), SnapshotStreamDeallocate(9L), SetStreamPriorities(10L), - CaptureSnapshot(11L), - SetViewport(13L), - SetImageRotation(14L), - SetImageFlipHorizontal(15L), - SetImageFlipVertical(16L),; + CaptureSnapshot(11L),; private final long id; Command(long id) { this.id = id; @@ -17352,74 +17344,6 @@ public static CaptureSnapshotCommandField value(int id) throws NoSuchFieldError } throw new NoSuchFieldError(); } - }public enum SetViewportCommandField {Viewport(0),; - private final int id; - SetViewportCommandField(int id) { - this.id = id; - } - - public int getID() { - return id; - } - public static SetViewportCommandField value(int id) throws NoSuchFieldError { - for (SetViewportCommandField field : SetViewportCommandField.values()) { - if (field.getID() == id) { - return field; - } - } - throw new NoSuchFieldError(); - } - }public enum SetImageRotationCommandField {Angle(0),; - private final int id; - SetImageRotationCommandField(int id) { - this.id = id; - } - - public int getID() { - return id; - } - public static SetImageRotationCommandField value(int id) throws NoSuchFieldError { - for (SetImageRotationCommandField field : SetImageRotationCommandField.values()) { - if (field.getID() == id) { - return field; - } - } - throw new NoSuchFieldError(); - } - }public enum SetImageFlipHorizontalCommandField {Enabled(0),; - private final int id; - SetImageFlipHorizontalCommandField(int id) { - this.id = id; - } - - public int getID() { - return id; - } - public static SetImageFlipHorizontalCommandField value(int id) throws NoSuchFieldError { - for (SetImageFlipHorizontalCommandField field : SetImageFlipHorizontalCommandField.values()) { - if (field.getID() == id) { - return field; - } - } - throw new NoSuchFieldError(); - } - }public enum SetImageFlipVerticalCommandField {Enabled(0),; - private final int id; - SetImageFlipVerticalCommandField(int id) { - this.id = id; - } - - public int getID() { - return id; - } - public static SetImageFlipVerticalCommandField value(int id) throws NoSuchFieldError { - for (SetImageFlipVerticalCommandField field : SetImageFlipVerticalCommandField.values()) { - if (field.getID() == id) { - return field; - } - } - throw new NoSuchFieldError(); - } }@Override public String getAttributeName(long id) throws NoSuchFieldError { return Attribute.value(id).toString(); diff --git a/src/controller/java/generated/java/chip/devicecontroller/ClusterInfoMapping.java b/src/controller/java/generated/java/chip/devicecontroller/ClusterInfoMapping.java index d0e83258a32ae5..ecc943e44d4dba 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ClusterInfoMapping.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ClusterInfoMapping.java @@ -29900,72 +29900,6 @@ public Map> getCommandMap() { ); cameraAvStreamManagementClusterInteractionInfoMap.put("captureSnapshot", cameraAvStreamManagementcaptureSnapshotInteractionInfo); - Map cameraAvStreamManagementsetViewportCommandParams = new LinkedHashMap(); - - InteractionInfo cameraAvStreamManagementsetViewportInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster) - .setViewport((DefaultClusterCallback) callback - , (ChipStructs.CameraAvStreamManagementClusterViewportStruct) - commandArguments.get("viewport") - ); - }, - () -> new DelegatedDefaultClusterCallback(), - cameraAvStreamManagementsetViewportCommandParams - ); - cameraAvStreamManagementClusterInteractionInfoMap.put("setViewport", cameraAvStreamManagementsetViewportInteractionInfo); - - Map cameraAvStreamManagementsetImageRotationCommandParams = new LinkedHashMap(); - - CommandParameterInfo cameraAvStreamManagementsetImageRotationangleCommandParameterInfo = new CommandParameterInfo("angle", Integer.class, Integer.class); - cameraAvStreamManagementsetImageRotationCommandParams.put("angle",cameraAvStreamManagementsetImageRotationangleCommandParameterInfo); - InteractionInfo cameraAvStreamManagementsetImageRotationInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster) - .setImageRotation((DefaultClusterCallback) callback - , (Integer) - commandArguments.get("angle") - ); - }, - () -> new DelegatedDefaultClusterCallback(), - cameraAvStreamManagementsetImageRotationCommandParams - ); - cameraAvStreamManagementClusterInteractionInfoMap.put("setImageRotation", cameraAvStreamManagementsetImageRotationInteractionInfo); - - Map cameraAvStreamManagementsetImageFlipHorizontalCommandParams = new LinkedHashMap(); - - CommandParameterInfo cameraAvStreamManagementsetImageFlipHorizontalenabledCommandParameterInfo = new CommandParameterInfo("enabled", Boolean.class, Boolean.class); - cameraAvStreamManagementsetImageFlipHorizontalCommandParams.put("enabled",cameraAvStreamManagementsetImageFlipHorizontalenabledCommandParameterInfo); - InteractionInfo cameraAvStreamManagementsetImageFlipHorizontalInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster) - .setImageFlipHorizontal((DefaultClusterCallback) callback - , (Boolean) - commandArguments.get("enabled") - ); - }, - () -> new DelegatedDefaultClusterCallback(), - cameraAvStreamManagementsetImageFlipHorizontalCommandParams - ); - cameraAvStreamManagementClusterInteractionInfoMap.put("setImageFlipHorizontal", cameraAvStreamManagementsetImageFlipHorizontalInteractionInfo); - - Map cameraAvStreamManagementsetImageFlipVerticalCommandParams = new LinkedHashMap(); - - CommandParameterInfo cameraAvStreamManagementsetImageFlipVerticalenabledCommandParameterInfo = new CommandParameterInfo("enabled", Boolean.class, Boolean.class); - cameraAvStreamManagementsetImageFlipVerticalCommandParams.put("enabled",cameraAvStreamManagementsetImageFlipVerticalenabledCommandParameterInfo); - InteractionInfo cameraAvStreamManagementsetImageFlipVerticalInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster) - .setImageFlipVertical((DefaultClusterCallback) callback - , (Boolean) - commandArguments.get("enabled") - ); - }, - () -> new DelegatedDefaultClusterCallback(), - cameraAvStreamManagementsetImageFlipVerticalCommandParams - ); - cameraAvStreamManagementClusterInteractionInfoMap.put("setImageFlipVertical", cameraAvStreamManagementsetImageFlipVerticalInteractionInfo); - commandMap.put("cameraAvStreamManagement", cameraAvStreamManagementClusterInteractionInfoMap); Map webRTCTransportProviderClusterInteractionInfoMap = new LinkedHashMap<>(); diff --git a/src/controller/java/generated/java/chip/devicecontroller/ClusterReadMapping.java b/src/controller/java/generated/java/chip/devicecontroller/ClusterReadMapping.java index 843114b4374f58..f9f500b6cfac4d 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ClusterReadMapping.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ClusterReadMapping.java @@ -18527,39 +18527,6 @@ private static Map readCameraAvStreamManagementInteract readCameraAvStreamManagementNightVisionIllumCommandParams ); result.put("readNightVisionIllumAttribute", readCameraAvStreamManagementNightVisionIllumAttributeInteractionInfo); - Map readCameraAvStreamManagementAWBEnabledCommandParams = new LinkedHashMap(); - InteractionInfo readCameraAvStreamManagementAWBEnabledAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).readAWBEnabledAttribute( - (ChipClusters.BooleanAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedBooleanAttributeCallback(), - readCameraAvStreamManagementAWBEnabledCommandParams - ); - result.put("readAWBEnabledAttribute", readCameraAvStreamManagementAWBEnabledAttributeInteractionInfo); - Map readCameraAvStreamManagementAutoShutterSpeedEnabledCommandParams = new LinkedHashMap(); - InteractionInfo readCameraAvStreamManagementAutoShutterSpeedEnabledAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).readAutoShutterSpeedEnabledAttribute( - (ChipClusters.BooleanAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedBooleanAttributeCallback(), - readCameraAvStreamManagementAutoShutterSpeedEnabledCommandParams - ); - result.put("readAutoShutterSpeedEnabledAttribute", readCameraAvStreamManagementAutoShutterSpeedEnabledAttributeInteractionInfo); - Map readCameraAvStreamManagementAutoISOEnabledCommandParams = new LinkedHashMap(); - InteractionInfo readCameraAvStreamManagementAutoISOEnabledAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).readAutoISOEnabledAttribute( - (ChipClusters.BooleanAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedBooleanAttributeCallback(), - readCameraAvStreamManagementAutoISOEnabledCommandParams - ); - result.put("readAutoISOEnabledAttribute", readCameraAvStreamManagementAutoISOEnabledAttributeInteractionInfo); Map readCameraAvStreamManagementSpeakerMutedCommandParams = new LinkedHashMap(); InteractionInfo readCameraAvStreamManagementSpeakerMutedAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { @@ -18736,17 +18703,6 @@ private static Map readCameraAvStreamManagementInteract readCameraAvStreamManagementStatusLightBrightnessCommandParams ); result.put("readStatusLightBrightnessAttribute", readCameraAvStreamManagementStatusLightBrightnessAttributeInteractionInfo); - Map readCameraAvStreamManagementDepthSensorStatusCommandParams = new LinkedHashMap(); - InteractionInfo readCameraAvStreamManagementDepthSensorStatusAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).readDepthSensorStatusAttribute( - (ChipClusters.IntegerAttributeCallback) callback - ); - }, - () -> new ClusterInfoMapping.DelegatedIntegerAttributeCallback(), - readCameraAvStreamManagementDepthSensorStatusCommandParams - ); - result.put("readDepthSensorStatusAttribute", readCameraAvStreamManagementDepthSensorStatusAttributeInteractionInfo); Map readCameraAvStreamManagementGeneratedCommandListCommandParams = new LinkedHashMap(); InteractionInfo readCameraAvStreamManagementGeneratedCommandListAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { diff --git a/src/controller/java/generated/java/chip/devicecontroller/ClusterWriteMapping.java b/src/controller/java/generated/java/chip/devicecontroller/ClusterWriteMapping.java index 725fd0baeccf65..68d1f3792157cc 100644 --- a/src/controller/java/generated/java/chip/devicecontroller/ClusterWriteMapping.java +++ b/src/controller/java/generated/java/chip/devicecontroller/ClusterWriteMapping.java @@ -3475,72 +3475,6 @@ public Map> getWriteAttributeMap() { writeCameraAvStreamManagementNightVisionIllumCommandParams ); writeCameraAvStreamManagementInteractionInfo.put("writeNightVisionIllumAttribute", writeCameraAvStreamManagementNightVisionIllumAttributeInteractionInfo); - Map writeCameraAvStreamManagementAWBEnabledCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementAWBEnabledCommandParameterInfo = - new CommandParameterInfo( - "value", - Boolean.class, - Boolean.class - ); - writeCameraAvStreamManagementAWBEnabledCommandParams.put( - "value", - cameraAvStreamManagementAWBEnabledCommandParameterInfo - ); - InteractionInfo writeCameraAvStreamManagementAWBEnabledAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeAWBEnabledAttribute( - (DefaultClusterCallback) callback, - (Boolean) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementAWBEnabledCommandParams - ); - writeCameraAvStreamManagementInteractionInfo.put("writeAWBEnabledAttribute", writeCameraAvStreamManagementAWBEnabledAttributeInteractionInfo); - Map writeCameraAvStreamManagementAutoShutterSpeedEnabledCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementautoShutterSpeedEnabledCommandParameterInfo = - new CommandParameterInfo( - "value", - Boolean.class, - Boolean.class - ); - writeCameraAvStreamManagementAutoShutterSpeedEnabledCommandParams.put( - "value", - cameraAvStreamManagementautoShutterSpeedEnabledCommandParameterInfo - ); - InteractionInfo writeCameraAvStreamManagementAutoShutterSpeedEnabledAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeAutoShutterSpeedEnabledAttribute( - (DefaultClusterCallback) callback, - (Boolean) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementAutoShutterSpeedEnabledCommandParams - ); - writeCameraAvStreamManagementInteractionInfo.put("writeAutoShutterSpeedEnabledAttribute", writeCameraAvStreamManagementAutoShutterSpeedEnabledAttributeInteractionInfo); - Map writeCameraAvStreamManagementAutoISOEnabledCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementautoISOEnabledCommandParameterInfo = - new CommandParameterInfo( - "value", - Boolean.class, - Boolean.class - ); - writeCameraAvStreamManagementAutoISOEnabledCommandParams.put( - "value", - cameraAvStreamManagementautoISOEnabledCommandParameterInfo - ); - InteractionInfo writeCameraAvStreamManagementAutoISOEnabledAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeAutoISOEnabledAttribute( - (DefaultClusterCallback) callback, - (Boolean) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementAutoISOEnabledCommandParams - ); - writeCameraAvStreamManagementInteractionInfo.put("writeAutoISOEnabledAttribute", writeCameraAvStreamManagementAutoISOEnabledAttributeInteractionInfo); Map writeCameraAvStreamManagementSpeakerMutedCommandParams = new LinkedHashMap(); CommandParameterInfo cameraAvStreamManagementspeakerMutedCommandParameterInfo = new CommandParameterInfo( @@ -3585,50 +3519,6 @@ public Map> getWriteAttributeMap() { writeCameraAvStreamManagementSpeakerVolumeLevelCommandParams ); writeCameraAvStreamManagementInteractionInfo.put("writeSpeakerVolumeLevelAttribute", writeCameraAvStreamManagementSpeakerVolumeLevelAttributeInteractionInfo); - Map writeCameraAvStreamManagementSpeakerMaxLevelCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementspeakerMaxLevelCommandParameterInfo = - new CommandParameterInfo( - "value", - Integer.class, - Integer.class - ); - writeCameraAvStreamManagementSpeakerMaxLevelCommandParams.put( - "value", - cameraAvStreamManagementspeakerMaxLevelCommandParameterInfo - ); - InteractionInfo writeCameraAvStreamManagementSpeakerMaxLevelAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeSpeakerMaxLevelAttribute( - (DefaultClusterCallback) callback, - (Integer) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementSpeakerMaxLevelCommandParams - ); - writeCameraAvStreamManagementInteractionInfo.put("writeSpeakerMaxLevelAttribute", writeCameraAvStreamManagementSpeakerMaxLevelAttributeInteractionInfo); - Map writeCameraAvStreamManagementSpeakerMinLevelCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementspeakerMinLevelCommandParameterInfo = - new CommandParameterInfo( - "value", - Integer.class, - Integer.class - ); - writeCameraAvStreamManagementSpeakerMinLevelCommandParams.put( - "value", - cameraAvStreamManagementspeakerMinLevelCommandParameterInfo - ); - InteractionInfo writeCameraAvStreamManagementSpeakerMinLevelAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeSpeakerMinLevelAttribute( - (DefaultClusterCallback) callback, - (Integer) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementSpeakerMinLevelCommandParams - ); - writeCameraAvStreamManagementInteractionInfo.put("writeSpeakerMinLevelAttribute", writeCameraAvStreamManagementSpeakerMinLevelAttributeInteractionInfo); Map writeCameraAvStreamManagementMicrophoneMutedCommandParams = new LinkedHashMap(); CommandParameterInfo cameraAvStreamManagementmicrophoneMutedCommandParameterInfo = new CommandParameterInfo( @@ -3673,72 +3563,94 @@ public Map> getWriteAttributeMap() { writeCameraAvStreamManagementMicrophoneVolumeLevelCommandParams ); writeCameraAvStreamManagementInteractionInfo.put("writeMicrophoneVolumeLevelAttribute", writeCameraAvStreamManagementMicrophoneVolumeLevelAttributeInteractionInfo); - Map writeCameraAvStreamManagementMicrophoneMaxLevelCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementmicrophoneMaxLevelCommandParameterInfo = + Map writeCameraAvStreamManagementMicrophoneAGCEnabledCommandParams = new LinkedHashMap(); + CommandParameterInfo cameraAvStreamManagementmicrophoneAGCEnabledCommandParameterInfo = new CommandParameterInfo( "value", - Integer.class, - Integer.class + Boolean.class, + Boolean.class ); - writeCameraAvStreamManagementMicrophoneMaxLevelCommandParams.put( + writeCameraAvStreamManagementMicrophoneAGCEnabledCommandParams.put( "value", - cameraAvStreamManagementmicrophoneMaxLevelCommandParameterInfo + cameraAvStreamManagementmicrophoneAGCEnabledCommandParameterInfo ); - InteractionInfo writeCameraAvStreamManagementMicrophoneMaxLevelAttributeInteractionInfo = new InteractionInfo( + InteractionInfo writeCameraAvStreamManagementMicrophoneAGCEnabledAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeMicrophoneMaxLevelAttribute( + ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeMicrophoneAGCEnabledAttribute( (DefaultClusterCallback) callback, - (Integer) commandArguments.get("value") + (Boolean) commandArguments.get("value") ); }, () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementMicrophoneMaxLevelCommandParams + writeCameraAvStreamManagementMicrophoneAGCEnabledCommandParams ); - writeCameraAvStreamManagementInteractionInfo.put("writeMicrophoneMaxLevelAttribute", writeCameraAvStreamManagementMicrophoneMaxLevelAttributeInteractionInfo); - Map writeCameraAvStreamManagementMicrophoneMinLevelCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementmicrophoneMinLevelCommandParameterInfo = + writeCameraAvStreamManagementInteractionInfo.put("writeMicrophoneAGCEnabledAttribute", writeCameraAvStreamManagementMicrophoneAGCEnabledAttributeInteractionInfo); + Map writeCameraAvStreamManagementImageRotationCommandParams = new LinkedHashMap(); + CommandParameterInfo cameraAvStreamManagementimageRotationCommandParameterInfo = new CommandParameterInfo( "value", Integer.class, Integer.class ); - writeCameraAvStreamManagementMicrophoneMinLevelCommandParams.put( + writeCameraAvStreamManagementImageRotationCommandParams.put( "value", - cameraAvStreamManagementmicrophoneMinLevelCommandParameterInfo + cameraAvStreamManagementimageRotationCommandParameterInfo ); - InteractionInfo writeCameraAvStreamManagementMicrophoneMinLevelAttributeInteractionInfo = new InteractionInfo( + InteractionInfo writeCameraAvStreamManagementImageRotationAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeMicrophoneMinLevelAttribute( + ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeImageRotationAttribute( (DefaultClusterCallback) callback, (Integer) commandArguments.get("value") ); }, () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementMicrophoneMinLevelCommandParams + writeCameraAvStreamManagementImageRotationCommandParams ); - writeCameraAvStreamManagementInteractionInfo.put("writeMicrophoneMinLevelAttribute", writeCameraAvStreamManagementMicrophoneMinLevelAttributeInteractionInfo); - Map writeCameraAvStreamManagementMicrophoneAGCEnabledCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementmicrophoneAGCEnabledCommandParameterInfo = + writeCameraAvStreamManagementInteractionInfo.put("writeImageRotationAttribute", writeCameraAvStreamManagementImageRotationAttributeInteractionInfo); + Map writeCameraAvStreamManagementImageFlipHorizontalCommandParams = new LinkedHashMap(); + CommandParameterInfo cameraAvStreamManagementimageFlipHorizontalCommandParameterInfo = new CommandParameterInfo( "value", Boolean.class, Boolean.class ); - writeCameraAvStreamManagementMicrophoneAGCEnabledCommandParams.put( + writeCameraAvStreamManagementImageFlipHorizontalCommandParams.put( "value", - cameraAvStreamManagementmicrophoneAGCEnabledCommandParameterInfo + cameraAvStreamManagementimageFlipHorizontalCommandParameterInfo ); - InteractionInfo writeCameraAvStreamManagementMicrophoneAGCEnabledAttributeInteractionInfo = new InteractionInfo( + InteractionInfo writeCameraAvStreamManagementImageFlipHorizontalAttributeInteractionInfo = new InteractionInfo( (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeMicrophoneAGCEnabledAttribute( + ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeImageFlipHorizontalAttribute( (DefaultClusterCallback) callback, (Boolean) commandArguments.get("value") ); }, () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementMicrophoneAGCEnabledCommandParams + writeCameraAvStreamManagementImageFlipHorizontalCommandParams ); - writeCameraAvStreamManagementInteractionInfo.put("writeMicrophoneAGCEnabledAttribute", writeCameraAvStreamManagementMicrophoneAGCEnabledAttributeInteractionInfo); + writeCameraAvStreamManagementInteractionInfo.put("writeImageFlipHorizontalAttribute", writeCameraAvStreamManagementImageFlipHorizontalAttributeInteractionInfo); + Map writeCameraAvStreamManagementImageFlipVerticalCommandParams = new LinkedHashMap(); + CommandParameterInfo cameraAvStreamManagementimageFlipVerticalCommandParameterInfo = + new CommandParameterInfo( + "value", + Boolean.class, + Boolean.class + ); + writeCameraAvStreamManagementImageFlipVerticalCommandParams.put( + "value", + cameraAvStreamManagementimageFlipVerticalCommandParameterInfo + ); + InteractionInfo writeCameraAvStreamManagementImageFlipVerticalAttributeInteractionInfo = new InteractionInfo( + (cluster, callback, commandArguments) -> { + ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeImageFlipVerticalAttribute( + (DefaultClusterCallback) callback, + (Boolean) commandArguments.get("value") + ); + }, + () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), + writeCameraAvStreamManagementImageFlipVerticalCommandParams + ); + writeCameraAvStreamManagementInteractionInfo.put("writeImageFlipVerticalAttribute", writeCameraAvStreamManagementImageFlipVerticalAttributeInteractionInfo); Map writeCameraAvStreamManagementLocalVideoRecordingEnabledCommandParams = new LinkedHashMap(); CommandParameterInfo cameraAvStreamManagementlocalVideoRecordingEnabledCommandParameterInfo = new CommandParameterInfo( @@ -3827,28 +3739,6 @@ public Map> getWriteAttributeMap() { writeCameraAvStreamManagementStatusLightBrightnessCommandParams ); writeCameraAvStreamManagementInteractionInfo.put("writeStatusLightBrightnessAttribute", writeCameraAvStreamManagementStatusLightBrightnessAttributeInteractionInfo); - Map writeCameraAvStreamManagementDepthSensorStatusCommandParams = new LinkedHashMap(); - CommandParameterInfo cameraAvStreamManagementdepthSensorStatusCommandParameterInfo = - new CommandParameterInfo( - "value", - Integer.class, - Integer.class - ); - writeCameraAvStreamManagementDepthSensorStatusCommandParams.put( - "value", - cameraAvStreamManagementdepthSensorStatusCommandParameterInfo - ); - InteractionInfo writeCameraAvStreamManagementDepthSensorStatusAttributeInteractionInfo = new InteractionInfo( - (cluster, callback, commandArguments) -> { - ((ChipClusters.CameraAvStreamManagementCluster) cluster).writeDepthSensorStatusAttribute( - (DefaultClusterCallback) callback, - (Integer) commandArguments.get("value") - ); - }, - () -> new ClusterInfoMapping.DelegatedDefaultClusterCallback(), - writeCameraAvStreamManagementDepthSensorStatusCommandParams - ); - writeCameraAvStreamManagementInteractionInfo.put("writeDepthSensorStatusAttribute", writeCameraAvStreamManagementDepthSensorStatusAttributeInteractionInfo); writeAttributeMap.put("cameraAvStreamManagement", writeCameraAvStreamManagementInteractionInfo); Map writeWebRTCTransportProviderInteractionInfo = new LinkedHashMap<>(); writeAttributeMap.put("webRTCTransportProvider", writeWebRTCTransportProviderInteractionInfo); diff --git a/src/controller/java/generated/java/matter/controller/cluster/clusters/CameraAvStreamManagementCluster.kt b/src/controller/java/generated/java/matter/controller/cluster/clusters/CameraAvStreamManagementCluster.kt index c0993403079dbf..9a8e562d2fda11 100644 --- a/src/controller/java/generated/java/matter/controller/cluster/clusters/CameraAvStreamManagementCluster.kt +++ b/src/controller/java/generated/java/matter/controller/cluster/clusters/CameraAvStreamManagementCluster.kt @@ -656,93 +656,6 @@ class CameraAvStreamManagementCluster( logger.log(Level.FINE, "Invoke command succeeded: ${response}") } - suspend fun setViewport( - viewport: CameraAvStreamManagementClusterViewportStruct, - timedInvokeTimeout: Duration? = null, - ) { - val commandId: UInt = 13u - - val tlvWriter = TlvWriter() - tlvWriter.startStructure(AnonymousTag) - - val TAG_VIEWPORT_REQ: Int = 0 - viewport.toTlv(ContextSpecificTag(TAG_VIEWPORT_REQ), tlvWriter) - tlvWriter.endStructure() - - val request: InvokeRequest = - InvokeRequest( - CommandPath(endpointId, clusterId = CLUSTER_ID, commandId), - tlvPayload = tlvWriter.getEncoded(), - timedRequest = timedInvokeTimeout, - ) - - val response: InvokeResponse = controller.invoke(request) - logger.log(Level.FINE, "Invoke command succeeded: ${response}") - } - - suspend fun setImageRotation(angle: UShort, timedInvokeTimeout: Duration? = null) { - val commandId: UInt = 14u - - val tlvWriter = TlvWriter() - tlvWriter.startStructure(AnonymousTag) - - val TAG_ANGLE_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ANGLE_REQ), angle) - tlvWriter.endStructure() - - val request: InvokeRequest = - InvokeRequest( - CommandPath(endpointId, clusterId = CLUSTER_ID, commandId), - tlvPayload = tlvWriter.getEncoded(), - timedRequest = timedInvokeTimeout, - ) - - val response: InvokeResponse = controller.invoke(request) - logger.log(Level.FINE, "Invoke command succeeded: ${response}") - } - - suspend fun setImageFlipHorizontal(enabled: Boolean, timedInvokeTimeout: Duration? = null) { - val commandId: UInt = 15u - - val tlvWriter = TlvWriter() - tlvWriter.startStructure(AnonymousTag) - - val TAG_ENABLED_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ENABLED_REQ), enabled) - tlvWriter.endStructure() - - val request: InvokeRequest = - InvokeRequest( - CommandPath(endpointId, clusterId = CLUSTER_ID, commandId), - tlvPayload = tlvWriter.getEncoded(), - timedRequest = timedInvokeTimeout, - ) - - val response: InvokeResponse = controller.invoke(request) - logger.log(Level.FINE, "Invoke command succeeded: ${response}") - } - - suspend fun setImageFlipVertical(enabled: Boolean, timedInvokeTimeout: Duration? = null) { - val commandId: UInt = 16u - - val tlvWriter = TlvWriter() - tlvWriter.startStructure(AnonymousTag) - - val TAG_ENABLED_REQ: Int = 0 - tlvWriter.put(ContextSpecificTag(TAG_ENABLED_REQ), enabled) - tlvWriter.endStructure() - - val request: InvokeRequest = - InvokeRequest( - CommandPath(endpointId, clusterId = CLUSTER_ID, commandId), - tlvPayload = tlvWriter.getEncoded(), - timedRequest = timedInvokeTimeout, - ) - - val response: InvokeResponse = controller.invoke(request) - logger.log(Level.FINE, "Invoke command succeeded: ${response}") - } - suspend fun readMaxConcurrentVideoEncodersAttribute(): UByte? { val ATTRIBUTE_ID: UInt = 0u @@ -3543,7 +3456,7 @@ class CameraAvStreamManagementCluster( } } - suspend fun readAWBEnabledAttribute(): Boolean? { + suspend fun readViewportAttribute(): ViewportAttribute { val ATTRIBUTE_ID: UInt = 26u val attributePath = @@ -3565,25 +3478,28 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Awbenabled attribute not found in response" } + requireNotNull(attributeData) { "Viewport attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = + val decodedValue: CameraAvStreamManagementClusterViewportStruct? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) + CameraAvStreamManagementClusterViewportStruct.fromTlv(AnonymousTag, tlvReader) } else { null } - return decodedValue + return ViewportAttribute(decodedValue) } - suspend fun writeAWBEnabledAttribute(value: Boolean, timedWriteTimeout: Duration? = null) { + suspend fun writeViewportAttribute( + value: CameraAvStreamManagementClusterViewportStruct, + timedWriteTimeout: Duration? = null, + ) { val ATTRIBUTE_ID: UInt = 26u val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) + value.toTlv(AnonymousTag, tlvWriter) val writeRequests: WriteRequests = WriteRequests( @@ -3619,10 +3535,10 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeAWBEnabledAttribute( + suspend fun subscribeViewportAttribute( minInterval: Int, maxInterval: Int, - ): Flow { + ): Flow { val ATTRIBUTE_ID: UInt = 26u val attributePaths = listOf( @@ -3641,7 +3557,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - BooleanSubscriptionState.Error( + ViewportAttributeSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -3654,27 +3570,27 @@ class CameraAvStreamManagementCluster( .filterIsInstance() .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Awbenabled attribute not found in Node State update" } + requireNotNull(attributeData) { "Viewport attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = + val decodedValue: CameraAvStreamManagementClusterViewportStruct? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) + CameraAvStreamManagementClusterViewportStruct.fromTlv(AnonymousTag, tlvReader) } else { null } - decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } + decodedValue?.let { emit(ViewportAttributeSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(BooleanSubscriptionState.SubscriptionEstablished) + emit(ViewportAttributeSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readAutoShutterSpeedEnabledAttribute(): Boolean? { + suspend fun readSpeakerMutedAttribute(): Boolean? { val ATTRIBUTE_ID: UInt = 27u val attributePath = @@ -3696,7 +3612,7 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Autoshutterspeedenabled attribute not found in response" } + requireNotNull(attributeData) { "Speakermuted attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -3710,10 +3626,7 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeAutoShutterSpeedEnabledAttribute( - value: Boolean, - timedWriteTimeout: Duration? = null, - ) { + suspend fun writeSpeakerMutedAttribute(value: Boolean, timedWriteTimeout: Duration? = null) { val ATTRIBUTE_ID: UInt = 27u val tlvWriter = TlvWriter() @@ -3753,7 +3666,7 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeAutoShutterSpeedEnabledAttribute( + suspend fun subscribeSpeakerMutedAttribute( minInterval: Int, maxInterval: Int, ): Flow { @@ -3788,9 +3701,7 @@ class CameraAvStreamManagementCluster( .filterIsInstance() .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { - "Autoshutterspeedenabled attribute not found in Node State update" - } + requireNotNull(attributeData) { "Speakermuted attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -3810,7 +3721,7 @@ class CameraAvStreamManagementCluster( } } - suspend fun readAutoISOEnabledAttribute(): Boolean? { + suspend fun readSpeakerVolumeLevelAttribute(): UByte? { val ATTRIBUTE_ID: UInt = 28u val attributePath = @@ -3832,13 +3743,13 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Autoisoenabled attribute not found in response" } + requireNotNull(attributeData) { "Speakervolumelevel attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = + val decodedValue: UByte? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) + tlvReader.getUByte(AnonymousTag) } else { null } @@ -3846,7 +3757,7 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeAutoISOEnabledAttribute(value: Boolean, timedWriteTimeout: Duration? = null) { + suspend fun writeSpeakerVolumeLevelAttribute(value: UByte, timedWriteTimeout: Duration? = null) { val ATTRIBUTE_ID: UInt = 28u val tlvWriter = TlvWriter() @@ -3886,10 +3797,10 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeAutoISOEnabledAttribute( + suspend fun subscribeSpeakerVolumeLevelAttribute( minInterval: Int, maxInterval: Int, - ): Flow { + ): Flow { val ATTRIBUTE_ID: UInt = 28u val attributePaths = listOf( @@ -3908,7 +3819,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - BooleanSubscriptionState.Error( + UByteSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -3922,28 +3833,28 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Autoisoenabled attribute not found in Node State update" + "Speakervolumelevel attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = + val decodedValue: UByte? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) + tlvReader.getUByte(AnonymousTag) } else { null } - decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } + decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(BooleanSubscriptionState.SubscriptionEstablished) + emit(UByteSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readViewportAttribute(): ViewportAttribute { + suspend fun readSpeakerMaxLevelAttribute(): UByte? { val ATTRIBUTE_ID: UInt = 29u val attributePath = @@ -3965,24 +3876,24 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Viewport attribute not found in response" } + requireNotNull(attributeData) { "Speakermaxlevel attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: CameraAvStreamManagementClusterViewportStruct? = + val decodedValue: UByte? = if (tlvReader.isNextTag(AnonymousTag)) { - CameraAvStreamManagementClusterViewportStruct.fromTlv(AnonymousTag, tlvReader) + tlvReader.getUByte(AnonymousTag) } else { null } - return ViewportAttribute(decodedValue) + return decodedValue } - suspend fun subscribeViewportAttribute( + suspend fun subscribeSpeakerMaxLevelAttribute( minInterval: Int, maxInterval: Int, - ): Flow { + ): Flow { val ATTRIBUTE_ID: UInt = 29u val attributePaths = listOf( @@ -4001,7 +3912,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - ViewportAttributeSubscriptionState.Error( + UByteSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -4014,27 +3925,29 @@ class CameraAvStreamManagementCluster( .filterIsInstance() .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Viewport attribute not found in Node State update" } + requireNotNull(attributeData) { + "Speakermaxlevel attribute not found in Node State update" + } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: CameraAvStreamManagementClusterViewportStruct? = + val decodedValue: UByte? = if (tlvReader.isNextTag(AnonymousTag)) { - CameraAvStreamManagementClusterViewportStruct.fromTlv(AnonymousTag, tlvReader) + tlvReader.getUByte(AnonymousTag) } else { null } - decodedValue?.let { emit(ViewportAttributeSubscriptionState.Success(it)) } + decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(ViewportAttributeSubscriptionState.SubscriptionEstablished) + emit(UByteSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readSpeakerMutedAttribute(): Boolean? { + suspend fun readSpeakerMinLevelAttribute(): UByte? { val ATTRIBUTE_ID: UInt = 30u val attributePath = @@ -4056,13 +3969,13 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Speakermuted attribute not found in response" } + requireNotNull(attributeData) { "Speakerminlevel attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = + val decodedValue: UByte? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) + tlvReader.getUByte(AnonymousTag) } else { null } @@ -4070,50 +3983,10 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeSpeakerMutedAttribute(value: Boolean, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 30u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - - suspend fun subscribeSpeakerMutedAttribute( + suspend fun subscribeSpeakerMinLevelAttribute( minInterval: Int, maxInterval: Int, - ): Flow { + ): Flow { val ATTRIBUTE_ID: UInt = 30u val attributePaths = listOf( @@ -4132,7 +4005,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - BooleanSubscriptionState.Error( + UByteSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -4145,27 +4018,29 @@ class CameraAvStreamManagementCluster( .filterIsInstance() .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Speakermuted attribute not found in Node State update" } + requireNotNull(attributeData) { + "Speakerminlevel attribute not found in Node State update" + } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = + val decodedValue: UByte? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) + tlvReader.getUByte(AnonymousTag) } else { null } - decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } + decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(BooleanSubscriptionState.SubscriptionEstablished) + emit(UByteSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readSpeakerVolumeLevelAttribute(): UByte? { + suspend fun readMicrophoneMutedAttribute(): Boolean? { val ATTRIBUTE_ID: UInt = 31u val attributePath = @@ -4187,13 +4062,13 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Speakervolumelevel attribute not found in response" } + requireNotNull(attributeData) { "Microphonemuted attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = + val decodedValue: Boolean? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) + tlvReader.getBoolean(AnonymousTag) } else { null } @@ -4201,7 +4076,7 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeSpeakerVolumeLevelAttribute(value: UByte, timedWriteTimeout: Duration? = null) { + suspend fun writeMicrophoneMutedAttribute(value: Boolean, timedWriteTimeout: Duration? = null) { val ATTRIBUTE_ID: UInt = 31u val tlvWriter = TlvWriter() @@ -4241,10 +4116,10 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeSpeakerVolumeLevelAttribute( + suspend fun subscribeMicrophoneMutedAttribute( minInterval: Int, maxInterval: Int, - ): Flow { + ): Flow { val ATTRIBUTE_ID: UInt = 31u val attributePaths = listOf( @@ -4263,7 +4138,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - UByteSubscriptionState.Error( + BooleanSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -4277,28 +4152,28 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Speakervolumelevel attribute not found in Node State update" + "Microphonemuted attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = + val decodedValue: Boolean? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) + tlvReader.getBoolean(AnonymousTag) } else { null } - decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } + decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(UByteSubscriptionState.SubscriptionEstablished) + emit(BooleanSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readSpeakerMaxLevelAttribute(): UByte? { + suspend fun readMicrophoneVolumeLevelAttribute(): UByte? { val ATTRIBUTE_ID: UInt = 32u val attributePath = @@ -4320,7 +4195,7 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Speakermaxlevel attribute not found in response" } + requireNotNull(attributeData) { "Microphonevolumelevel attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -4334,7 +4209,10 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeSpeakerMaxLevelAttribute(value: UByte, timedWriteTimeout: Duration? = null) { + suspend fun writeMicrophoneVolumeLevelAttribute( + value: UByte, + timedWriteTimeout: Duration? = null, + ) { val ATTRIBUTE_ID: UInt = 32u val tlvWriter = TlvWriter() @@ -4374,7 +4252,7 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeSpeakerMaxLevelAttribute( + suspend fun subscribeMicrophoneVolumeLevelAttribute( minInterval: Int, maxInterval: Int, ): Flow { @@ -4392,408 +4270,6 @@ class CameraAvStreamManagementCluster( maxInterval = Duration.ofSeconds(maxInterval.toLong()), ) - return controller.subscribe(subscribeRequest).transform { subscriptionState -> - when (subscriptionState) { - is SubscriptionState.SubscriptionErrorNotification -> { - emit( - UByteSubscriptionState.Error( - Exception( - "Subscription terminated with error code: ${subscriptionState.terminationCause}" - ) - ) - ) - } - is SubscriptionState.NodeStateUpdate -> { - val attributeData = - subscriptionState.updateState.successes - .filterIsInstance() - .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - - requireNotNull(attributeData) { - "Speakermaxlevel attribute not found in Node State update" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) - } else { - null - } - - decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } - } - SubscriptionState.SubscriptionEstablished -> { - emit(UByteSubscriptionState.SubscriptionEstablished) - } - } - } - } - - suspend fun readSpeakerMinLevelAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 33u - - val attributePath = - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - - val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath)) - - val response = controller.read(readRequest) - - if (response.successes.isEmpty()) { - logger.log(Level.WARNING, "Read command failed") - throw IllegalStateException("Read command failed with failures: ${response.failures}") - } - - logger.log(Level.FINE, "Read command succeeded") - - val attributeData = - response.successes.filterIsInstance().firstOrNull { - it.path.attributeId == ATTRIBUTE_ID - } - - requireNotNull(attributeData) { "Speakerminlevel attribute not found in response" } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) - } else { - null - } - - return decodedValue - } - - suspend fun writeSpeakerMinLevelAttribute(value: UByte, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 33u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - - suspend fun subscribeSpeakerMinLevelAttribute( - minInterval: Int, - maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 33u - val attributePaths = - listOf( - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - ) - - val subscribeRequest: SubscribeRequest = - SubscribeRequest( - eventPaths = emptyList(), - attributePaths = attributePaths, - minInterval = Duration.ofSeconds(minInterval.toLong()), - maxInterval = Duration.ofSeconds(maxInterval.toLong()), - ) - - return controller.subscribe(subscribeRequest).transform { subscriptionState -> - when (subscriptionState) { - is SubscriptionState.SubscriptionErrorNotification -> { - emit( - UByteSubscriptionState.Error( - Exception( - "Subscription terminated with error code: ${subscriptionState.terminationCause}" - ) - ) - ) - } - is SubscriptionState.NodeStateUpdate -> { - val attributeData = - subscriptionState.updateState.successes - .filterIsInstance() - .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - - requireNotNull(attributeData) { - "Speakerminlevel attribute not found in Node State update" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) - } else { - null - } - - decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } - } - SubscriptionState.SubscriptionEstablished -> { - emit(UByteSubscriptionState.SubscriptionEstablished) - } - } - } - } - - suspend fun readMicrophoneMutedAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 34u - - val attributePath = - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - - val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath)) - - val response = controller.read(readRequest) - - if (response.successes.isEmpty()) { - logger.log(Level.WARNING, "Read command failed") - throw IllegalStateException("Read command failed with failures: ${response.failures}") - } - - logger.log(Level.FINE, "Read command succeeded") - - val attributeData = - response.successes.filterIsInstance().firstOrNull { - it.path.attributeId == ATTRIBUTE_ID - } - - requireNotNull(attributeData) { "Microphonemuted attribute not found in response" } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) - } else { - null - } - - return decodedValue - } - - suspend fun writeMicrophoneMutedAttribute(value: Boolean, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 34u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - - suspend fun subscribeMicrophoneMutedAttribute( - minInterval: Int, - maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 34u - val attributePaths = - listOf( - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - ) - - val subscribeRequest: SubscribeRequest = - SubscribeRequest( - eventPaths = emptyList(), - attributePaths = attributePaths, - minInterval = Duration.ofSeconds(minInterval.toLong()), - maxInterval = Duration.ofSeconds(maxInterval.toLong()), - ) - - return controller.subscribe(subscribeRequest).transform { subscriptionState -> - when (subscriptionState) { - is SubscriptionState.SubscriptionErrorNotification -> { - emit( - BooleanSubscriptionState.Error( - Exception( - "Subscription terminated with error code: ${subscriptionState.terminationCause}" - ) - ) - ) - } - is SubscriptionState.NodeStateUpdate -> { - val attributeData = - subscriptionState.updateState.successes - .filterIsInstance() - .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - - requireNotNull(attributeData) { - "Microphonemuted attribute not found in Node State update" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) - } else { - null - } - - decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } - } - SubscriptionState.SubscriptionEstablished -> { - emit(BooleanSubscriptionState.SubscriptionEstablished) - } - } - } - } - - suspend fun readMicrophoneVolumeLevelAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 35u - - val attributePath = - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - - val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath)) - - val response = controller.read(readRequest) - - if (response.successes.isEmpty()) { - logger.log(Level.WARNING, "Read command failed") - throw IllegalStateException("Read command failed with failures: ${response.failures}") - } - - logger.log(Level.FINE, "Read command succeeded") - - val attributeData = - response.successes.filterIsInstance().firstOrNull { - it.path.attributeId == ATTRIBUTE_ID - } - - requireNotNull(attributeData) { "Microphonevolumelevel attribute not found in response" } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) - } else { - null - } - - return decodedValue - } - - suspend fun writeMicrophoneVolumeLevelAttribute( - value: UByte, - timedWriteTimeout: Duration? = null, - ) { - val ATTRIBUTE_ID: UInt = 35u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - - suspend fun subscribeMicrophoneVolumeLevelAttribute( - minInterval: Int, - maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 35u - val attributePaths = - listOf( - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - ) - - val subscribeRequest: SubscribeRequest = - SubscribeRequest( - eventPaths = emptyList(), - attributePaths = attributePaths, - minInterval = Duration.ofSeconds(minInterval.toLong()), - maxInterval = Duration.ofSeconds(maxInterval.toLong()), - ) - return controller.subscribe(subscribeRequest).transform { subscriptionState -> when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { @@ -4834,7 +4310,7 @@ class CameraAvStreamManagementCluster( } suspend fun readMicrophoneMaxLevelAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 36u + val ATTRIBUTE_ID: UInt = 33u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4869,51 +4345,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeMicrophoneMaxLevelAttribute(value: UByte, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 36u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - suspend fun subscribeMicrophoneMaxLevelAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 36u + val ATTRIBUTE_ID: UInt = 33u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -4967,7 +4403,7 @@ class CameraAvStreamManagementCluster( } suspend fun readMicrophoneMinLevelAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 37u + val ATTRIBUTE_ID: UInt = 34u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5002,51 +4438,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeMicrophoneMinLevelAttribute(value: UByte, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 37u - - val tlvWriter = TlvWriter() - tlvWriter.put(AnonymousTag, value) - - val writeRequests: WriteRequests = - WriteRequests( - requests = - listOf( - WriteRequest( - attributePath = - AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), - tlvPayload = tlvWriter.getEncoded(), - ) - ), - timedRequest = timedWriteTimeout, - ) - - val response: WriteResponse = controller.write(writeRequests) - - when (response) { - is WriteResponse.Success -> { - logger.log(Level.FINE, "Write command succeeded") - } - is WriteResponse.PartialWriteFailure -> { - val aggregatedErrorMessage = - response.failures.joinToString("\n") { failure -> - "Error at ${failure.attributePath}: ${failure.ex.message}" - } - - response.failures.forEach { failure -> - logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") - } - - throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") - } - } - } - suspend fun subscribeMicrophoneMinLevelAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 37u + val ATTRIBUTE_ID: UInt = 34u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5100,7 +4496,7 @@ class CameraAvStreamManagementCluster( } suspend fun readMicrophoneAGCEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 38u + val ATTRIBUTE_ID: UInt = 35u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5139,7 +4535,7 @@ class CameraAvStreamManagementCluster( value: Boolean, timedWriteTimeout: Duration? = null, ) { - val ATTRIBUTE_ID: UInt = 38u + val ATTRIBUTE_ID: UInt = 35u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -5182,7 +4578,7 @@ class CameraAvStreamManagementCluster( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 38u + val ATTRIBUTE_ID: UInt = 35u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5236,7 +4632,7 @@ class CameraAvStreamManagementCluster( } suspend fun readImageRotationAttribute(): UShort? { - val ATTRIBUTE_ID: UInt = 39u + val ATTRIBUTE_ID: UInt = 36u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5271,11 +4667,51 @@ class CameraAvStreamManagementCluster( return decodedValue } + suspend fun writeImageRotationAttribute(value: UShort, timedWriteTimeout: Duration? = null) { + val ATTRIBUTE_ID: UInt = 36u + + val tlvWriter = TlvWriter() + tlvWriter.put(AnonymousTag, value) + + val writeRequests: WriteRequests = + WriteRequests( + requests = + listOf( + WriteRequest( + attributePath = + AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), + tlvPayload = tlvWriter.getEncoded(), + ) + ), + timedRequest = timedWriteTimeout, + ) + + val response: WriteResponse = controller.write(writeRequests) + + when (response) { + is WriteResponse.Success -> { + logger.log(Level.FINE, "Write command succeeded") + } + is WriteResponse.PartialWriteFailure -> { + val aggregatedErrorMessage = + response.failures.joinToString("\n") { failure -> + "Error at ${failure.attributePath}: ${failure.ex.message}" + } + + response.failures.forEach { failure -> + logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") + } + + throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") + } + } + } + suspend fun subscribeImageRotationAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 39u + val ATTRIBUTE_ID: UInt = 36u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5327,7 +4763,7 @@ class CameraAvStreamManagementCluster( } suspend fun readImageFlipHorizontalAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 40u + val ATTRIBUTE_ID: UInt = 37u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5362,104 +4798,54 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun subscribeImageFlipHorizontalAttribute( - minInterval: Int, - maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 40u - val attributePaths = - listOf( - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - ) + suspend fun writeImageFlipHorizontalAttribute( + value: Boolean, + timedWriteTimeout: Duration? = null, + ) { + val ATTRIBUTE_ID: UInt = 37u - val subscribeRequest: SubscribeRequest = - SubscribeRequest( - eventPaths = emptyList(), - attributePaths = attributePaths, - minInterval = Duration.ofSeconds(minInterval.toLong()), - maxInterval = Duration.ofSeconds(maxInterval.toLong()), - ) + val tlvWriter = TlvWriter() + tlvWriter.put(AnonymousTag, value) - return controller.subscribe(subscribeRequest).transform { subscriptionState -> - when (subscriptionState) { - is SubscriptionState.SubscriptionErrorNotification -> { - emit( - BooleanSubscriptionState.Error( - Exception( - "Subscription terminated with error code: ${subscriptionState.terminationCause}" - ) + val writeRequests: WriteRequests = + WriteRequests( + requests = + listOf( + WriteRequest( + attributePath = + AttributePath(endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID), + tlvPayload = tlvWriter.getEncoded(), ) - ) - } - is SubscriptionState.NodeStateUpdate -> { - val attributeData = - subscriptionState.updateState.successes - .filterIsInstance() - .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } - - requireNotNull(attributeData) { - "Imagefliphorizontal attribute not found in Node State update" - } - - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) - } else { - null - } - - decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } - } - SubscriptionState.SubscriptionEstablished -> { - emit(BooleanSubscriptionState.SubscriptionEstablished) - } - } - } - } - - suspend fun readImageFlipVerticalAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 41u - - val attributePath = - AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) - - val readRequest = ReadRequest(eventPaths = emptyList(), attributePaths = listOf(attributePath)) - - val response = controller.read(readRequest) - - if (response.successes.isEmpty()) { - logger.log(Level.WARNING, "Read command failed") - throw IllegalStateException("Read command failed with failures: ${response.failures}") - } + ), + timedRequest = timedWriteTimeout, + ) - logger.log(Level.FINE, "Read command succeeded") + val response: WriteResponse = controller.write(writeRequests) - val attributeData = - response.successes.filterIsInstance().firstOrNull { - it.path.attributeId == ATTRIBUTE_ID + when (response) { + is WriteResponse.Success -> { + logger.log(Level.FINE, "Write command succeeded") } + is WriteResponse.PartialWriteFailure -> { + val aggregatedErrorMessage = + response.failures.joinToString("\n") { failure -> + "Error at ${failure.attributePath}: ${failure.ex.message}" + } - requireNotNull(attributeData) { "Imageflipvertical attribute not found in response" } + response.failures.forEach { failure -> + logger.log(Level.WARNING, "Error at ${failure.attributePath}: ${failure.ex.message}") + } - // Decode the TLV data into the appropriate type - val tlvReader = TlvReader(attributeData.data) - val decodedValue: Boolean? = - if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getBoolean(AnonymousTag) - } else { - null + throw IllegalStateException("Write command failed with errors: \n$aggregatedErrorMessage") } - - return decodedValue + } } - suspend fun subscribeImageFlipVerticalAttribute( + suspend fun subscribeImageFlipHorizontalAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 41u + val ATTRIBUTE_ID: UInt = 37u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5491,7 +4877,7 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Imageflipvertical attribute not found in Node State update" + "Imagefliphorizontal attribute not found in Node State update" } // Decode the TLV data into the appropriate type @@ -5512,8 +4898,8 @@ class CameraAvStreamManagementCluster( } } - suspend fun readLocalVideoRecordingEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 42u + suspend fun readImageFlipVerticalAttribute(): Boolean? { + val ATTRIBUTE_ID: UInt = 38u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5534,7 +4920,7 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Localvideorecordingenabled attribute not found in response" } + requireNotNull(attributeData) { "Imageflipvertical attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -5548,11 +4934,8 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeLocalVideoRecordingEnabledAttribute( - value: Boolean, - timedWriteTimeout: Duration? = null, - ) { - val ATTRIBUTE_ID: UInt = 42u + suspend fun writeImageFlipVerticalAttribute(value: Boolean, timedWriteTimeout: Duration? = null) { + val ATTRIBUTE_ID: UInt = 38u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -5591,11 +4974,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeLocalVideoRecordingEnabledAttribute( + suspend fun subscribeImageFlipVerticalAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 42u + val ATTRIBUTE_ID: UInt = 38u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5627,7 +5010,7 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Localvideorecordingenabled attribute not found in Node State update" + "Imageflipvertical attribute not found in Node State update" } // Decode the TLV data into the appropriate type @@ -5648,8 +5031,8 @@ class CameraAvStreamManagementCluster( } } - suspend fun readLocalSnapshotRecordingEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 43u + suspend fun readLocalVideoRecordingEnabledAttribute(): Boolean? { + val ATTRIBUTE_ID: UInt = 39u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5670,9 +5053,7 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { - "Localsnapshotrecordingenabled attribute not found in response" - } + requireNotNull(attributeData) { "Localvideorecordingenabled attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -5686,11 +5067,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeLocalSnapshotRecordingEnabledAttribute( + suspend fun writeLocalVideoRecordingEnabledAttribute( value: Boolean, timedWriteTimeout: Duration? = null, ) { - val ATTRIBUTE_ID: UInt = 43u + val ATTRIBUTE_ID: UInt = 39u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -5729,11 +5110,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeLocalSnapshotRecordingEnabledAttribute( + suspend fun subscribeLocalVideoRecordingEnabledAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 43u + val ATTRIBUTE_ID: UInt = 39u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5765,7 +5146,7 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Localsnapshotrecordingenabled attribute not found in Node State update" + "Localvideorecordingenabled attribute not found in Node State update" } // Decode the TLV data into the appropriate type @@ -5786,8 +5167,8 @@ class CameraAvStreamManagementCluster( } } - suspend fun readStatusLightEnabledAttribute(): Boolean? { - val ATTRIBUTE_ID: UInt = 44u + suspend fun readLocalSnapshotRecordingEnabledAttribute(): Boolean? { + val ATTRIBUTE_ID: UInt = 40u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5808,7 +5189,9 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Statuslightenabled attribute not found in response" } + requireNotNull(attributeData) { + "Localsnapshotrecordingenabled attribute not found in response" + } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -5822,11 +5205,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeStatusLightEnabledAttribute( + suspend fun writeLocalSnapshotRecordingEnabledAttribute( value: Boolean, timedWriteTimeout: Duration? = null, ) { - val ATTRIBUTE_ID: UInt = 44u + val ATTRIBUTE_ID: UInt = 40u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -5865,11 +5248,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeStatusLightEnabledAttribute( + suspend fun subscribeLocalSnapshotRecordingEnabledAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 44u + val ATTRIBUTE_ID: UInt = 40u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5901,7 +5284,7 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Statuslightenabled attribute not found in Node State update" + "Localsnapshotrecordingenabled attribute not found in Node State update" } // Decode the TLV data into the appropriate type @@ -5922,8 +5305,8 @@ class CameraAvStreamManagementCluster( } } - suspend fun readStatusLightBrightnessAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 45u + suspend fun readStatusLightEnabledAttribute(): Boolean? { + val ATTRIBUTE_ID: UInt = 41u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -5944,13 +5327,13 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Statuslightbrightness attribute not found in response" } + requireNotNull(attributeData) { "Statuslightenabled attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = + val decodedValue: Boolean? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) + tlvReader.getBoolean(AnonymousTag) } else { null } @@ -5958,11 +5341,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeStatusLightBrightnessAttribute( - value: UByte, + suspend fun writeStatusLightEnabledAttribute( + value: Boolean, timedWriteTimeout: Duration? = null, ) { - val ATTRIBUTE_ID: UInt = 45u + val ATTRIBUTE_ID: UInt = 41u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -6001,11 +5384,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeStatusLightBrightnessAttribute( + suspend fun subscribeStatusLightEnabledAttribute( minInterval: Int, maxInterval: Int, - ): Flow { - val ATTRIBUTE_ID: UInt = 45u + ): Flow { + val ATTRIBUTE_ID: UInt = 41u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -6023,7 +5406,7 @@ class CameraAvStreamManagementCluster( when (subscriptionState) { is SubscriptionState.SubscriptionErrorNotification -> { emit( - UByteSubscriptionState.Error( + BooleanSubscriptionState.Error( Exception( "Subscription terminated with error code: ${subscriptionState.terminationCause}" ) @@ -6037,29 +5420,29 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Statuslightbrightness attribute not found in Node State update" + "Statuslightenabled attribute not found in Node State update" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) - val decodedValue: UByte? = + val decodedValue: Boolean? = if (tlvReader.isNextTag(AnonymousTag)) { - tlvReader.getUByte(AnonymousTag) + tlvReader.getBoolean(AnonymousTag) } else { null } - decodedValue?.let { emit(UByteSubscriptionState.Success(it)) } + decodedValue?.let { emit(BooleanSubscriptionState.Success(it)) } } SubscriptionState.SubscriptionEstablished -> { - emit(UByteSubscriptionState.SubscriptionEstablished) + emit(BooleanSubscriptionState.SubscriptionEstablished) } } } } - suspend fun readDepthSensorStatusAttribute(): UByte? { - val ATTRIBUTE_ID: UInt = 46u + suspend fun readStatusLightBrightnessAttribute(): UByte? { + val ATTRIBUTE_ID: UInt = 42u val attributePath = AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -6080,7 +5463,7 @@ class CameraAvStreamManagementCluster( it.path.attributeId == ATTRIBUTE_ID } - requireNotNull(attributeData) { "Depthsensorstatus attribute not found in response" } + requireNotNull(attributeData) { "Statuslightbrightness attribute not found in response" } // Decode the TLV data into the appropriate type val tlvReader = TlvReader(attributeData.data) @@ -6094,8 +5477,11 @@ class CameraAvStreamManagementCluster( return decodedValue } - suspend fun writeDepthSensorStatusAttribute(value: UByte, timedWriteTimeout: Duration? = null) { - val ATTRIBUTE_ID: UInt = 46u + suspend fun writeStatusLightBrightnessAttribute( + value: UByte, + timedWriteTimeout: Duration? = null, + ) { + val ATTRIBUTE_ID: UInt = 42u val tlvWriter = TlvWriter() tlvWriter.put(AnonymousTag, value) @@ -6134,11 +5520,11 @@ class CameraAvStreamManagementCluster( } } - suspend fun subscribeDepthSensorStatusAttribute( + suspend fun subscribeStatusLightBrightnessAttribute( minInterval: Int, maxInterval: Int, ): Flow { - val ATTRIBUTE_ID: UInt = 46u + val ATTRIBUTE_ID: UInt = 42u val attributePaths = listOf( AttributePath(endpointId = endpointId, clusterId = CLUSTER_ID, attributeId = ATTRIBUTE_ID) @@ -6170,7 +5556,7 @@ class CameraAvStreamManagementCluster( .firstOrNull { it.path.attributeId == ATTRIBUTE_ID } requireNotNull(attributeData) { - "Depthsensorstatus attribute not found in Node State update" + "Statuslightbrightness attribute not found in Node State update" } // Decode the TLV data into the appropriate type diff --git a/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp b/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp index c8247c5d4d31a8..b07c63d480f6d6 100644 --- a/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp +++ b/src/controller/java/zap-generated/CHIPAttributeTLVValueDecoder.cpp @@ -41252,54 +41252,6 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR value); return value; } - case Attributes::AWBEnabled::Id: { - using TypeInfo = Attributes::AWBEnabled::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = app::DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) - { - return nullptr; - } - jobject value; - std::string valueClassName = "java/lang/Boolean"; - std::string valueCtorSignature = "(Z)V"; - jboolean jnivalue = static_cast(cppValue); - chip::JniReferences::GetInstance().CreateBoxedObject(valueClassName.c_str(), valueCtorSignature.c_str(), - jnivalue, value); - return value; - } - case Attributes::AutoShutterSpeedEnabled::Id: { - using TypeInfo = Attributes::AutoShutterSpeedEnabled::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = app::DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) - { - return nullptr; - } - jobject value; - std::string valueClassName = "java/lang/Boolean"; - std::string valueCtorSignature = "(Z)V"; - jboolean jnivalue = static_cast(cppValue); - chip::JniReferences::GetInstance().CreateBoxedObject(valueClassName.c_str(), valueCtorSignature.c_str(), - jnivalue, value); - return value; - } - case Attributes::AutoISOEnabled::Id: { - using TypeInfo = Attributes::AutoISOEnabled::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = app::DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) - { - return nullptr; - } - jobject value; - std::string valueClassName = "java/lang/Boolean"; - std::string valueCtorSignature = "(Z)V"; - jboolean jnivalue = static_cast(cppValue); - chip::JniReferences::GetInstance().CreateBoxedObject(valueClassName.c_str(), valueCtorSignature.c_str(), - jnivalue, value); - return value; - } case Attributes::Viewport::Id: { using TypeInfo = Attributes::Viewport::TypeInfo; TypeInfo::DecodableType cppValue; @@ -41616,22 +41568,6 @@ jobject DecodeAttributeValue(const app::ConcreteAttributePath & aPath, TLV::TLVR value); return value; } - case Attributes::DepthSensorStatus::Id: { - using TypeInfo = Attributes::DepthSensorStatus::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = app::DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) - { - return nullptr; - } - jobject value; - std::string valueClassName = "java/lang/Integer"; - std::string valueCtorSignature = "(I)V"; - jint jnivalue = static_cast(cppValue); - chip::JniReferences::GetInstance().CreateBoxedObject(valueClassName.c_str(), valueCtorSignature.c_str(), jnivalue, - value); - return value; - } case Attributes::GeneratedCommandList::Id: { using TypeInfo = Attributes::GeneratedCommandList::TypeInfo; TypeInfo::DecodableType cppValue; diff --git a/src/controller/python/chip/clusters/CHIPClusters.py b/src/controller/python/chip/clusters/CHIPClusters.py index 08f8182e6b6886..ba02cdeb026fd5 100644 --- a/src/controller/python/chip/clusters/CHIPClusters.py +++ b/src/controller/python/chip/clusters/CHIPClusters.py @@ -12476,34 +12476,6 @@ class ChipClusters: "requestedResolution": "VideoResolutionStruct", }, }, - 0x0000000D: { - "commandId": 0x0000000D, - "commandName": "SetViewport", - "args": { - "viewport": "ViewportStruct", - }, - }, - 0x0000000E: { - "commandId": 0x0000000E, - "commandName": "SetImageRotation", - "args": { - "angle": "int", - }, - }, - 0x0000000F: { - "commandId": 0x0000000F, - "commandName": "SetImageFlipHorizontal", - "args": { - "enabled": "bool", - }, - }, - 0x00000010: { - "commandId": 0x00000010, - "commandName": "SetImageFlipVertical", - "args": { - "enabled": "bool", - }, - }, }, "attributes": { 0x00000000: { @@ -12669,144 +12641,116 @@ class ChipClusters: "writable": True, }, 0x0000001A: { - "attributeName": "AWBEnabled", + "attributeName": "Viewport", "attributeId": 0x0000001A, - "type": "bool", + "type": "", "reportable": True, "writable": True, }, 0x0000001B: { - "attributeName": "AutoShutterSpeedEnabled", + "attributeName": "SpeakerMuted", "attributeId": 0x0000001B, "type": "bool", "reportable": True, "writable": True, }, 0x0000001C: { - "attributeName": "AutoISOEnabled", + "attributeName": "SpeakerVolumeLevel", "attributeId": 0x0000001C, - "type": "bool", + "type": "int", "reportable": True, "writable": True, }, 0x0000001D: { - "attributeName": "Viewport", + "attributeName": "SpeakerMaxLevel", "attributeId": 0x0000001D, - "type": "", + "type": "int", "reportable": True, }, 0x0000001E: { - "attributeName": "SpeakerMuted", + "attributeName": "SpeakerMinLevel", "attributeId": 0x0000001E, - "type": "bool", + "type": "int", "reportable": True, - "writable": True, }, 0x0000001F: { - "attributeName": "SpeakerVolumeLevel", + "attributeName": "MicrophoneMuted", "attributeId": 0x0000001F, - "type": "int", + "type": "bool", "reportable": True, "writable": True, }, 0x00000020: { - "attributeName": "SpeakerMaxLevel", + "attributeName": "MicrophoneVolumeLevel", "attributeId": 0x00000020, "type": "int", "reportable": True, "writable": True, }, 0x00000021: { - "attributeName": "SpeakerMinLevel", + "attributeName": "MicrophoneMaxLevel", "attributeId": 0x00000021, "type": "int", "reportable": True, - "writable": True, }, 0x00000022: { - "attributeName": "MicrophoneMuted", + "attributeName": "MicrophoneMinLevel", "attributeId": 0x00000022, - "type": "bool", + "type": "int", "reportable": True, - "writable": True, }, 0x00000023: { - "attributeName": "MicrophoneVolumeLevel", + "attributeName": "MicrophoneAGCEnabled", "attributeId": 0x00000023, - "type": "int", + "type": "bool", "reportable": True, "writable": True, }, 0x00000024: { - "attributeName": "MicrophoneMaxLevel", + "attributeName": "ImageRotation", "attributeId": 0x00000024, "type": "int", "reportable": True, "writable": True, }, 0x00000025: { - "attributeName": "MicrophoneMinLevel", + "attributeName": "ImageFlipHorizontal", "attributeId": 0x00000025, - "type": "int", + "type": "bool", "reportable": True, "writable": True, }, 0x00000026: { - "attributeName": "MicrophoneAGCEnabled", + "attributeName": "ImageFlipVertical", "attributeId": 0x00000026, "type": "bool", "reportable": True, "writable": True, }, 0x00000027: { - "attributeName": "ImageRotation", - "attributeId": 0x00000027, - "type": "int", - "reportable": True, - }, - 0x00000028: { - "attributeName": "ImageFlipHorizontal", - "attributeId": 0x00000028, - "type": "bool", - "reportable": True, - }, - 0x00000029: { - "attributeName": "ImageFlipVertical", - "attributeId": 0x00000029, - "type": "bool", - "reportable": True, - }, - 0x0000002A: { "attributeName": "LocalVideoRecordingEnabled", - "attributeId": 0x0000002A, + "attributeId": 0x00000027, "type": "bool", "reportable": True, "writable": True, }, - 0x0000002B: { + 0x00000028: { "attributeName": "LocalSnapshotRecordingEnabled", - "attributeId": 0x0000002B, + "attributeId": 0x00000028, "type": "bool", "reportable": True, "writable": True, }, - 0x0000002C: { + 0x00000029: { "attributeName": "StatusLightEnabled", - "attributeId": 0x0000002C, + "attributeId": 0x00000029, "type": "bool", "reportable": True, "writable": True, }, - 0x0000002D: { + 0x0000002A: { "attributeName": "StatusLightBrightness", - "attributeId": 0x0000002D, - "type": "int", - "reportable": True, - "writable": True, - }, - 0x0000002E: { - "attributeName": "DepthSensorStatus", - "attributeId": 0x0000002E, + "attributeId": 0x0000002A, "type": "int", "reportable": True, "writable": True, diff --git a/src/controller/python/chip/clusters/Objects.py b/src/controller/python/chip/clusters/Objects.py index b7b73282715a22..8774535b1a2a7f 100644 --- a/src/controller/python/chip/clusters/Objects.py +++ b/src/controller/python/chip/clusters/Objects.py @@ -44799,27 +44799,23 @@ def descriptor(cls) -> ClusterObjectDescriptor: ClusterObjectFieldDescriptor(Label="hardPrivacyModeOn", Tag=0x00000017, Type=typing.Optional[bool]), ClusterObjectFieldDescriptor(Label="nightVision", Tag=0x00000018, Type=typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum]), ClusterObjectFieldDescriptor(Label="nightVisionIllum", Tag=0x00000019, Type=typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum]), - ClusterObjectFieldDescriptor(Label="AWBEnabled", Tag=0x0000001A, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="autoShutterSpeedEnabled", Tag=0x0000001B, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="autoISOEnabled", Tag=0x0000001C, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="viewport", Tag=0x0000001D, Type=typing.Optional[CameraAvStreamManagement.Structs.ViewportStruct]), - ClusterObjectFieldDescriptor(Label="speakerMuted", Tag=0x0000001E, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="speakerVolumeLevel", Tag=0x0000001F, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="speakerMaxLevel", Tag=0x00000020, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="speakerMinLevel", Tag=0x00000021, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="microphoneMuted", Tag=0x00000022, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="microphoneVolumeLevel", Tag=0x00000023, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="microphoneMaxLevel", Tag=0x00000024, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="microphoneMinLevel", Tag=0x00000025, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="microphoneAGCEnabled", Tag=0x00000026, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="imageRotation", Tag=0x00000027, Type=typing.Optional[uint]), - ClusterObjectFieldDescriptor(Label="imageFlipHorizontal", Tag=0x00000028, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="imageFlipVertical", Tag=0x00000029, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="localVideoRecordingEnabled", Tag=0x0000002A, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="localSnapshotRecordingEnabled", Tag=0x0000002B, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="statusLightEnabled", Tag=0x0000002C, Type=typing.Optional[bool]), - ClusterObjectFieldDescriptor(Label="statusLightBrightness", Tag=0x0000002D, Type=typing.Optional[Globals.Enums.ThreeLevelAutoEnum]), - ClusterObjectFieldDescriptor(Label="depthSensorStatus", Tag=0x0000002E, Type=typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum]), + ClusterObjectFieldDescriptor(Label="viewport", Tag=0x0000001A, Type=typing.Optional[CameraAvStreamManagement.Structs.ViewportStruct]), + ClusterObjectFieldDescriptor(Label="speakerMuted", Tag=0x0000001B, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="speakerVolumeLevel", Tag=0x0000001C, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="speakerMaxLevel", Tag=0x0000001D, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="speakerMinLevel", Tag=0x0000001E, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="microphoneMuted", Tag=0x0000001F, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="microphoneVolumeLevel", Tag=0x00000020, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="microphoneMaxLevel", Tag=0x00000021, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="microphoneMinLevel", Tag=0x00000022, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="microphoneAGCEnabled", Tag=0x00000023, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="imageRotation", Tag=0x00000024, Type=typing.Optional[uint]), + ClusterObjectFieldDescriptor(Label="imageFlipHorizontal", Tag=0x00000025, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="imageFlipVertical", Tag=0x00000026, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="localVideoRecordingEnabled", Tag=0x00000027, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="localSnapshotRecordingEnabled", Tag=0x00000028, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="statusLightEnabled", Tag=0x00000029, Type=typing.Optional[bool]), + ClusterObjectFieldDescriptor(Label="statusLightBrightness", Tag=0x0000002A, Type=typing.Optional[Globals.Enums.ThreeLevelAutoEnum]), ClusterObjectFieldDescriptor(Label="generatedCommandList", Tag=0x0000FFF8, Type=typing.List[uint]), ClusterObjectFieldDescriptor(Label="acceptedCommandList", Tag=0x0000FFF9, Type=typing.List[uint]), ClusterObjectFieldDescriptor(Label="attributeList", Tag=0x0000FFFB, Type=typing.List[uint]), @@ -44853,9 +44849,6 @@ def descriptor(cls) -> ClusterObjectDescriptor: hardPrivacyModeOn: typing.Optional[bool] = None nightVision: typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum] = None nightVisionIllum: typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum] = None - AWBEnabled: typing.Optional[bool] = None - autoShutterSpeedEnabled: typing.Optional[bool] = None - autoISOEnabled: typing.Optional[bool] = None viewport: typing.Optional[CameraAvStreamManagement.Structs.ViewportStruct] = None speakerMuted: typing.Optional[bool] = None speakerVolumeLevel: typing.Optional[uint] = None @@ -44873,7 +44866,6 @@ def descriptor(cls) -> ClusterObjectDescriptor: localSnapshotRecordingEnabled: typing.Optional[bool] = None statusLightEnabled: typing.Optional[bool] = None statusLightBrightness: typing.Optional[Globals.Enums.ThreeLevelAutoEnum] = None - depthSensorStatus: typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum] = None generatedCommandList: typing.List[uint] = field(default_factory=lambda: []) acceptedCommandList: typing.List[uint] = field(default_factory=lambda: []) attributeList: typing.List[uint] = field(default_factory=lambda: []) @@ -44942,12 +44934,12 @@ class VideoCodecEnum(MatterIntEnum): class Bitmaps: class Feature(IntFlag): - kPrivacy = 0x1 - kAudio = 0x2 - kSpeaker = 0x4 - kImageControl = 0x8 - kVideo = 0x10 - kSnapshot = 0x20 + kAudio = 0x1 + kVideo = 0x2 + kSnapshot = 0x4 + kPrivacy = 0x8 + kSpeaker = 0x10 + kImageControl = 0x20 kWatermark = 0x40 kOnScreenDisplay = 0x80 kLocalStorage = 0x100 @@ -45399,70 +45391,6 @@ def descriptor(cls) -> ClusterObjectDescriptor: imageCodec: CameraAvStreamManagement.Enums.ImageCodecEnum = 0 resolution: CameraAvStreamManagement.Structs.VideoResolutionStruct = field(default_factory=lambda: CameraAvStreamManagement.Structs.VideoResolutionStruct()) - @dataclass - class SetViewport(ClusterCommand): - cluster_id: typing.ClassVar[int] = 0x00000551 - command_id: typing.ClassVar[int] = 0x0000000D - is_client: typing.ClassVar[bool] = True - response_type: typing.ClassVar[typing.Optional[str]] = None - - @ChipUtility.classproperty - def descriptor(cls) -> ClusterObjectDescriptor: - return ClusterObjectDescriptor( - Fields=[ - ClusterObjectFieldDescriptor(Label="viewport", Tag=0, Type=CameraAvStreamManagement.Structs.ViewportStruct), - ]) - - viewport: CameraAvStreamManagement.Structs.ViewportStruct = field(default_factory=lambda: CameraAvStreamManagement.Structs.ViewportStruct()) - - @dataclass - class SetImageRotation(ClusterCommand): - cluster_id: typing.ClassVar[int] = 0x00000551 - command_id: typing.ClassVar[int] = 0x0000000E - is_client: typing.ClassVar[bool] = True - response_type: typing.ClassVar[typing.Optional[str]] = None - - @ChipUtility.classproperty - def descriptor(cls) -> ClusterObjectDescriptor: - return ClusterObjectDescriptor( - Fields=[ - ClusterObjectFieldDescriptor(Label="angle", Tag=0, Type=uint), - ]) - - angle: uint = 0 - - @dataclass - class SetImageFlipHorizontal(ClusterCommand): - cluster_id: typing.ClassVar[int] = 0x00000551 - command_id: typing.ClassVar[int] = 0x0000000F - is_client: typing.ClassVar[bool] = True - response_type: typing.ClassVar[typing.Optional[str]] = None - - @ChipUtility.classproperty - def descriptor(cls) -> ClusterObjectDescriptor: - return ClusterObjectDescriptor( - Fields=[ - ClusterObjectFieldDescriptor(Label="enabled", Tag=0, Type=bool), - ]) - - enabled: bool = False - - @dataclass - class SetImageFlipVertical(ClusterCommand): - cluster_id: typing.ClassVar[int] = 0x00000551 - command_id: typing.ClassVar[int] = 0x00000010 - is_client: typing.ClassVar[bool] = True - response_type: typing.ClassVar[typing.Optional[str]] = None - - @ChipUtility.classproperty - def descriptor(cls) -> ClusterObjectDescriptor: - return ClusterObjectDescriptor( - Fields=[ - ClusterObjectFieldDescriptor(Label="enabled", Tag=0, Type=bool), - ]) - - enabled: bool = False - class Attributes: @dataclass class MaxConcurrentVideoEncoders(ClusterAttributeDescriptor): @@ -45880,54 +45808,6 @@ def attribute_type(cls) -> ClusterObjectFieldDescriptor: value: typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum] = None - @dataclass - class AWBEnabled(ClusterAttributeDescriptor): - @ChipUtility.classproperty - def cluster_id(cls) -> int: - return 0x00000551 - - @ChipUtility.classproperty - def attribute_id(cls) -> int: - return 0x0000001A - - @ChipUtility.classproperty - def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=typing.Optional[bool]) - - value: typing.Optional[bool] = None - - @dataclass - class AutoShutterSpeedEnabled(ClusterAttributeDescriptor): - @ChipUtility.classproperty - def cluster_id(cls) -> int: - return 0x00000551 - - @ChipUtility.classproperty - def attribute_id(cls) -> int: - return 0x0000001B - - @ChipUtility.classproperty - def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=typing.Optional[bool]) - - value: typing.Optional[bool] = None - - @dataclass - class AutoISOEnabled(ClusterAttributeDescriptor): - @ChipUtility.classproperty - def cluster_id(cls) -> int: - return 0x00000551 - - @ChipUtility.classproperty - def attribute_id(cls) -> int: - return 0x0000001C - - @ChipUtility.classproperty - def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=typing.Optional[bool]) - - value: typing.Optional[bool] = None - @dataclass class Viewport(ClusterAttributeDescriptor): @ChipUtility.classproperty @@ -45936,7 +45816,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000001D + return 0x0000001A @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45952,7 +45832,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000001E + return 0x0000001B @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45968,7 +45848,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000001F + return 0x0000001C @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -45984,7 +45864,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000020 + return 0x0000001D @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46000,7 +45880,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000021 + return 0x0000001E @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46016,7 +45896,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000022 + return 0x0000001F @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46032,7 +45912,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000023 + return 0x00000020 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46048,7 +45928,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000024 + return 0x00000021 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46064,7 +45944,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000025 + return 0x00000022 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46080,7 +45960,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000026 + return 0x00000023 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46096,7 +45976,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000027 + return 0x00000024 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46112,7 +45992,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000028 + return 0x00000025 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46128,7 +46008,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x00000029 + return 0x00000026 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46144,7 +46024,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000002A + return 0x00000027 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46160,7 +46040,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000002B + return 0x00000028 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46176,7 +46056,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000002C + return 0x00000029 @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46192,7 +46072,7 @@ def cluster_id(cls) -> int: @ChipUtility.classproperty def attribute_id(cls) -> int: - return 0x0000002D + return 0x0000002A @ChipUtility.classproperty def attribute_type(cls) -> ClusterObjectFieldDescriptor: @@ -46200,22 +46080,6 @@ def attribute_type(cls) -> ClusterObjectFieldDescriptor: value: typing.Optional[Globals.Enums.ThreeLevelAutoEnum] = None - @dataclass - class DepthSensorStatus(ClusterAttributeDescriptor): - @ChipUtility.classproperty - def cluster_id(cls) -> int: - return 0x00000551 - - @ChipUtility.classproperty - def attribute_id(cls) -> int: - return 0x0000002E - - @ChipUtility.classproperty - def attribute_type(cls) -> ClusterObjectFieldDescriptor: - return ClusterObjectFieldDescriptor(Type=typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum]) - - value: typing.Optional[CameraAvStreamManagement.Enums.TriStateAutoEnum] = None - @dataclass class GeneratedCommandList(ClusterAttributeDescriptor): @ChipUtility.classproperty diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeSpecifiedCheck.mm b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeSpecifiedCheck.mm index 43e0528c252c14..c544b8ade33851 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeSpecifiedCheck.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeSpecifiedCheck.mm @@ -5673,15 +5673,6 @@ static BOOL AttributeIsSpecifiedInCameraAVStreamManagementCluster(AttributeId aA case Attributes::NightVisionIllum::Id: { return YES; } - case Attributes::AWBEnabled::Id: { - return YES; - } - case Attributes::AutoShutterSpeedEnabled::Id: { - return YES; - } - case Attributes::AutoISOEnabled::Id: { - return YES; - } case Attributes::Viewport::Id: { return YES; } @@ -5733,9 +5724,6 @@ static BOOL AttributeIsSpecifiedInCameraAVStreamManagementCluster(AttributeId aA case Attributes::StatusLightBrightness::Id: { return YES; } - case Attributes::DepthSensorStatus::Id: { - return YES; - } case Attributes::GeneratedCommandList::Id: { return YES; } diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm index 16f882fe473a43..0eacdb19363f28 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRAttributeTLVValueDecoder.mm @@ -17478,39 +17478,6 @@ static id _Nullable DecodeAttributeValueForCameraAVStreamManagementCluster(Attri value = [NSNumber numberWithUnsignedChar:chip::to_underlying(cppValue)]; return value; } - case Attributes::AWBEnabled::Id: { - using TypeInfo = Attributes::AWBEnabled::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) { - return nil; - } - NSNumber * _Nonnull value; - value = [NSNumber numberWithBool:cppValue]; - return value; - } - case Attributes::AutoShutterSpeedEnabled::Id: { - using TypeInfo = Attributes::AutoShutterSpeedEnabled::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) { - return nil; - } - NSNumber * _Nonnull value; - value = [NSNumber numberWithBool:cppValue]; - return value; - } - case Attributes::AutoISOEnabled::Id: { - using TypeInfo = Attributes::AutoISOEnabled::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) { - return nil; - } - NSNumber * _Nonnull value; - value = [NSNumber numberWithBool:cppValue]; - return value; - } case Attributes::Viewport::Id: { using TypeInfo = Attributes::Viewport::TypeInfo; TypeInfo::DecodableType cppValue; @@ -17702,17 +17669,6 @@ static id _Nullable DecodeAttributeValueForCameraAVStreamManagementCluster(Attri value = [NSNumber numberWithUnsignedChar:chip::to_underlying(cppValue)]; return value; } - case Attributes::DepthSensorStatus::Id: { - using TypeInfo = Attributes::DepthSensorStatus::TypeInfo; - TypeInfo::DecodableType cppValue; - *aError = DataModel::Decode(aReader, cppValue); - if (*aError != CHIP_NO_ERROR) { - return nil; - } - NSNumber * _Nonnull value; - value = [NSNumber numberWithUnsignedChar:chip::to_underlying(cppValue)]; - return value; - } default: { break; } diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h index 73008bfde7f718..edf7ad201ce259 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.h @@ -14199,30 +14199,6 @@ MTR_PROVISIONALLY_AVAILABLE * This command SHALL return a Snapshot from the camera. */ - (void)captureSnapshotWithParams:(MTRCameraAVStreamManagementClusterCaptureSnapshotParams *)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -/** - * Command SetViewport - * - * This command sets the viewport in all video streams. - */ -- (void)setViewportWithParams:(MTRCameraAVStreamManagementClusterSetViewportParams *)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -/** - * Command SetImageRotation - * - * The data fields for this command SHALL be as follows: - */ -- (void)setImageRotationWithParams:(MTRCameraAVStreamManagementClusterSetImageRotationParams *)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -/** - * Command SetImageFlipHorizontal - * - * The data fields for this command SHALL be as follows: - */ -- (void)setImageFlipHorizontalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams *)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -/** - * Command SetImageFlipVertical - * - * The data fields for this command SHALL be as follows: - */ -- (void)setImageFlipVerticalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams *)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeMaxConcurrentVideoEncodersWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeMaxConcurrentVideoEncodersWithParams:(MTRSubscribeParams *)params @@ -14392,31 +14368,9 @@ MTR_PROVISIONALLY_AVAILABLE reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeNightVisionIllumWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)readAttributeAWBEnabledWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAWBEnabledWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAWBEnabledWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)subscribeAttributeAWBEnabledWithParams:(MTRSubscribeParams *)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; -+ (void)readAttributeAWBEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - -- (void)readAttributeAutoShutterSpeedEnabledWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)subscribeAttributeAutoShutterSpeedEnabledWithParams:(MTRSubscribeParams *)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; -+ (void)readAttributeAutoShutterSpeedEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - -- (void)readAttributeAutoISOEnabledWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoISOEnabledWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoISOEnabledWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)subscribeAttributeAutoISOEnabledWithParams:(MTRSubscribeParams *)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; -+ (void)readAttributeAutoISOEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - - (void)readAttributeViewportWithCompletion:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeViewportWithValue:(MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeViewportWithValue:(MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeViewportWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; @@ -14439,16 +14393,12 @@ MTR_PROVISIONALLY_AVAILABLE + (void)readAttributeSpeakerVolumeLevelWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeSpeakerMaxLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeSpeakerMaxLevelWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeSpeakerMaxLevelWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeSpeakerMinLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMinLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMinLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeSpeakerMinLevelWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; @@ -14471,16 +14421,12 @@ MTR_PROVISIONALLY_AVAILABLE + (void)readAttributeMicrophoneVolumeLevelWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeMicrophoneMaxLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeMicrophoneMaxLevelWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeMicrophoneMaxLevelWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeMicrophoneMinLevelWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeMicrophoneMinLevelWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; @@ -14495,18 +14441,24 @@ MTR_PROVISIONALLY_AVAILABLE + (void)readAttributeMicrophoneAGCEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeImageRotationWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageRotationWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageRotationWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeImageRotationWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeImageRotationWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeImageFlipHorizontalWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipHorizontalWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipHorizontalWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeImageFlipHorizontalWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeImageFlipHorizontalWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)readAttributeImageFlipVerticalWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipVerticalWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipVerticalWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeImageFlipVerticalWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; @@ -14544,14 +14496,6 @@ MTR_PROVISIONALLY_AVAILABLE reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; + (void)readAttributeStatusLightBrightnessWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)readAttributeDepthSensorStatusWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeDepthSensorStatusWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeDepthSensorStatusWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)subscribeAttributeDepthSensorStatusWithParams:(MTRSubscribeParams *)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler MTR_PROVISIONALLY_AVAILABLE; -+ (void)readAttributeDepthSensorStatusWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - - (void)readAttributeGeneratedCommandListWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion MTR_PROVISIONALLY_AVAILABLE; - (void)subscribeAttributeGeneratedCommandListWithParams:(MTRSubscribeParams *)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished @@ -20188,12 +20132,12 @@ typedef NS_ENUM(uint8_t, MTRCameraAVStreamManagementVideoCodec) { } MTR_PROVISIONALLY_AVAILABLE; typedef NS_OPTIONS(uint32_t, MTRCameraAVStreamManagementFeature) { - MTRCameraAVStreamManagementFeaturePrivacy MTR_PROVISIONALLY_AVAILABLE = 0x1, - MTRCameraAVStreamManagementFeatureAudio MTR_PROVISIONALLY_AVAILABLE = 0x2, - MTRCameraAVStreamManagementFeatureSpeaker MTR_PROVISIONALLY_AVAILABLE = 0x4, - MTRCameraAVStreamManagementFeatureImageControl MTR_PROVISIONALLY_AVAILABLE = 0x8, - MTRCameraAVStreamManagementFeatureVideo MTR_PROVISIONALLY_AVAILABLE = 0x10, - MTRCameraAVStreamManagementFeatureSnapshot MTR_PROVISIONALLY_AVAILABLE = 0x20, + MTRCameraAVStreamManagementFeatureAudio MTR_PROVISIONALLY_AVAILABLE = 0x1, + MTRCameraAVStreamManagementFeatureVideo MTR_PROVISIONALLY_AVAILABLE = 0x2, + MTRCameraAVStreamManagementFeatureSnapshot MTR_PROVISIONALLY_AVAILABLE = 0x4, + MTRCameraAVStreamManagementFeaturePrivacy MTR_PROVISIONALLY_AVAILABLE = 0x8, + MTRCameraAVStreamManagementFeatureSpeaker MTR_PROVISIONALLY_AVAILABLE = 0x10, + MTRCameraAVStreamManagementFeatureImageControl MTR_PROVISIONALLY_AVAILABLE = 0x20, MTRCameraAVStreamManagementFeatureWatermark MTR_PROVISIONALLY_AVAILABLE = 0x40, MTRCameraAVStreamManagementFeatureOnScreenDisplay MTR_PROVISIONALLY_AVAILABLE = 0x80, MTRCameraAVStreamManagementFeatureLocalStorage MTR_PROVISIONALLY_AVAILABLE = 0x100, diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.mm b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.mm index 3c347c4472e132..0d13ca47be3c6d 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRBaseClusters.mm @@ -98330,102 +98330,6 @@ - (void)captureSnapshotWithParams:(MTRCameraAVStreamManagementClusterCaptureSnap queue:self.callbackQueue completion:responseHandler]; } -- (void)setViewportWithParams:(MTRCameraAVStreamManagementClusterSetViewportParams *)params completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetViewportParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetViewport::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} -- (void)setImageRotationWithParams:(MTRCameraAVStreamManagementClusterSetImageRotationParams *)params completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetImageRotationParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetImageRotation::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} -- (void)setImageFlipHorizontalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams *)params completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} -- (void)setImageFlipVerticalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams *)params completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetImageFlipVertical::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} - (void)readAttributeMaxConcurrentVideoEncodersWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion { @@ -99552,137 +99456,9 @@ + (void)readAttributeNightVisionIllumWithClusterStateCache:(MTRClusterStateCache completion:completion]; } -- (void)readAttributeAWBEnabledWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::AWBEnabled::TypeInfo; - [self.device _readKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:nil - queue:self.callbackQueue - completion:completion]; -} - -- (void)writeAttributeAWBEnabledWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeAWBEnabledWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeAWBEnabledWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::AWBEnabled::TypeInfo; - TypeInfo::Type cppValue; - cppValue = value.boolValue; - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - -- (void)subscribeAttributeAWBEnabledWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler -{ - using TypeInfo = CameraAvStreamManagement::Attributes::AWBEnabled::TypeInfo; - [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:params - queue:self.callbackQueue - reportHandler:reportHandler - subscriptionEstablished:subscriptionEstablished]; -} - -+ (void)readAttributeAWBEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::AWBEnabled::TypeInfo; - [clusterStateCacheContainer - _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) - clusterID:TypeInfo::GetClusterId() - attributeID:TypeInfo::GetAttributeId() - queue:queue - completion:completion]; -} - -- (void)readAttributeAutoShutterSpeedEnabledWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::TypeInfo; - [self.device _readKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:nil - queue:self.callbackQueue - completion:completion]; -} - -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeAutoShutterSpeedEnabledWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::TypeInfo; - TypeInfo::Type cppValue; - cppValue = value.boolValue; - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - -- (void)subscribeAttributeAutoShutterSpeedEnabledWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler -{ - using TypeInfo = CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::TypeInfo; - [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:params - queue:self.callbackQueue - reportHandler:reportHandler - subscriptionEstablished:subscriptionEstablished]; -} - -+ (void)readAttributeAutoShutterSpeedEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::TypeInfo; - [clusterStateCacheContainer - _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) - clusterID:TypeInfo::GetClusterId() - attributeID:TypeInfo::GetAttributeId() - queue:queue - completion:completion]; -} - -- (void)readAttributeAutoISOEnabledWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion +- (void)readAttributeViewportWithCompletion:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))completion { - using TypeInfo = CameraAvStreamManagement::Attributes::AutoISOEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::Viewport::TypeInfo; [self.device _readKnownAttributeWithEndpointID:self.endpointID clusterID:@(TypeInfo::GetClusterId()) attributeID:@(TypeInfo::GetAttributeId()) @@ -99691,11 +99467,11 @@ - (void)readAttributeAutoISOEnabledWithCompletion:(void (^)(NSNumber * _Nullable completion:completion]; } -- (void)writeAttributeAutoISOEnabledWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion +- (void)writeAttributeViewportWithValue:(MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull)value completion:(MTRStatusCompletion)completion { - [self writeAttributeAutoISOEnabledWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; + [self writeAttributeViewportWithValue:(MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull) value params:nil completion:completion]; } -- (void)writeAttributeAutoISOEnabledWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion +- (void)writeAttributeViewportWithValue:(MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion { // Make a copy of params before we go async. params = [params copy]; @@ -99710,51 +99486,18 @@ - (void)writeAttributeAutoISOEnabledWithValue:(NSNumber * _Nonnull)value params: } ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::AutoISOEnabled::TypeInfo; + using TypeInfo = CameraAvStreamManagement::Attributes::Viewport::TypeInfo; TypeInfo::Type cppValue; - cppValue = value.boolValue; + cppValue.x1 = value.x1.unsignedShortValue; + cppValue.y1 = value.y1.unsignedShortValue; + cppValue.x2 = value.x2.unsignedShortValue; + cppValue.y2 = value.y2.unsignedShortValue; chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); std::move(*bridge).DispatchAction(self.device); } -- (void)subscribeAttributeAutoISOEnabledWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler -{ - using TypeInfo = CameraAvStreamManagement::Attributes::AutoISOEnabled::TypeInfo; - [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:params - queue:self.callbackQueue - reportHandler:reportHandler - subscriptionEstablished:subscriptionEstablished]; -} - -+ (void)readAttributeAutoISOEnabledWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::AutoISOEnabled::TypeInfo; - [clusterStateCacheContainer - _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) - clusterID:TypeInfo::GetClusterId() - attributeID:TypeInfo::GetAttributeId() - queue:queue - completion:completion]; -} - -- (void)readAttributeViewportWithCompletion:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::Viewport::TypeInfo; - [self.device _readKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:nil - queue:self.callbackQueue - completion:completion]; -} - - (void)subscribeAttributeViewportWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error))reportHandler @@ -99919,34 +99662,6 @@ - (void)readAttributeSpeakerMaxLevelWithCompletion:(void (^)(NSNumber * _Nullabl completion:completion]; } -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeSpeakerMaxLevelWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMaxLevel::TypeInfo; - TypeInfo::Type cppValue; - cppValue = value.unsignedCharValue; - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - - (void)subscribeAttributeSpeakerMaxLevelWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -99983,34 +99698,6 @@ - (void)readAttributeSpeakerMinLevelWithCompletion:(void (^)(NSNumber * _Nullabl completion:completion]; } -- (void)writeAttributeSpeakerMinLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeSpeakerMinLevelWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeSpeakerMinLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::SpeakerMinLevel::TypeInfo; - TypeInfo::Type cppValue; - cppValue = value.unsignedCharValue; - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - - (void)subscribeAttributeSpeakerMinLevelWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -100175,34 +99862,6 @@ - (void)readAttributeMicrophoneMaxLevelWithCompletion:(void (^)(NSNumber * _Null completion:completion]; } -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeMicrophoneMaxLevelWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::MicrophoneMaxLevel::TypeInfo; - TypeInfo::Type cppValue; - cppValue = value.unsignedCharValue; - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - - (void)subscribeAttributeMicrophoneMaxLevelWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -100239,34 +99898,6 @@ - (void)readAttributeMicrophoneMinLevelWithCompletion:(void (^)(NSNumber * _Null completion:completion]; } -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeMicrophoneMinLevelWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::MicrophoneMinLevel::TypeInfo; - TypeInfo::Type cppValue; - cppValue = value.unsignedCharValue; - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - - (void)subscribeAttributeMicrophoneMinLevelWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -100367,6 +99998,34 @@ - (void)readAttributeImageRotationWithCompletion:(void (^)(NSNumber * _Nullable completion:completion]; } +- (void)writeAttributeImageRotationWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion +{ + [self writeAttributeImageRotationWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; +} +- (void)writeAttributeImageRotationWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion +{ + // Make a copy of params before we go async. + params = [params copy]; + value = [value copy]; + + auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { + chip::Optional timedWriteTimeout; + if (params != nil) { + if (params.timedWriteTimeout != nil){ + timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); + } + } + + ListFreer listFreer; + using TypeInfo = CameraAvStreamManagement::Attributes::ImageRotation::TypeInfo; + TypeInfo::Type cppValue; + cppValue = value.unsignedShortValue; + + chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); + return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); + std::move(*bridge).DispatchAction(self.device); +} + - (void)subscribeAttributeImageRotationWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -100403,6 +100062,34 @@ - (void)readAttributeImageFlipHorizontalWithCompletion:(void (^)(NSNumber * _Nul completion:completion]; } +- (void)writeAttributeImageFlipHorizontalWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion +{ + [self writeAttributeImageFlipHorizontalWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; +} +- (void)writeAttributeImageFlipHorizontalWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion +{ + // Make a copy of params before we go async. + params = [params copy]; + value = [value copy]; + + auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { + chip::Optional timedWriteTimeout; + if (params != nil) { + if (params.timedWriteTimeout != nil){ + timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); + } + } + + ListFreer listFreer; + using TypeInfo = CameraAvStreamManagement::Attributes::ImageFlipHorizontal::TypeInfo; + TypeInfo::Type cppValue; + cppValue = value.boolValue; + + chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); + return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); + std::move(*bridge).DispatchAction(self.device); +} + - (void)subscribeAttributeImageFlipHorizontalWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -100439,6 +100126,34 @@ - (void)readAttributeImageFlipVerticalWithCompletion:(void (^)(NSNumber * _Nulla completion:completion]; } +- (void)writeAttributeImageFlipVerticalWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion +{ + [self writeAttributeImageFlipVerticalWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; +} +- (void)writeAttributeImageFlipVerticalWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion +{ + // Make a copy of params before we go async. + params = [params copy]; + value = [value copy]; + + auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { + chip::Optional timedWriteTimeout; + if (params != nil) { + if (params.timedWriteTimeout != nil){ + timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); + } + } + + ListFreer listFreer; + using TypeInfo = CameraAvStreamManagement::Attributes::ImageFlipVertical::TypeInfo; + TypeInfo::Type cppValue; + cppValue = value.boolValue; + + chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); + return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); + std::move(*bridge).DispatchAction(self.device); +} + - (void)subscribeAttributeImageFlipVerticalWithParams:(MTRSubscribeParams * _Nonnull)params subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler @@ -100720,70 +100435,6 @@ + (void)readAttributeStatusLightBrightnessWithClusterStateCache:(MTRClusterState completion:completion]; } -- (void)readAttributeDepthSensorStatusWithCompletion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::DepthSensorStatus::TypeInfo; - [self.device _readKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:nil - queue:self.callbackQueue - completion:completion]; -} - -- (void)writeAttributeDepthSensorStatusWithValue:(NSNumber * _Nonnull)value completion:(MTRStatusCompletion)completion -{ - [self writeAttributeDepthSensorStatusWithValue:(NSNumber * _Nonnull) value params:nil completion:completion]; -} -- (void)writeAttributeDepthSensorStatusWithValue:(NSNumber * _Nonnull)value params:(MTRWriteParams * _Nullable)params completion:(MTRStatusCompletion)completion -{ - // Make a copy of params before we go async. - params = [params copy]; - value = [value copy]; - - auto * bridge = new MTRDefaultSuccessCallbackBridge(self.callbackQueue, ^(id _Nullable ignored, NSError * _Nullable error) { completion(error); }, ^(ExchangeManager & exchangeManager, const SessionHandle & session, DefaultSuccessCallbackType successCb, MTRErrorCallback failureCb, MTRCallbackBridgeBase * bridge) { - chip::Optional timedWriteTimeout; - if (params != nil) { - if (params.timedWriteTimeout != nil){ - timedWriteTimeout.SetValue(params.timedWriteTimeout.unsignedShortValue); - } - } - - ListFreer listFreer; - using TypeInfo = CameraAvStreamManagement::Attributes::DepthSensorStatus::TypeInfo; - TypeInfo::Type cppValue; - cppValue = static_cast>(value.unsignedCharValue); - - chip::Controller::ClusterBase cppCluster(exchangeManager, session, self.endpointID.unsignedShortValue); - return cppCluster.WriteAttribute(cppValue, bridge, successCb, failureCb, timedWriteTimeout); }); - std::move(*bridge).DispatchAction(self.device); -} - -- (void)subscribeAttributeDepthSensorStatusWithParams:(MTRSubscribeParams * _Nonnull)params - subscriptionEstablished:(MTRSubscriptionEstablishedHandler _Nullable)subscriptionEstablished - reportHandler:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))reportHandler -{ - using TypeInfo = CameraAvStreamManagement::Attributes::DepthSensorStatus::TypeInfo; - [self.device _subscribeToKnownAttributeWithEndpointID:self.endpointID - clusterID:@(TypeInfo::GetClusterId()) - attributeID:@(TypeInfo::GetAttributeId()) - params:params - queue:self.callbackQueue - reportHandler:reportHandler - subscriptionEstablished:subscriptionEstablished]; -} - -+ (void)readAttributeDepthSensorStatusWithClusterStateCache:(MTRClusterStateCacheContainer *)clusterStateCacheContainer endpoint:(NSNumber *)endpoint queue:(dispatch_queue_t)queue completion:(void (^)(NSNumber * _Nullable value, NSError * _Nullable error))completion -{ - using TypeInfo = CameraAvStreamManagement::Attributes::DepthSensorStatus::TypeInfo; - [clusterStateCacheContainer - _readKnownCachedAttributeWithEndpointID:static_cast([endpoint unsignedShortValue]) - clusterID:TypeInfo::GetClusterId() - attributeID:TypeInfo::GetAttributeId() - queue:queue - completion:completion]; -} - - (void)readAttributeGeneratedCommandListWithCompletion:(void (^)(NSArray * _Nullable value, NSError * _Nullable error))completion { using TypeInfo = CameraAvStreamManagement::Attributes::GeneratedCommandList::TypeInfo; diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h b/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h index a5e2650097b105..e1f194c9916d15 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRClusterConstants.h @@ -4661,27 +4661,23 @@ typedef NS_ENUM(uint32_t, MTRAttributeIDType) { MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeHardPrivacyModeOnID MTR_PROVISIONALLY_AVAILABLE = 0x00000017, MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeNightVisionID MTR_PROVISIONALLY_AVAILABLE = 0x00000018, MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeNightVisionIllumID MTR_PROVISIONALLY_AVAILABLE = 0x00000019, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAWBEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000001A, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoShutterSpeedEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000001B, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoISOEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000001C, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeViewportID MTR_PROVISIONALLY_AVAILABLE = 0x0000001D, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMutedID MTR_PROVISIONALLY_AVAILABLE = 0x0000001E, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerVolumeLevelID MTR_PROVISIONALLY_AVAILABLE = 0x0000001F, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMaxLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000020, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMinLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000021, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMutedID MTR_PROVISIONALLY_AVAILABLE = 0x00000022, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneVolumeLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000023, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMaxLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000024, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMinLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000025, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneAGCEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000026, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageRotationID MTR_PROVISIONALLY_AVAILABLE = 0x00000027, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipHorizontalID MTR_PROVISIONALLY_AVAILABLE = 0x00000028, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipVerticalID MTR_PROVISIONALLY_AVAILABLE = 0x00000029, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeLocalVideoRecordingEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000002A, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeLocalSnapshotRecordingEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000002B, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeStatusLightEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x0000002C, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeStatusLightBrightnessID MTR_PROVISIONALLY_AVAILABLE = 0x0000002D, - MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeDepthSensorStatusID MTR_PROVISIONALLY_AVAILABLE = 0x0000002E, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeViewportID MTR_PROVISIONALLY_AVAILABLE = 0x0000001A, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMutedID MTR_PROVISIONALLY_AVAILABLE = 0x0000001B, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerVolumeLevelID MTR_PROVISIONALLY_AVAILABLE = 0x0000001C, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMaxLevelID MTR_PROVISIONALLY_AVAILABLE = 0x0000001D, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMinLevelID MTR_PROVISIONALLY_AVAILABLE = 0x0000001E, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMutedID MTR_PROVISIONALLY_AVAILABLE = 0x0000001F, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneVolumeLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000020, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMaxLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000021, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMinLevelID MTR_PROVISIONALLY_AVAILABLE = 0x00000022, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneAGCEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000023, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageRotationID MTR_PROVISIONALLY_AVAILABLE = 0x00000024, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipHorizontalID MTR_PROVISIONALLY_AVAILABLE = 0x00000025, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipVerticalID MTR_PROVISIONALLY_AVAILABLE = 0x00000026, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeLocalVideoRecordingEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000027, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeLocalSnapshotRecordingEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000028, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeStatusLightEnabledID MTR_PROVISIONALLY_AVAILABLE = 0x00000029, + MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeStatusLightBrightnessID MTR_PROVISIONALLY_AVAILABLE = 0x0000002A, MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeGeneratedCommandListID MTR_PROVISIONALLY_AVAILABLE = MTRAttributeIDTypeGlobalAttributeGeneratedCommandListID, MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAcceptedCommandListID MTR_PROVISIONALLY_AVAILABLE = MTRAttributeIDTypeGlobalAttributeAcceptedCommandListID, MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAttributeListID MTR_PROVISIONALLY_AVAILABLE = MTRAttributeIDTypeGlobalAttributeAttributeListID, @@ -6925,10 +6921,6 @@ typedef NS_ENUM(uint32_t, MTRCommandIDType) { MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetStreamPrioritiesID MTR_PROVISIONALLY_AVAILABLE = 0x0000000A, MTRCommandIDTypeClusterCameraAVStreamManagementCommandCaptureSnapshotID MTR_PROVISIONALLY_AVAILABLE = 0x0000000B, MTRCommandIDTypeClusterCameraAVStreamManagementCommandCaptureSnapshotResponseID MTR_PROVISIONALLY_AVAILABLE = 0x0000000C, - MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetViewportID MTR_PROVISIONALLY_AVAILABLE = 0x0000000D, - MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetImageRotationID MTR_PROVISIONALLY_AVAILABLE = 0x0000000E, - MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetImageFlipHorizontalID MTR_PROVISIONALLY_AVAILABLE = 0x0000000F, - MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetImageFlipVerticalID MTR_PROVISIONALLY_AVAILABLE = 0x00000010, // Cluster WebRTCTransportProvider commands MTRCommandIDTypeClusterWebRTCTransportProviderCommandSolicitOfferID MTR_PROVISIONALLY_AVAILABLE = 0x00000001, diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRClusterNames.mm b/src/darwin/Framework/CHIP/zap-generated/MTRClusterNames.mm index ef41bc6487b379..18d0151955242e 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRClusterNames.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRClusterNames.mm @@ -7831,18 +7831,6 @@ result = @"NightVisionIllum"; break; - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAWBEnabledID: - result = @"AWBEnabled"; - break; - - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoShutterSpeedEnabledID: - result = @"AutoShutterSpeedEnabled"; - break; - - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoISOEnabledID: - result = @"AutoISOEnabled"; - break; - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeViewportID: result = @"Viewport"; break; @@ -7911,10 +7899,6 @@ result = @"StatusLightBrightness"; break; - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeDepthSensorStatusID: - result = @"DepthSensorStatus"; - break; - case MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeGeneratedCommandListID: result = @"GeneratedCommandList"; break; @@ -10832,22 +10816,6 @@ result = @"CaptureSnapshot"; break; - case MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetViewportID: - result = @"SetViewport"; - break; - - case MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetImageRotationID: - result = @"SetImageRotation"; - break; - - case MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetImageFlipHorizontalID: - result = @"SetImageFlipHorizontal"; - break; - - case MTRCommandIDTypeClusterCameraAVStreamManagementCommandSetImageFlipVerticalID: - result = @"SetImageFlipVertical"; - break; - default: result = [NSString stringWithFormat:@"", commandID]; break; diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRClusters.h b/src/darwin/Framework/CHIP/zap-generated/MTRClusters.h index 111cab13f8af49..7c7c93d027a715 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRClusters.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRClusters.h @@ -6643,10 +6643,6 @@ MTR_PROVISIONALLY_AVAILABLE - (void)snapshotStreamDeallocateWithParams:(MTRCameraAVStreamManagementClusterSnapshotStreamDeallocateParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)setStreamPrioritiesWithParams:(MTRCameraAVStreamManagementClusterSetStreamPrioritiesParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (void)captureSnapshotWithParams:(MTRCameraAVStreamManagementClusterCaptureSnapshotParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)setViewportWithParams:(MTRCameraAVStreamManagementClusterSetViewportParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)setImageRotationWithParams:(MTRCameraAVStreamManagementClusterSetImageRotationParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)setImageFlipHorizontalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; -- (void)setImageFlipVerticalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams *)params expectedValues:(NSArray *> * _Nullable)expectedDataValueDictionaries expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeMaxConcurrentVideoEncodersWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; @@ -6712,19 +6708,9 @@ MTR_PROVISIONALLY_AVAILABLE - (void)writeAttributeNightVisionIllumWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeNightVisionIllumWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (NSDictionary * _Nullable)readAttributeAWBEnabledWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAWBEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAWBEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - -- (NSDictionary * _Nullable)readAttributeAutoShutterSpeedEnabledWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - -- (NSDictionary * _Nullable)readAttributeAutoISOEnabledWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoISOEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeAutoISOEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - - (NSDictionary * _Nullable)readAttributeViewportWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeViewportWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeViewportWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeSpeakerMutedWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeSpeakerMutedWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; @@ -6735,12 +6721,8 @@ MTR_PROVISIONALLY_AVAILABLE - (void)writeAttributeSpeakerVolumeLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeSpeakerMaxLevelWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeSpeakerMinLevelWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeSpeakerMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeMicrophoneMutedWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeMicrophoneMutedWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; @@ -6751,22 +6733,24 @@ MTR_PROVISIONALLY_AVAILABLE - (void)writeAttributeMicrophoneVolumeLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeMicrophoneMaxLevelWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeMicrophoneMinLevelWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeMicrophoneAGCEnabledWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeMicrophoneAGCEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeMicrophoneAGCEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeImageRotationWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageRotationWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageRotationWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeImageFlipHorizontalWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipHorizontalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipHorizontalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeImageFlipVerticalWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipVerticalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; +- (void)writeAttributeImageFlipVerticalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeLocalVideoRecordingEnabledWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeLocalVideoRecordingEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; @@ -6784,10 +6768,6 @@ MTR_PROVISIONALLY_AVAILABLE - (void)writeAttributeStatusLightBrightnessWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; - (void)writeAttributeStatusLightBrightnessWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (NSDictionary * _Nullable)readAttributeDepthSensorStatusWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeDepthSensorStatusWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs MTR_PROVISIONALLY_AVAILABLE; -- (void)writeAttributeDepthSensorStatusWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - - (NSDictionary * _Nullable)readAttributeGeneratedCommandListWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; - (NSDictionary * _Nullable)readAttributeAcceptedCommandListWithParams:(MTRReadParams * _Nullable)params MTR_PROVISIONALLY_AVAILABLE; diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRClusters.mm b/src/darwin/Framework/CHIP/zap-generated/MTRClusters.mm index b473aed7020e46..656983754cae96 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRClusters.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRClusters.mm @@ -19316,114 +19316,6 @@ - (void)captureSnapshotWithParams:(MTRCameraAVStreamManagementClusterCaptureSnap completion:responseHandler]; } -- (void)setViewportWithParams:(MTRCameraAVStreamManagementClusterSetViewportParams *)params expectedValues:(NSArray *> * _Nullable)expectedValues expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetViewportParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetViewport::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - expectedValues:expectedValues - expectedValueInterval:expectedValueIntervalMs - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} - -- (void)setImageRotationWithParams:(MTRCameraAVStreamManagementClusterSetImageRotationParams *)params expectedValues:(NSArray *> * _Nullable)expectedValues expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetImageRotationParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetImageRotation::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - expectedValues:expectedValues - expectedValueInterval:expectedValueIntervalMs - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} - -- (void)setImageFlipHorizontalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams *)params expectedValues:(NSArray *> * _Nullable)expectedValues expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - expectedValues:expectedValues - expectedValueInterval:expectedValueIntervalMs - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} - -- (void)setImageFlipVerticalWithParams:(MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams *)params expectedValues:(NSArray *> * _Nullable)expectedValues expectedValueInterval:(NSNumber * _Nullable)expectedValueIntervalMs completion:(MTRStatusCompletion)completion -{ - if (params == nil) { - params = [[MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams - alloc] init]; - } - - auto responseHandler = ^(id _Nullable response, NSError * _Nullable error) { - completion(error); - }; - - auto * timedInvokeTimeoutMs = params.timedInvokeTimeoutMs; - - using RequestType = CameraAvStreamManagement::Commands::SetImageFlipVertical::Type; - [self.device _invokeKnownCommandWithEndpointID:self.endpointID - clusterID:@(RequestType::GetClusterId()) - commandID:@(RequestType::GetCommandId()) - commandPayload:params - expectedValues:expectedValues - expectedValueInterval:expectedValueIntervalMs - timedInvokeTimeout:timedInvokeTimeoutMs - serverSideProcessingTimeout:params.serverSideProcessingTimeout - responseClass:nil - queue:self.callbackQueue - completion:responseHandler]; -} - - (NSDictionary * _Nullable)readAttributeMaxConcurrentVideoEncodersWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMaxConcurrentVideoEncodersID) params:params]; @@ -19620,57 +19512,20 @@ - (void)writeAttributeNightVisionIllumWithValue:(NSDictionary *) [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeNightVisionIllumID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; } -- (NSDictionary * _Nullable)readAttributeAWBEnabledWithParams:(MTRReadParams * _Nullable)params -{ - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAWBEnabledID) params:params]; -} - -- (void)writeAttributeAWBEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeAWBEnabledWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeAWBEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAWBEnabledID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - -- (NSDictionary * _Nullable)readAttributeAutoShutterSpeedEnabledWithParams:(MTRReadParams * _Nullable)params -{ - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoShutterSpeedEnabledID) params:params]; -} - -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeAutoShutterSpeedEnabledWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeAutoShutterSpeedEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoShutterSpeedEnabledID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - -- (NSDictionary * _Nullable)readAttributeAutoISOEnabledWithParams:(MTRReadParams * _Nullable)params +- (NSDictionary * _Nullable)readAttributeViewportWithParams:(MTRReadParams * _Nullable)params { - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoISOEnabledID) params:params]; + return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeViewportID) params:params]; } -- (void)writeAttributeAutoISOEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs +- (void)writeAttributeViewportWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs { - [self writeAttributeAutoISOEnabledWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; + [self writeAttributeViewportWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; } -- (void)writeAttributeAutoISOEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params +- (void)writeAttributeViewportWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params { NSNumber * timedWriteTimeout = params.timedWriteTimeout; - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeAutoISOEnabledID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - -- (NSDictionary * _Nullable)readAttributeViewportWithParams:(MTRReadParams * _Nullable)params -{ - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeViewportID) params:params]; + [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeViewportID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; } - (NSDictionary * _Nullable)readAttributeSpeakerMutedWithParams:(MTRReadParams * _Nullable)params @@ -19710,33 +19565,11 @@ - (void)writeAttributeSpeakerVolumeLevelWithValue:(NSDictionary return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMaxLevelID) params:params]; } -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeSpeakerMaxLevelWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeSpeakerMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMaxLevelID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - - (NSDictionary * _Nullable)readAttributeSpeakerMinLevelWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMinLevelID) params:params]; } -- (void)writeAttributeSpeakerMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeSpeakerMinLevelWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeSpeakerMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeSpeakerMinLevelID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - - (NSDictionary * _Nullable)readAttributeMicrophoneMutedWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMutedID) params:params]; @@ -19774,33 +19607,11 @@ - (void)writeAttributeMicrophoneVolumeLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeMicrophoneMaxLevelWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeMicrophoneMaxLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMaxLevelID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - - (NSDictionary * _Nullable)readAttributeMicrophoneMinLevelWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMinLevelID) params:params]; } -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeMicrophoneMinLevelWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeMicrophoneMinLevelWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneMinLevelID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - - (NSDictionary * _Nullable)readAttributeMicrophoneAGCEnabledWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeMicrophoneAGCEnabledID) params:params]; @@ -19822,16 +19633,49 @@ - (void)writeAttributeMicrophoneAGCEnabledWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs +{ + [self writeAttributeImageRotationWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; +} +- (void)writeAttributeImageRotationWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params +{ + NSNumber * timedWriteTimeout = params.timedWriteTimeout; + + [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageRotationID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; +} + - (NSDictionary * _Nullable)readAttributeImageFlipHorizontalWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipHorizontalID) params:params]; } +- (void)writeAttributeImageFlipHorizontalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs +{ + [self writeAttributeImageFlipHorizontalWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; +} +- (void)writeAttributeImageFlipHorizontalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params +{ + NSNumber * timedWriteTimeout = params.timedWriteTimeout; + + [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipHorizontalID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; +} + - (NSDictionary * _Nullable)readAttributeImageFlipVerticalWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipVerticalID) params:params]; } +- (void)writeAttributeImageFlipVerticalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs +{ + [self writeAttributeImageFlipVerticalWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; +} +- (void)writeAttributeImageFlipVerticalWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params +{ + NSNumber * timedWriteTimeout = params.timedWriteTimeout; + + [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeImageFlipVerticalID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; +} + - (NSDictionary * _Nullable)readAttributeLocalVideoRecordingEnabledWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeLocalVideoRecordingEnabledID) params:params]; @@ -19896,22 +19740,6 @@ - (void)writeAttributeStatusLightBrightnessWithValue:(NSDictionary * _Nullable)readAttributeDepthSensorStatusWithParams:(MTRReadParams * _Nullable)params -{ - return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeDepthSensorStatusID) params:params]; -} - -- (void)writeAttributeDepthSensorStatusWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs -{ - [self writeAttributeDepthSensorStatusWithValue:dataValueDictionary expectedValueInterval:expectedValueIntervalMs params:nil]; -} -- (void)writeAttributeDepthSensorStatusWithValue:(NSDictionary *)dataValueDictionary expectedValueInterval:(NSNumber *)expectedValueIntervalMs params:(MTRWriteParams * _Nullable)params -{ - NSNumber * timedWriteTimeout = params.timedWriteTimeout; - - [self.device writeAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeDepthSensorStatusID) value:dataValueDictionary expectedValueInterval:expectedValueIntervalMs timedWriteTimeout:timedWriteTimeout]; -} - - (NSDictionary * _Nullable)readAttributeGeneratedCommandListWithParams:(MTRReadParams * _Nullable)params { return [self.device readAttributeWithEndpointID:self.endpointID clusterID:@(MTRClusterIDTypeCameraAVStreamManagementID) attributeID:@(MTRAttributeIDTypeClusterCameraAVStreamManagementAttributeGeneratedCommandListID) params:params]; diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.h b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.h index 6a5580c95b88db..c6dbb8e975f8f3 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.h @@ -11395,126 +11395,6 @@ MTR_PROVISIONALLY_AVAILABLE error:(NSError * __autoreleasing *)error MTR_PROVISIONALLY_AVAILABLE; @end -MTR_PROVISIONALLY_AVAILABLE -@interface MTRCameraAVStreamManagementClusterSetViewportParams : NSObject - -@property (nonatomic, copy) MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull viewport MTR_PROVISIONALLY_AVAILABLE; -/** - * Controls whether the command is a timed command (using Timed Invoke). - * - * If nil (the default value), a regular invoke is done for commands that do - * not require a timed invoke and a timed invoke with some default timed request - * timeout is done for commands that require a timed invoke. - * - * If not nil, a timed invoke is done, with the provided value used as the timed - * request timeout. The value should be chosen small enough to provide the - * desired security properties but large enough that it will allow a round-trip - * from the sever to the client (for the status response and actual invoke - * request) within the timeout window. - * - */ -@property (nonatomic, copy, nullable) NSNumber * timedInvokeTimeoutMs; - -/** - * Controls how much time, in seconds, we will allow for the server to process the command. - * - * The command will then time out if that much time, plus an allowance for retransmits due to network failures, passes. - * - * If nil, the framework will try to select an appropriate timeout value itself. - */ -@property (nonatomic, copy, nullable) NSNumber * serverSideProcessingTimeout; -@end - -MTR_PROVISIONALLY_AVAILABLE -@interface MTRCameraAVStreamManagementClusterSetImageRotationParams : NSObject - -@property (nonatomic, copy) NSNumber * _Nonnull angle MTR_PROVISIONALLY_AVAILABLE; -/** - * Controls whether the command is a timed command (using Timed Invoke). - * - * If nil (the default value), a regular invoke is done for commands that do - * not require a timed invoke and a timed invoke with some default timed request - * timeout is done for commands that require a timed invoke. - * - * If not nil, a timed invoke is done, with the provided value used as the timed - * request timeout. The value should be chosen small enough to provide the - * desired security properties but large enough that it will allow a round-trip - * from the sever to the client (for the status response and actual invoke - * request) within the timeout window. - * - */ -@property (nonatomic, copy, nullable) NSNumber * timedInvokeTimeoutMs; - -/** - * Controls how much time, in seconds, we will allow for the server to process the command. - * - * The command will then time out if that much time, plus an allowance for retransmits due to network failures, passes. - * - * If nil, the framework will try to select an appropriate timeout value itself. - */ -@property (nonatomic, copy, nullable) NSNumber * serverSideProcessingTimeout; -@end - -MTR_PROVISIONALLY_AVAILABLE -@interface MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams : NSObject - -@property (nonatomic, copy) NSNumber * _Nonnull enabled MTR_PROVISIONALLY_AVAILABLE; -/** - * Controls whether the command is a timed command (using Timed Invoke). - * - * If nil (the default value), a regular invoke is done for commands that do - * not require a timed invoke and a timed invoke with some default timed request - * timeout is done for commands that require a timed invoke. - * - * If not nil, a timed invoke is done, with the provided value used as the timed - * request timeout. The value should be chosen small enough to provide the - * desired security properties but large enough that it will allow a round-trip - * from the sever to the client (for the status response and actual invoke - * request) within the timeout window. - * - */ -@property (nonatomic, copy, nullable) NSNumber * timedInvokeTimeoutMs; - -/** - * Controls how much time, in seconds, we will allow for the server to process the command. - * - * The command will then time out if that much time, plus an allowance for retransmits due to network failures, passes. - * - * If nil, the framework will try to select an appropriate timeout value itself. - */ -@property (nonatomic, copy, nullable) NSNumber * serverSideProcessingTimeout; -@end - -MTR_PROVISIONALLY_AVAILABLE -@interface MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams : NSObject - -@property (nonatomic, copy) NSNumber * _Nonnull enabled MTR_PROVISIONALLY_AVAILABLE; -/** - * Controls whether the command is a timed command (using Timed Invoke). - * - * If nil (the default value), a regular invoke is done for commands that do - * not require a timed invoke and a timed invoke with some default timed request - * timeout is done for commands that require a timed invoke. - * - * If not nil, a timed invoke is done, with the provided value used as the timed - * request timeout. The value should be chosen small enough to provide the - * desired security properties but large enough that it will allow a round-trip - * from the sever to the client (for the status response and actual invoke - * request) within the timeout window. - * - */ -@property (nonatomic, copy, nullable) NSNumber * timedInvokeTimeoutMs; - -/** - * Controls how much time, in seconds, we will allow for the server to process the command. - * - * The command will then time out if that much time, plus an allowance for retransmits due to network failures, passes. - * - * If nil, the framework will try to select an appropriate timeout value itself. - */ -@property (nonatomic, copy, nullable) NSNumber * serverSideProcessingTimeout; -@end - MTR_PROVISIONALLY_AVAILABLE @interface MTRWebRTCTransportProviderClusterSolicitOfferParams : NSObject diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm index 2010627d89e7db..b737f253cbd64b 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm +++ b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloadsObjc.mm @@ -33160,325 +33160,6 @@ - (CHIP_ERROR)_setFieldsFromDecodableStruct:(const chip::app::Clusters::CameraAv @end -@implementation MTRCameraAVStreamManagementClusterSetViewportParams -- (instancetype)init -{ - if (self = [super init]) { - - _viewport = [MTRCameraAVStreamManagementClusterViewportStruct new]; - _timedInvokeTimeoutMs = nil; - _serverSideProcessingTimeout = nil; - } - return self; -} - -- (id)copyWithZone:(NSZone * _Nullable)zone; -{ - auto other = [[MTRCameraAVStreamManagementClusterSetViewportParams alloc] init]; - - other.viewport = self.viewport; - other.timedInvokeTimeoutMs = self.timedInvokeTimeoutMs; - other.serverSideProcessingTimeout = self.serverSideProcessingTimeout; - - return other; -} - -- (NSString *)description -{ - NSString * descriptionString = [NSString stringWithFormat:@"<%@: viewport:%@; >", NSStringFromClass([self class]), _viewport]; - return descriptionString; -} - -@end - -@implementation MTRCameraAVStreamManagementClusterSetViewportParams (InternalMethods) - -- (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader -{ - chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Type encodableStruct; - ListFreer listFreer; - { - encodableStruct.viewport.x1 = self.viewport.x1.unsignedShortValue; - encodableStruct.viewport.y1 = self.viewport.y1.unsignedShortValue; - encodableStruct.viewport.x2 = self.viewport.x2.unsignedShortValue; - encodableStruct.viewport.y2 = self.viewport.y2.unsignedShortValue; - } - - auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); - if (buffer.IsNull()) { - return CHIP_ERROR_NO_MEMORY; - } - - chip::System::PacketBufferTLVWriter writer; - // Commands never need chained buffers, since they cannot be chunked. - writer.Init(std::move(buffer), /* useChainedBuffers = */ false); - - ReturnErrorOnFailure(chip::app::DataModel::Encode(writer, chip::TLV::AnonymousTag(), encodableStruct)); - - ReturnErrorOnFailure(writer.Finalize(&buffer)); - - reader.Init(std::move(buffer)); - return reader.Next(chip::TLV::kTLVType_Structure, chip::TLV::AnonymousTag()); -} - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error -{ - chip::System::PacketBufferTLVReader reader; - CHIP_ERROR err = [self _encodeToTLVReader:reader]; - if (err != CHIP_NO_ERROR) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:err]; - } - return nil; - } - - auto decodedObj = MTRDecodeDataValueDictionaryFromCHIPTLV(&reader); - if (decodedObj == nil) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; - } - } - return decodedObj; -} -@end - -@implementation MTRCameraAVStreamManagementClusterSetImageRotationParams -- (instancetype)init -{ - if (self = [super init]) { - - _angle = @(0); - _timedInvokeTimeoutMs = nil; - _serverSideProcessingTimeout = nil; - } - return self; -} - -- (id)copyWithZone:(NSZone * _Nullable)zone; -{ - auto other = [[MTRCameraAVStreamManagementClusterSetImageRotationParams alloc] init]; - - other.angle = self.angle; - other.timedInvokeTimeoutMs = self.timedInvokeTimeoutMs; - other.serverSideProcessingTimeout = self.serverSideProcessingTimeout; - - return other; -} - -- (NSString *)description -{ - NSString * descriptionString = [NSString stringWithFormat:@"<%@: angle:%@; >", NSStringFromClass([self class]), _angle]; - return descriptionString; -} - -@end - -@implementation MTRCameraAVStreamManagementClusterSetImageRotationParams (InternalMethods) - -- (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader -{ - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Type encodableStruct; - ListFreer listFreer; - { - encodableStruct.angle = self.angle.unsignedShortValue; - } - - auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); - if (buffer.IsNull()) { - return CHIP_ERROR_NO_MEMORY; - } - - chip::System::PacketBufferTLVWriter writer; - // Commands never need chained buffers, since they cannot be chunked. - writer.Init(std::move(buffer), /* useChainedBuffers = */ false); - - ReturnErrorOnFailure(chip::app::DataModel::Encode(writer, chip::TLV::AnonymousTag(), encodableStruct)); - - ReturnErrorOnFailure(writer.Finalize(&buffer)); - - reader.Init(std::move(buffer)); - return reader.Next(chip::TLV::kTLVType_Structure, chip::TLV::AnonymousTag()); -} - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error -{ - chip::System::PacketBufferTLVReader reader; - CHIP_ERROR err = [self _encodeToTLVReader:reader]; - if (err != CHIP_NO_ERROR) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:err]; - } - return nil; - } - - auto decodedObj = MTRDecodeDataValueDictionaryFromCHIPTLV(&reader); - if (decodedObj == nil) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; - } - } - return decodedObj; -} -@end - -@implementation MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams -- (instancetype)init -{ - if (self = [super init]) { - - _enabled = @(0); - _timedInvokeTimeoutMs = nil; - _serverSideProcessingTimeout = nil; - } - return self; -} - -- (id)copyWithZone:(NSZone * _Nullable)zone; -{ - auto other = [[MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams alloc] init]; - - other.enabled = self.enabled; - other.timedInvokeTimeoutMs = self.timedInvokeTimeoutMs; - other.serverSideProcessingTimeout = self.serverSideProcessingTimeout; - - return other; -} - -- (NSString *)description -{ - NSString * descriptionString = [NSString stringWithFormat:@"<%@: enabled:%@; >", NSStringFromClass([self class]), _enabled]; - return descriptionString; -} - -@end - -@implementation MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams (InternalMethods) - -- (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader -{ - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Type encodableStruct; - ListFreer listFreer; - { - encodableStruct.enabled = self.enabled.boolValue; - } - - auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); - if (buffer.IsNull()) { - return CHIP_ERROR_NO_MEMORY; - } - - chip::System::PacketBufferTLVWriter writer; - // Commands never need chained buffers, since they cannot be chunked. - writer.Init(std::move(buffer), /* useChainedBuffers = */ false); - - ReturnErrorOnFailure(chip::app::DataModel::Encode(writer, chip::TLV::AnonymousTag(), encodableStruct)); - - ReturnErrorOnFailure(writer.Finalize(&buffer)); - - reader.Init(std::move(buffer)); - return reader.Next(chip::TLV::kTLVType_Structure, chip::TLV::AnonymousTag()); -} - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error -{ - chip::System::PacketBufferTLVReader reader; - CHIP_ERROR err = [self _encodeToTLVReader:reader]; - if (err != CHIP_NO_ERROR) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:err]; - } - return nil; - } - - auto decodedObj = MTRDecodeDataValueDictionaryFromCHIPTLV(&reader); - if (decodedObj == nil) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; - } - } - return decodedObj; -} -@end - -@implementation MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams -- (instancetype)init -{ - if (self = [super init]) { - - _enabled = @(0); - _timedInvokeTimeoutMs = nil; - _serverSideProcessingTimeout = nil; - } - return self; -} - -- (id)copyWithZone:(NSZone * _Nullable)zone; -{ - auto other = [[MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams alloc] init]; - - other.enabled = self.enabled; - other.timedInvokeTimeoutMs = self.timedInvokeTimeoutMs; - other.serverSideProcessingTimeout = self.serverSideProcessingTimeout; - - return other; -} - -- (NSString *)description -{ - NSString * descriptionString = [NSString stringWithFormat:@"<%@: enabled:%@; >", NSStringFromClass([self class]), _enabled]; - return descriptionString; -} - -@end - -@implementation MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams (InternalMethods) - -- (CHIP_ERROR)_encodeToTLVReader:(chip::System::PacketBufferTLVReader &)reader -{ - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Type encodableStruct; - ListFreer listFreer; - { - encodableStruct.enabled = self.enabled.boolValue; - } - - auto buffer = chip::System::PacketBufferHandle::New(chip::System::PacketBuffer::kMaxSizeWithoutReserve, 0); - if (buffer.IsNull()) { - return CHIP_ERROR_NO_MEMORY; - } - - chip::System::PacketBufferTLVWriter writer; - // Commands never need chained buffers, since they cannot be chunked. - writer.Init(std::move(buffer), /* useChainedBuffers = */ false); - - ReturnErrorOnFailure(chip::app::DataModel::Encode(writer, chip::TLV::AnonymousTag(), encodableStruct)); - - ReturnErrorOnFailure(writer.Finalize(&buffer)); - - reader.Init(std::move(buffer)); - return reader.Next(chip::TLV::kTLVType_Structure, chip::TLV::AnonymousTag()); -} - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error -{ - chip::System::PacketBufferTLVReader reader; - CHIP_ERROR err = [self _encodeToTLVReader:reader]; - if (err != CHIP_NO_ERROR) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:err]; - } - return nil; - } - - auto decodedObj = MTRDecodeDataValueDictionaryFromCHIPTLV(&reader); - if (decodedObj == nil) { - if (error) { - *error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]; - } - } - return decodedObj; -} -@end - @implementation MTRWebRTCTransportProviderClusterSolicitOfferParams - (instancetype)init { diff --git a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloads_Internal.h b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloads_Internal.h index 70d8a461c6bf9e..89f78e7a2422fc 100644 --- a/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloads_Internal.h +++ b/src/darwin/Framework/CHIP/zap-generated/MTRCommandPayloads_Internal.h @@ -2146,30 +2146,6 @@ NS_ASSUME_NONNULL_BEGIN @end -@interface MTRCameraAVStreamManagementClusterSetViewportParams (InternalMethods) - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error; - -@end - -@interface MTRCameraAVStreamManagementClusterSetImageRotationParams (InternalMethods) - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error; - -@end - -@interface MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams (InternalMethods) - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error; - -@end - -@interface MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams (InternalMethods) - -- (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error; - -@end - @interface MTRWebRTCTransportProviderClusterSolicitOfferParams (InternalMethods) - (NSDictionary * _Nullable)_encodeAsDataValue:(NSError * __autoreleasing *)error; diff --git a/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.cpp b/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.cpp index a1caa8052ae71e..afb3da76dc8bc3 100644 --- a/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.cpp +++ b/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.cpp @@ -37487,147 +37487,6 @@ Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters } // namespace NightVisionIllum -namespace AWBEnabled { - -Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value) -{ - using Traits = NumericAttributeTraits; - Traits::StorageType temp; - uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); - Protocols::InteractionModel::Status status = - emberAfReadAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, readable, sizeof(temp)); - VerifyOrReturnError(Protocols::InteractionModel::Status::Success == status, status); - if (!Traits::CanRepresentValue(/* isNullable = */ false, temp)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - *value = Traits::StorageToWorking(temp); - return status; -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value, MarkAttributeDirty markDirty) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(ConcreteAttributePath(endpoint, Clusters::CameraAvStreamManagement::Id, Id), - EmberAfWriteDataInput(writable, ZCL_BOOLEAN_ATTRIBUTE_TYPE).SetMarkDirty(markDirty)); -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, writable, ZCL_BOOLEAN_ATTRIBUTE_TYPE); -} - -} // namespace AWBEnabled - -namespace AutoShutterSpeedEnabled { - -Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value) -{ - using Traits = NumericAttributeTraits; - Traits::StorageType temp; - uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); - Protocols::InteractionModel::Status status = - emberAfReadAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, readable, sizeof(temp)); - VerifyOrReturnError(Protocols::InteractionModel::Status::Success == status, status); - if (!Traits::CanRepresentValue(/* isNullable = */ false, temp)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - *value = Traits::StorageToWorking(temp); - return status; -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value, MarkAttributeDirty markDirty) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(ConcreteAttributePath(endpoint, Clusters::CameraAvStreamManagement::Id, Id), - EmberAfWriteDataInput(writable, ZCL_BOOLEAN_ATTRIBUTE_TYPE).SetMarkDirty(markDirty)); -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, writable, ZCL_BOOLEAN_ATTRIBUTE_TYPE); -} - -} // namespace AutoShutterSpeedEnabled - -namespace AutoISOEnabled { - -Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value) -{ - using Traits = NumericAttributeTraits; - Traits::StorageType temp; - uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); - Protocols::InteractionModel::Status status = - emberAfReadAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, readable, sizeof(temp)); - VerifyOrReturnError(Protocols::InteractionModel::Status::Success == status, status); - if (!Traits::CanRepresentValue(/* isNullable = */ false, temp)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - *value = Traits::StorageToWorking(temp); - return status; -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value, MarkAttributeDirty markDirty) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(ConcreteAttributePath(endpoint, Clusters::CameraAvStreamManagement::Id, Id), - EmberAfWriteDataInput(writable, ZCL_BOOLEAN_ATTRIBUTE_TYPE).SetMarkDirty(markDirty)); -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, writable, ZCL_BOOLEAN_ATTRIBUTE_TYPE); -} - -} // namespace AutoISOEnabled - namespace SpeakerMuted { Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value) @@ -38381,55 +38240,6 @@ Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters } // namespace StatusLightBrightness -namespace DepthSensorStatus { - -Protocols::InteractionModel::Status Get(EndpointId endpoint, - chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum * value) -{ - using Traits = NumericAttributeTraits; - Traits::StorageType temp; - uint8_t * readable = Traits::ToAttributeStoreRepresentation(temp); - Protocols::InteractionModel::Status status = - emberAfReadAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, readable, sizeof(temp)); - VerifyOrReturnError(Protocols::InteractionModel::Status::Success == status, status); - if (!Traits::CanRepresentValue(/* isNullable = */ false, temp)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - *value = Traits::StorageToWorking(temp); - return status; -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum value, - MarkAttributeDirty markDirty) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(ConcreteAttributePath(endpoint, Clusters::CameraAvStreamManagement::Id, Id), - EmberAfWriteDataInput(writable, ZCL_ENUM8_ATTRIBUTE_TYPE).SetMarkDirty(markDirty)); -} - -Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum value) -{ - using Traits = NumericAttributeTraits; - if (!Traits::CanRepresentValue(/* isNullable = */ false, value)) - { - return Protocols::InteractionModel::Status::ConstraintError; - } - Traits::StorageType storageValue; - Traits::WorkingToStorage(value, storageValue); - uint8_t * writable = Traits::ToAttributeStoreRepresentation(storageValue); - return emberAfWriteAttribute(endpoint, Clusters::CameraAvStreamManagement::Id, Id, writable, ZCL_ENUM8_ATTRIBUTE_TYPE); -} - -} // namespace DepthSensorStatus - namespace FeatureMap { Protocols::InteractionModel::Status Get(EndpointId endpoint, uint32_t * value) diff --git a/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.h b/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.h index bb11fdf51607d1..c79c0657c5b11b 100644 --- a/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.h +++ b/zzz_generated/app-common/app-common/zap-generated/attributes/Accessors.h @@ -5683,24 +5683,6 @@ Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters MarkAttributeDirty markDirty); } // namespace NightVisionIllum -namespace AWBEnabled { -Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value); // boolean -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value); -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value, MarkAttributeDirty markDirty); -} // namespace AWBEnabled - -namespace AutoShutterSpeedEnabled { -Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value); // boolean -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value); -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value, MarkAttributeDirty markDirty); -} // namespace AutoShutterSpeedEnabled - -namespace AutoISOEnabled { -Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value); // boolean -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value); -Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value, MarkAttributeDirty markDirty); -} // namespace AutoISOEnabled - namespace SpeakerMuted { Protocols::InteractionModel::Status Get(EndpointId endpoint, bool * value); // boolean Protocols::InteractionModel::Status Set(EndpointId endpoint, bool value); @@ -5799,14 +5781,6 @@ Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters MarkAttributeDirty markDirty); } // namespace StatusLightBrightness -namespace DepthSensorStatus { -Protocols::InteractionModel::Status -Get(EndpointId endpoint, chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum * value); // TriStateAutoEnum -Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum value); -Protocols::InteractionModel::Status Set(EndpointId endpoint, chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum value, - MarkAttributeDirty markDirty); -} // namespace DepthSensorStatus - namespace FeatureMap { Protocols::InteractionModel::Status Get(EndpointId endpoint, uint32_t * value); // bitmap32 Protocols::InteractionModel::Status Set(EndpointId endpoint, uint32_t value); diff --git a/zzz_generated/app-common/app-common/zap-generated/callback.h b/zzz_generated/app-common/app-common/zap-generated/callback.h index 430eb0bd3821fd..1c8cccc476c6dd 100644 --- a/zzz_generated/app-common/app-common/zap-generated/callback.h +++ b/zzz_generated/app-common/app-common/zap-generated/callback.h @@ -6852,30 +6852,6 @@ bool emberAfCameraAvStreamManagementClusterSetStreamPrioritiesCallback( bool emberAfCameraAvStreamManagementClusterCaptureSnapshotCallback( chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, const chip::app::Clusters::CameraAvStreamManagement::Commands::CaptureSnapshot::DecodableType & commandData); -/** - * @brief Camera AV Stream Management Cluster SetViewport Command callback (from client) - */ -bool emberAfCameraAvStreamManagementClusterSetViewportCallback( - chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::DecodableType & commandData); -/** - * @brief Camera AV Stream Management Cluster SetImageRotation Command callback (from client) - */ -bool emberAfCameraAvStreamManagementClusterSetImageRotationCallback( - chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::DecodableType & commandData); -/** - * @brief Camera AV Stream Management Cluster SetImageFlipHorizontal Command callback (from client) - */ -bool emberAfCameraAvStreamManagementClusterSetImageFlipHorizontalCallback( - chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::DecodableType & commandData); -/** - * @brief Camera AV Stream Management Cluster SetImageFlipVertical Command callback (from client) - */ -bool emberAfCameraAvStreamManagementClusterSetImageFlipVerticalCallback( - chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, - const chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::DecodableType & commandData); /** * @brief WebRTC Transport Provider Cluster SolicitOffer Command callback (from client) */ diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-enums.h b/zzz_generated/app-common/app-common/zap-generated/cluster-enums.h index 586eeb91aff695..adeaf3bf12b4f6 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-enums.h +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-enums.h @@ -5599,12 +5599,12 @@ enum class VideoCodecEnum : uint8_t // Bitmap for Feature enum class Feature : uint32_t { - kPrivacy = 0x1, - kAudio = 0x2, - kSpeaker = 0x4, - kImageControl = 0x8, - kVideo = 0x10, - kSnapshot = 0x20, + kAudio = 0x1, + kVideo = 0x2, + kSnapshot = 0x4, + kPrivacy = 0x8, + kSpeaker = 0x10, + kImageControl = 0x20, kWatermark = 0x40, kOnScreenDisplay = 0x80, kLocalStorage = 0x100, diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp index 9dd42a69d9e430..5a4f042e4c492a 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.cpp @@ -29983,142 +29983,6 @@ CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) } } } // namespace CaptureSnapshotResponse. -namespace SetViewport { -CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const -{ - DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; - encoder.Encode(to_underlying(Fields::kViewport), viewport); - return encoder.Finalize(); -} - -CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) -{ - detail::StructDecodeIterator __iterator(reader); - while (true) - { - auto __element = __iterator.Next(); - if (std::holds_alternative(__element)) - { - return std::get(__element); - } - - CHIP_ERROR err = CHIP_NO_ERROR; - const uint8_t __context_tag = std::get(__element); - - if (__context_tag == to_underlying(Fields::kViewport)) - { - err = DataModel::Decode(reader, viewport); - } - else - { - } - - ReturnErrorOnFailure(err); - } -} -} // namespace SetViewport. -namespace SetImageRotation { -CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const -{ - DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; - encoder.Encode(to_underlying(Fields::kAngle), angle); - return encoder.Finalize(); -} - -CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) -{ - detail::StructDecodeIterator __iterator(reader); - while (true) - { - auto __element = __iterator.Next(); - if (std::holds_alternative(__element)) - { - return std::get(__element); - } - - CHIP_ERROR err = CHIP_NO_ERROR; - const uint8_t __context_tag = std::get(__element); - - if (__context_tag == to_underlying(Fields::kAngle)) - { - err = DataModel::Decode(reader, angle); - } - else - { - } - - ReturnErrorOnFailure(err); - } -} -} // namespace SetImageRotation. -namespace SetImageFlipHorizontal { -CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const -{ - DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; - encoder.Encode(to_underlying(Fields::kEnabled), enabled); - return encoder.Finalize(); -} - -CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) -{ - detail::StructDecodeIterator __iterator(reader); - while (true) - { - auto __element = __iterator.Next(); - if (std::holds_alternative(__element)) - { - return std::get(__element); - } - - CHIP_ERROR err = CHIP_NO_ERROR; - const uint8_t __context_tag = std::get(__element); - - if (__context_tag == to_underlying(Fields::kEnabled)) - { - err = DataModel::Decode(reader, enabled); - } - else - { - } - - ReturnErrorOnFailure(err); - } -} -} // namespace SetImageFlipHorizontal. -namespace SetImageFlipVertical { -CHIP_ERROR Type::Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const -{ - DataModel::WrappedStructEncoder encoder{ aWriter, aTag }; - encoder.Encode(to_underlying(Fields::kEnabled), enabled); - return encoder.Finalize(); -} - -CHIP_ERROR DecodableType::Decode(TLV::TLVReader & reader) -{ - detail::StructDecodeIterator __iterator(reader); - while (true) - { - auto __element = __iterator.Next(); - if (std::holds_alternative(__element)) - { - return std::get(__element); - } - - CHIP_ERROR err = CHIP_NO_ERROR; - const uint8_t __context_tag = std::get(__element); - - if (__context_tag == to_underlying(Fields::kEnabled)) - { - err = DataModel::Decode(reader, enabled); - } - else - { - } - - ReturnErrorOnFailure(err); - } -} -} // namespace SetImageFlipVertical. } // namespace Commands namespace Attributes { @@ -30178,12 +30042,6 @@ CHIP_ERROR TypeInfo::DecodableType::Decode(TLV::TLVReader & reader, const Concre return DataModel::Decode(reader, nightVision); case Attributes::NightVisionIllum::TypeInfo::GetAttributeId(): return DataModel::Decode(reader, nightVisionIllum); - case Attributes::AWBEnabled::TypeInfo::GetAttributeId(): - return DataModel::Decode(reader, AWBEnabled); - case Attributes::AutoShutterSpeedEnabled::TypeInfo::GetAttributeId(): - return DataModel::Decode(reader, autoShutterSpeedEnabled); - case Attributes::AutoISOEnabled::TypeInfo::GetAttributeId(): - return DataModel::Decode(reader, autoISOEnabled); case Attributes::Viewport::TypeInfo::GetAttributeId(): return DataModel::Decode(reader, viewport); case Attributes::SpeakerMuted::TypeInfo::GetAttributeId(): @@ -30218,8 +30076,6 @@ CHIP_ERROR TypeInfo::DecodableType::Decode(TLV::TLVReader & reader, const Concre return DataModel::Decode(reader, statusLightEnabled); case Attributes::StatusLightBrightness::TypeInfo::GetAttributeId(): return DataModel::Decode(reader, statusLightBrightness); - case Attributes::DepthSensorStatus::TypeInfo::GetAttributeId(): - return DataModel::Decode(reader, depthSensorStatus); case Attributes::GeneratedCommandList::TypeInfo::GetAttributeId(): return DataModel::Decode(reader, generatedCommandList); case Attributes::AcceptedCommandList::TypeInfo::GetAttributeId(): diff --git a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h index 62a98d4eabfb3e..d4b3d9c7eebe09 100644 --- a/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h +++ b/zzz_generated/app-common/app-common/zap-generated/cluster-objects.h @@ -41253,26 +41253,6 @@ struct Type; struct DecodableType; } // namespace CaptureSnapshotResponse -namespace SetViewport { -struct Type; -struct DecodableType; -} // namespace SetViewport - -namespace SetImageRotation { -struct Type; -struct DecodableType; -} // namespace SetImageRotation - -namespace SetImageFlipHorizontal { -struct Type; -struct DecodableType; -} // namespace SetImageFlipHorizontal - -namespace SetImageFlipVertical { -struct Type; -struct DecodableType; -} // namespace SetImageFlipVertical - } // namespace Commands namespace Commands { @@ -41773,134 +41753,6 @@ struct DecodableType CHIP_ERROR Decode(TLV::TLVReader & reader); }; }; // namespace CaptureSnapshotResponse -namespace SetViewport { -enum class Fields : uint8_t -{ - kViewport = 0, -}; - -struct Type -{ -public: - // Use GetCommandId instead of commandId directly to avoid naming conflict with CommandIdentification in ExecutionOfACommand - static constexpr CommandId GetCommandId() { return Commands::SetViewport::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - Structs::ViewportStruct::Type viewport; - - CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; - - using ResponseType = DataModel::NullObjectType; - - static constexpr bool MustUseTimedInvoke() { return false; } -}; - -struct DecodableType -{ -public: - static constexpr CommandId GetCommandId() { return Commands::SetViewport::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - Structs::ViewportStruct::DecodableType viewport; - CHIP_ERROR Decode(TLV::TLVReader & reader); -}; -}; // namespace SetViewport -namespace SetImageRotation { -enum class Fields : uint8_t -{ - kAngle = 0, -}; - -struct Type -{ -public: - // Use GetCommandId instead of commandId directly to avoid naming conflict with CommandIdentification in ExecutionOfACommand - static constexpr CommandId GetCommandId() { return Commands::SetImageRotation::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - uint16_t angle = static_cast(0); - - CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; - - using ResponseType = DataModel::NullObjectType; - - static constexpr bool MustUseTimedInvoke() { return false; } -}; - -struct DecodableType -{ -public: - static constexpr CommandId GetCommandId() { return Commands::SetImageRotation::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - uint16_t angle = static_cast(0); - CHIP_ERROR Decode(TLV::TLVReader & reader); -}; -}; // namespace SetImageRotation -namespace SetImageFlipHorizontal { -enum class Fields : uint8_t -{ - kEnabled = 0, -}; - -struct Type -{ -public: - // Use GetCommandId instead of commandId directly to avoid naming conflict with CommandIdentification in ExecutionOfACommand - static constexpr CommandId GetCommandId() { return Commands::SetImageFlipHorizontal::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - bool enabled = static_cast(0); - - CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; - - using ResponseType = DataModel::NullObjectType; - - static constexpr bool MustUseTimedInvoke() { return false; } -}; - -struct DecodableType -{ -public: - static constexpr CommandId GetCommandId() { return Commands::SetImageFlipHorizontal::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - bool enabled = static_cast(0); - CHIP_ERROR Decode(TLV::TLVReader & reader); -}; -}; // namespace SetImageFlipHorizontal -namespace SetImageFlipVertical { -enum class Fields : uint8_t -{ - kEnabled = 0, -}; - -struct Type -{ -public: - // Use GetCommandId instead of commandId directly to avoid naming conflict with CommandIdentification in ExecutionOfACommand - static constexpr CommandId GetCommandId() { return Commands::SetImageFlipVertical::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - bool enabled = static_cast(0); - - CHIP_ERROR Encode(TLV::TLVWriter & aWriter, TLV::Tag aTag) const; - - using ResponseType = DataModel::NullObjectType; - - static constexpr bool MustUseTimedInvoke() { return false; } -}; - -struct DecodableType -{ -public: - static constexpr CommandId GetCommandId() { return Commands::SetImageFlipVertical::Id; } - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - - bool enabled = static_cast(0); - CHIP_ERROR Decode(TLV::TLVReader & reader); -}; -}; // namespace SetImageFlipVertical } // namespace Commands namespace Attributes { @@ -42232,42 +42084,6 @@ struct TypeInfo static constexpr bool MustUseTimedWrite() { return false; } }; } // namespace NightVisionIllum -namespace AWBEnabled { -struct TypeInfo -{ - using Type = bool; - using DecodableType = bool; - using DecodableArgType = bool; - - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - static constexpr AttributeId GetAttributeId() { return Attributes::AWBEnabled::Id; } - static constexpr bool MustUseTimedWrite() { return false; } -}; -} // namespace AWBEnabled -namespace AutoShutterSpeedEnabled { -struct TypeInfo -{ - using Type = bool; - using DecodableType = bool; - using DecodableArgType = bool; - - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - static constexpr AttributeId GetAttributeId() { return Attributes::AutoShutterSpeedEnabled::Id; } - static constexpr bool MustUseTimedWrite() { return false; } -}; -} // namespace AutoShutterSpeedEnabled -namespace AutoISOEnabled { -struct TypeInfo -{ - using Type = bool; - using DecodableType = bool; - using DecodableArgType = bool; - - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - static constexpr AttributeId GetAttributeId() { return Attributes::AutoISOEnabled::Id; } - static constexpr bool MustUseTimedWrite() { return false; } -}; -} // namespace AutoISOEnabled namespace Viewport { struct TypeInfo { @@ -42472,18 +42288,6 @@ struct TypeInfo static constexpr bool MustUseTimedWrite() { return false; } }; } // namespace StatusLightBrightness -namespace DepthSensorStatus { -struct TypeInfo -{ - using Type = chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum; - using DecodableType = chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum; - using DecodableArgType = chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum; - - static constexpr ClusterId GetClusterId() { return Clusters::CameraAvStreamManagement::Id; } - static constexpr AttributeId GetAttributeId() { return Attributes::DepthSensorStatus::Id; } - static constexpr bool MustUseTimedWrite() { return false; } -}; -} // namespace DepthSensorStatus namespace GeneratedCommandList { struct TypeInfo : public Clusters::Globals::Attributes::GeneratedCommandList::TypeInfo { @@ -42553,9 +42357,6 @@ struct TypeInfo static_cast(0); Attributes::NightVisionIllum::TypeInfo::DecodableType nightVisionIllum = static_cast(0); - Attributes::AWBEnabled::TypeInfo::DecodableType AWBEnabled = static_cast(0); - Attributes::AutoShutterSpeedEnabled::TypeInfo::DecodableType autoShutterSpeedEnabled = static_cast(0); - Attributes::AutoISOEnabled::TypeInfo::DecodableType autoISOEnabled = static_cast(0); Attributes::Viewport::TypeInfo::DecodableType viewport; Attributes::SpeakerMuted::TypeInfo::DecodableType speakerMuted = static_cast(0); Attributes::SpeakerVolumeLevel::TypeInfo::DecodableType speakerVolumeLevel = static_cast(0); @@ -42574,8 +42375,6 @@ struct TypeInfo Attributes::StatusLightEnabled::TypeInfo::DecodableType statusLightEnabled = static_cast(0); Attributes::StatusLightBrightness::TypeInfo::DecodableType statusLightBrightness = static_cast(0); - Attributes::DepthSensorStatus::TypeInfo::DecodableType depthSensorStatus = - static_cast(0); Attributes::GeneratedCommandList::TypeInfo::DecodableType generatedCommandList; Attributes::AcceptedCommandList::TypeInfo::DecodableType acceptedCommandList; Attributes::AttributeList::TypeInfo::DecodableType attributeList; diff --git a/zzz_generated/app-common/app-common/zap-generated/ids/Attributes.h b/zzz_generated/app-common/app-common/zap-generated/ids/Attributes.h index e9375f5dad786a..91a52d7c96404f 100644 --- a/zzz_generated/app-common/app-common/zap-generated/ids/Attributes.h +++ b/zzz_generated/app-common/app-common/zap-generated/ids/Attributes.h @@ -6970,90 +6970,74 @@ namespace NightVisionIllum { static constexpr AttributeId Id = 0x00000019; } // namespace NightVisionIllum -namespace AWBEnabled { -static constexpr AttributeId Id = 0x0000001A; -} // namespace AWBEnabled - -namespace AutoShutterSpeedEnabled { -static constexpr AttributeId Id = 0x0000001B; -} // namespace AutoShutterSpeedEnabled - -namespace AutoISOEnabled { -static constexpr AttributeId Id = 0x0000001C; -} // namespace AutoISOEnabled - namespace Viewport { -static constexpr AttributeId Id = 0x0000001D; +static constexpr AttributeId Id = 0x0000001A; } // namespace Viewport namespace SpeakerMuted { -static constexpr AttributeId Id = 0x0000001E; +static constexpr AttributeId Id = 0x0000001B; } // namespace SpeakerMuted namespace SpeakerVolumeLevel { -static constexpr AttributeId Id = 0x0000001F; +static constexpr AttributeId Id = 0x0000001C; } // namespace SpeakerVolumeLevel namespace SpeakerMaxLevel { -static constexpr AttributeId Id = 0x00000020; +static constexpr AttributeId Id = 0x0000001D; } // namespace SpeakerMaxLevel namespace SpeakerMinLevel { -static constexpr AttributeId Id = 0x00000021; +static constexpr AttributeId Id = 0x0000001E; } // namespace SpeakerMinLevel namespace MicrophoneMuted { -static constexpr AttributeId Id = 0x00000022; +static constexpr AttributeId Id = 0x0000001F; } // namespace MicrophoneMuted namespace MicrophoneVolumeLevel { -static constexpr AttributeId Id = 0x00000023; +static constexpr AttributeId Id = 0x00000020; } // namespace MicrophoneVolumeLevel namespace MicrophoneMaxLevel { -static constexpr AttributeId Id = 0x00000024; +static constexpr AttributeId Id = 0x00000021; } // namespace MicrophoneMaxLevel namespace MicrophoneMinLevel { -static constexpr AttributeId Id = 0x00000025; +static constexpr AttributeId Id = 0x00000022; } // namespace MicrophoneMinLevel namespace MicrophoneAGCEnabled { -static constexpr AttributeId Id = 0x00000026; +static constexpr AttributeId Id = 0x00000023; } // namespace MicrophoneAGCEnabled namespace ImageRotation { -static constexpr AttributeId Id = 0x00000027; +static constexpr AttributeId Id = 0x00000024; } // namespace ImageRotation namespace ImageFlipHorizontal { -static constexpr AttributeId Id = 0x00000028; +static constexpr AttributeId Id = 0x00000025; } // namespace ImageFlipHorizontal namespace ImageFlipVertical { -static constexpr AttributeId Id = 0x00000029; +static constexpr AttributeId Id = 0x00000026; } // namespace ImageFlipVertical namespace LocalVideoRecordingEnabled { -static constexpr AttributeId Id = 0x0000002A; +static constexpr AttributeId Id = 0x00000027; } // namespace LocalVideoRecordingEnabled namespace LocalSnapshotRecordingEnabled { -static constexpr AttributeId Id = 0x0000002B; +static constexpr AttributeId Id = 0x00000028; } // namespace LocalSnapshotRecordingEnabled namespace StatusLightEnabled { -static constexpr AttributeId Id = 0x0000002C; +static constexpr AttributeId Id = 0x00000029; } // namespace StatusLightEnabled namespace StatusLightBrightness { -static constexpr AttributeId Id = 0x0000002D; +static constexpr AttributeId Id = 0x0000002A; } // namespace StatusLightBrightness -namespace DepthSensorStatus { -static constexpr AttributeId Id = 0x0000002E; -} // namespace DepthSensorStatus - namespace GeneratedCommandList { static constexpr AttributeId Id = Globals::Attributes::GeneratedCommandList::Id; } // namespace GeneratedCommandList diff --git a/zzz_generated/app-common/app-common/zap-generated/ids/Commands.h b/zzz_generated/app-common/app-common/zap-generated/ids/Commands.h index 5a07d8ac1bd191..d46b8ae0765467 100644 --- a/zzz_generated/app-common/app-common/zap-generated/ids/Commands.h +++ b/zzz_generated/app-common/app-common/zap-generated/ids/Commands.h @@ -1888,22 +1888,6 @@ namespace CaptureSnapshotResponse { static constexpr CommandId Id = 0x0000000C; } // namespace CaptureSnapshotResponse -namespace SetViewport { -static constexpr CommandId Id = 0x0000000D; -} // namespace SetViewport - -namespace SetImageRotation { -static constexpr CommandId Id = 0x0000000E; -} // namespace SetImageRotation - -namespace SetImageFlipHorizontal { -static constexpr CommandId Id = 0x0000000F; -} // namespace SetImageFlipHorizontal - -namespace SetImageFlipVertical { -static constexpr CommandId Id = 0x00000010; -} // namespace SetImageFlipVertical - } // namespace Commands } // namespace CameraAvStreamManagement diff --git a/zzz_generated/chip-tool/zap-generated/cluster/Commands.h b/zzz_generated/chip-tool/zap-generated/cluster/Commands.h index 4ee3c3e1f98afa..ad706028cc4d52 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/Commands.h +++ b/zzz_generated/chip-tool/zap-generated/cluster/Commands.h @@ -13720,10 +13720,6 @@ class ZoneManagementRemoveZone : public ClusterCommand | * SnapshotStreamDeallocate | 0x09 | | * SetStreamPriorities | 0x0A | | * CaptureSnapshot | 0x0B | -| * SetViewport | 0x0D | -| * SetImageRotation | 0x0E | -| * SetImageFlipHorizontal | 0x0F | -| * SetImageFlipVertical | 0x10 | |------------------------------------------------------------------------------| | Attributes: | | | * MaxConcurrentVideoEncoders | 0x0000 | @@ -13752,27 +13748,23 @@ class ZoneManagementRemoveZone : public ClusterCommand | * HardPrivacyModeOn | 0x0017 | | * NightVision | 0x0018 | | * NightVisionIllum | 0x0019 | -| * AWBEnabled | 0x001A | -| * AutoShutterSpeedEnabled | 0x001B | -| * AutoISOEnabled | 0x001C | -| * Viewport | 0x001D | -| * SpeakerMuted | 0x001E | -| * SpeakerVolumeLevel | 0x001F | -| * SpeakerMaxLevel | 0x0020 | -| * SpeakerMinLevel | 0x0021 | -| * MicrophoneMuted | 0x0022 | -| * MicrophoneVolumeLevel | 0x0023 | -| * MicrophoneMaxLevel | 0x0024 | -| * MicrophoneMinLevel | 0x0025 | -| * MicrophoneAGCEnabled | 0x0026 | -| * ImageRotation | 0x0027 | -| * ImageFlipHorizontal | 0x0028 | -| * ImageFlipVertical | 0x0029 | -| * LocalVideoRecordingEnabled | 0x002A | -| * LocalSnapshotRecordingEnabled | 0x002B | -| * StatusLightEnabled | 0x002C | -| * StatusLightBrightness | 0x002D | -| * DepthSensorStatus | 0x002E | +| * Viewport | 0x001A | +| * SpeakerMuted | 0x001B | +| * SpeakerVolumeLevel | 0x001C | +| * SpeakerMaxLevel | 0x001D | +| * SpeakerMinLevel | 0x001E | +| * MicrophoneMuted | 0x001F | +| * MicrophoneVolumeLevel | 0x0020 | +| * MicrophoneMaxLevel | 0x0021 | +| * MicrophoneMinLevel | 0x0022 | +| * MicrophoneAGCEnabled | 0x0023 | +| * ImageRotation | 0x0024 | +| * ImageFlipHorizontal | 0x0025 | +| * ImageFlipVertical | 0x0026 | +| * LocalVideoRecordingEnabled | 0x0027 | +| * LocalSnapshotRecordingEnabled | 0x0028 | +| * StatusLightEnabled | 0x0029 | +| * StatusLightBrightness | 0x002A | | * GeneratedCommandList | 0xFFF8 | | * AcceptedCommandList | 0xFFF9 | | * AttributeList | 0xFFFB | @@ -14168,159 +14160,6 @@ class CameraAvStreamManagementCaptureSnapshot : public ClusterCommand mComplex_RequestedResolution; }; -/* - * Command SetViewport - */ -class CameraAvStreamManagementSetViewport : public ClusterCommand -{ -public: - CameraAvStreamManagementSetViewport(CredentialIssuerCommands * credsIssuerConfig) : - ClusterCommand("set-viewport", credsIssuerConfig), mComplex_Viewport(&mRequest.viewport) - { - AddArgument("Viewport", &mComplex_Viewport); - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(chip::DeviceProxy * device, std::vector endpointIds) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, - commandId, endpointIds.at(0)); - return ClusterCommand::SendCommand(device, endpointIds.at(0), clusterId, commandId, mRequest); - } - - CHIP_ERROR SendGroupCommand(chip::GroupId groupId, chip::FabricIndex fabricIndex) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on Group %u", clusterId, commandId, - groupId); - - return ClusterCommand::SendGroupCommand(groupId, fabricIndex, clusterId, commandId, mRequest); - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Type mRequest; - TypedComplexArgument mComplex_Viewport; -}; - -/* - * Command SetImageRotation - */ -class CameraAvStreamManagementSetImageRotation : public ClusterCommand -{ -public: - CameraAvStreamManagementSetImageRotation(CredentialIssuerCommands * credsIssuerConfig) : - ClusterCommand("set-image-rotation", credsIssuerConfig) - { - AddArgument("Angle", 0, UINT16_MAX, &mRequest.angle); - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(chip::DeviceProxy * device, std::vector endpointIds) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, - commandId, endpointIds.at(0)); - return ClusterCommand::SendCommand(device, endpointIds.at(0), clusterId, commandId, mRequest); - } - - CHIP_ERROR SendGroupCommand(chip::GroupId groupId, chip::FabricIndex fabricIndex) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on Group %u", clusterId, commandId, - groupId); - - return ClusterCommand::SendGroupCommand(groupId, fabricIndex, clusterId, commandId, mRequest); - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Type mRequest; -}; - -/* - * Command SetImageFlipHorizontal - */ -class CameraAvStreamManagementSetImageFlipHorizontal : public ClusterCommand -{ -public: - CameraAvStreamManagementSetImageFlipHorizontal(CredentialIssuerCommands * credsIssuerConfig) : - ClusterCommand("set-image-flip-horizontal", credsIssuerConfig) - { - AddArgument("Enabled", 0, 1, &mRequest.enabled); - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(chip::DeviceProxy * device, std::vector endpointIds) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, - commandId, endpointIds.at(0)); - return ClusterCommand::SendCommand(device, endpointIds.at(0), clusterId, commandId, mRequest); - } - - CHIP_ERROR SendGroupCommand(chip::GroupId groupId, chip::FabricIndex fabricIndex) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on Group %u", clusterId, commandId, - groupId); - - return ClusterCommand::SendGroupCommand(groupId, fabricIndex, clusterId, commandId, mRequest); - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Type mRequest; -}; - -/* - * Command SetImageFlipVertical - */ -class CameraAvStreamManagementSetImageFlipVertical : public ClusterCommand -{ -public: - CameraAvStreamManagementSetImageFlipVertical(CredentialIssuerCommands * credsIssuerConfig) : - ClusterCommand("set-image-flip-vertical", credsIssuerConfig) - { - AddArgument("Enabled", 0, 1, &mRequest.enabled); - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(chip::DeviceProxy * device, std::vector endpointIds) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, - commandId, endpointIds.at(0)); - return ClusterCommand::SendCommand(device, endpointIds.at(0), clusterId, commandId, mRequest); - } - - CHIP_ERROR SendGroupCommand(chip::GroupId groupId, chip::FabricIndex fabricIndex) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on Group %u", clusterId, commandId, - groupId); - - return ClusterCommand::SendGroupCommand(groupId, fabricIndex, clusterId, commandId, mRequest); - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Type mRequest; -}; - /*----------------------------------------------------------------------------*\ | Cluster WebRTCTransportProvider | 0x0553 | |------------------------------------------------------------------------------| @@ -26909,10 +26748,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu make_unique(credsIssuerConfig), // make_unique(credsIssuerConfig), // make_unique(credsIssuerConfig), // - make_unique(credsIssuerConfig), // - make_unique(credsIssuerConfig), // - make_unique(credsIssuerConfig), // - make_unique(credsIssuerConfig), // // // Attributes // @@ -26945,33 +26780,29 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu make_unique(Id, "soft-recording-privacy-mode-enabled", Attributes::SoftRecordingPrivacyModeEnabled::Id, credsIssuerConfig), // make_unique(Id, "soft-livestream-privacy-mode-enabled", Attributes::SoftLivestreamPrivacyModeEnabled::Id, - credsIssuerConfig), // - make_unique(Id, "hard-privacy-mode-on", Attributes::HardPrivacyModeOn::Id, credsIssuerConfig), // - make_unique(Id, "night-vision", Attributes::NightVision::Id, credsIssuerConfig), // - make_unique(Id, "night-vision-illum", Attributes::NightVisionIllum::Id, credsIssuerConfig), // - make_unique(Id, "awbenabled", Attributes::AWBEnabled::Id, credsIssuerConfig), // - make_unique(Id, "auto-shutter-speed-enabled", Attributes::AutoShutterSpeedEnabled::Id, credsIssuerConfig), // - make_unique(Id, "auto-isoenabled", Attributes::AutoISOEnabled::Id, credsIssuerConfig), // - make_unique(Id, "viewport", Attributes::Viewport::Id, credsIssuerConfig), // - make_unique(Id, "speaker-muted", Attributes::SpeakerMuted::Id, credsIssuerConfig), // - make_unique(Id, "speaker-volume-level", Attributes::SpeakerVolumeLevel::Id, credsIssuerConfig), // - make_unique(Id, "speaker-max-level", Attributes::SpeakerMaxLevel::Id, credsIssuerConfig), // - make_unique(Id, "speaker-min-level", Attributes::SpeakerMinLevel::Id, credsIssuerConfig), // - make_unique(Id, "microphone-muted", Attributes::MicrophoneMuted::Id, credsIssuerConfig), // - make_unique(Id, "microphone-volume-level", Attributes::MicrophoneVolumeLevel::Id, credsIssuerConfig), // - make_unique(Id, "microphone-max-level", Attributes::MicrophoneMaxLevel::Id, credsIssuerConfig), // - make_unique(Id, "microphone-min-level", Attributes::MicrophoneMinLevel::Id, credsIssuerConfig), // - make_unique(Id, "microphone-agcenabled", Attributes::MicrophoneAGCEnabled::Id, credsIssuerConfig), // - make_unique(Id, "image-rotation", Attributes::ImageRotation::Id, credsIssuerConfig), // - make_unique(Id, "image-flip-horizontal", Attributes::ImageFlipHorizontal::Id, credsIssuerConfig), // - make_unique(Id, "image-flip-vertical", Attributes::ImageFlipVertical::Id, credsIssuerConfig), // + credsIssuerConfig), // + make_unique(Id, "hard-privacy-mode-on", Attributes::HardPrivacyModeOn::Id, credsIssuerConfig), // + make_unique(Id, "night-vision", Attributes::NightVision::Id, credsIssuerConfig), // + make_unique(Id, "night-vision-illum", Attributes::NightVisionIllum::Id, credsIssuerConfig), // + make_unique(Id, "viewport", Attributes::Viewport::Id, credsIssuerConfig), // + make_unique(Id, "speaker-muted", Attributes::SpeakerMuted::Id, credsIssuerConfig), // + make_unique(Id, "speaker-volume-level", Attributes::SpeakerVolumeLevel::Id, credsIssuerConfig), // + make_unique(Id, "speaker-max-level", Attributes::SpeakerMaxLevel::Id, credsIssuerConfig), // + make_unique(Id, "speaker-min-level", Attributes::SpeakerMinLevel::Id, credsIssuerConfig), // + make_unique(Id, "microphone-muted", Attributes::MicrophoneMuted::Id, credsIssuerConfig), // + make_unique(Id, "microphone-volume-level", Attributes::MicrophoneVolumeLevel::Id, credsIssuerConfig), // + make_unique(Id, "microphone-max-level", Attributes::MicrophoneMaxLevel::Id, credsIssuerConfig), // + make_unique(Id, "microphone-min-level", Attributes::MicrophoneMinLevel::Id, credsIssuerConfig), // + make_unique(Id, "microphone-agcenabled", Attributes::MicrophoneAGCEnabled::Id, credsIssuerConfig), // + make_unique(Id, "image-rotation", Attributes::ImageRotation::Id, credsIssuerConfig), // + make_unique(Id, "image-flip-horizontal", Attributes::ImageFlipHorizontal::Id, credsIssuerConfig), // + make_unique(Id, "image-flip-vertical", Attributes::ImageFlipVertical::Id, credsIssuerConfig), // make_unique(Id, "local-video-recording-enabled", Attributes::LocalVideoRecordingEnabled::Id, credsIssuerConfig), // make_unique(Id, "local-snapshot-recording-enabled", Attributes::LocalSnapshotRecordingEnabled::Id, credsIssuerConfig), // make_unique(Id, "status-light-enabled", Attributes::StatusLightEnabled::Id, credsIssuerConfig), // make_unique(Id, "status-light-brightness", Attributes::StatusLightBrightness::Id, credsIssuerConfig), // - make_unique(Id, "depth-sensor-status", Attributes::DepthSensorStatus::Id, credsIssuerConfig), // make_unique(Id, "generated-command-list", Attributes::GeneratedCommandList::Id, credsIssuerConfig), // make_unique(Id, "accepted-command-list", Attributes::AcceptedCommandList::Id, credsIssuerConfig), // make_unique(Id, "attribute-list", Attributes::AttributeList::Id, credsIssuerConfig), // @@ -27050,38 +26881,32 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu make_unique>( Id, "night-vision-illum", 0, UINT8_MAX, Attributes::NightVisionIllum::Id, WriteCommandType::kWrite, credsIssuerConfig), // - make_unique>(Id, "awbenabled", 0, 1, Attributes::AWBEnabled::Id, WriteCommandType::kWrite, - credsIssuerConfig), // - make_unique>(Id, "auto-shutter-speed-enabled", 0, 1, Attributes::AutoShutterSpeedEnabled::Id, - WriteCommandType::kWrite, credsIssuerConfig), // - make_unique>(Id, "auto-isoenabled", 0, 1, Attributes::AutoISOEnabled::Id, WriteCommandType::kWrite, - credsIssuerConfig), // make_unique>( - Id, "viewport", Attributes::Viewport::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // + Id, "viewport", Attributes::Viewport::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "speaker-muted", 0, 1, Attributes::SpeakerMuted::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "speaker-volume-level", 0, UINT8_MAX, Attributes::SpeakerVolumeLevel::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "speaker-max-level", 0, UINT8_MAX, Attributes::SpeakerMaxLevel::Id, - WriteCommandType::kWrite, credsIssuerConfig), // + WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "speaker-min-level", 0, UINT8_MAX, Attributes::SpeakerMinLevel::Id, - WriteCommandType::kWrite, credsIssuerConfig), // + WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "microphone-muted", 0, 1, Attributes::MicrophoneMuted::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "microphone-volume-level", 0, UINT8_MAX, Attributes::MicrophoneVolumeLevel::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "microphone-max-level", 0, UINT8_MAX, Attributes::MicrophoneMaxLevel::Id, - WriteCommandType::kWrite, credsIssuerConfig), // + WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "microphone-min-level", 0, UINT8_MAX, Attributes::MicrophoneMinLevel::Id, - WriteCommandType::kWrite, credsIssuerConfig), // + WriteCommandType::kForceWrite, credsIssuerConfig), // make_unique>(Id, "microphone-agcenabled", 0, 1, Attributes::MicrophoneAGCEnabled::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "image-rotation", 0, UINT16_MAX, Attributes::ImageRotation::Id, - WriteCommandType::kForceWrite, credsIssuerConfig), // + WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "image-flip-horizontal", 0, 1, Attributes::ImageFlipHorizontal::Id, - WriteCommandType::kForceWrite, credsIssuerConfig), // + WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "image-flip-vertical", 0, 1, Attributes::ImageFlipVertical::Id, - WriteCommandType::kForceWrite, credsIssuerConfig), // + WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "local-video-recording-enabled", 0, 1, Attributes::LocalVideoRecordingEnabled::Id, WriteCommandType::kWrite, credsIssuerConfig), // make_unique>(Id, "local-snapshot-recording-enabled", 0, 1, @@ -27092,9 +26917,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu make_unique>( Id, "status-light-brightness", 0, UINT8_MAX, Attributes::StatusLightBrightness::Id, WriteCommandType::kWrite, credsIssuerConfig), // - make_unique>( - Id, "depth-sensor-status", 0, UINT8_MAX, Attributes::DepthSensorStatus::Id, WriteCommandType::kWrite, - credsIssuerConfig), // make_unique>>( Id, "generated-command-list", Attributes::GeneratedCommandList::Id, WriteCommandType::kForceWrite, credsIssuerConfig), // @@ -27137,14 +26959,10 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu make_unique(Id, "soft-recording-privacy-mode-enabled", Attributes::SoftRecordingPrivacyModeEnabled::Id, credsIssuerConfig), // make_unique(Id, "soft-livestream-privacy-mode-enabled", - Attributes::SoftLivestreamPrivacyModeEnabled::Id, credsIssuerConfig), // - make_unique(Id, "hard-privacy-mode-on", Attributes::HardPrivacyModeOn::Id, credsIssuerConfig), // - make_unique(Id, "night-vision", Attributes::NightVision::Id, credsIssuerConfig), // - make_unique(Id, "night-vision-illum", Attributes::NightVisionIllum::Id, credsIssuerConfig), // - make_unique(Id, "awbenabled", Attributes::AWBEnabled::Id, credsIssuerConfig), // - make_unique(Id, "auto-shutter-speed-enabled", Attributes::AutoShutterSpeedEnabled::Id, - credsIssuerConfig), // - make_unique(Id, "auto-isoenabled", Attributes::AutoISOEnabled::Id, credsIssuerConfig), // + Attributes::SoftLivestreamPrivacyModeEnabled::Id, credsIssuerConfig), // + make_unique(Id, "hard-privacy-mode-on", Attributes::HardPrivacyModeOn::Id, credsIssuerConfig), // + make_unique(Id, "night-vision", Attributes::NightVision::Id, credsIssuerConfig), // + make_unique(Id, "night-vision-illum", Attributes::NightVisionIllum::Id, credsIssuerConfig), // make_unique(Id, "viewport", Attributes::Viewport::Id, credsIssuerConfig), // make_unique(Id, "speaker-muted", Attributes::SpeakerMuted::Id, credsIssuerConfig), // make_unique(Id, "speaker-volume-level", Attributes::SpeakerVolumeLevel::Id, credsIssuerConfig), // @@ -27164,7 +26982,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands, CredentialIssu credsIssuerConfig), // make_unique(Id, "status-light-enabled", Attributes::StatusLightEnabled::Id, credsIssuerConfig), // make_unique(Id, "status-light-brightness", Attributes::StatusLightBrightness::Id, credsIssuerConfig), // - make_unique(Id, "depth-sensor-status", Attributes::DepthSensorStatus::Id, credsIssuerConfig), // make_unique(Id, "generated-command-list", Attributes::GeneratedCommandList::Id, credsIssuerConfig), // make_unique(Id, "accepted-command-list", Attributes::AcceptedCommandList::Id, credsIssuerConfig), // make_unique(Id, "attribute-list", Attributes::AttributeList::Id, credsIssuerConfig), // diff --git a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp index ac4e3adbbbebc3..d3991b2e80d7c0 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/DataModelLogger.cpp @@ -18621,21 +18621,6 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); return DataModelLogger::LogValue("NightVisionIllum", 1, value); } - case CameraAvStreamManagement::Attributes::AWBEnabled::Id: { - bool value; - ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AWBEnabled", 1, value); - } - case CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::Id: { - bool value; - ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AutoShutterSpeedEnabled", 1, value); - } - case CameraAvStreamManagement::Attributes::AutoISOEnabled::Id: { - bool value; - ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("AutoISOEnabled", 1, value); - } case CameraAvStreamManagement::Attributes::Viewport::Id: { chip::app::Clusters::CameraAvStreamManagement::Structs::ViewportStruct::DecodableType value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); @@ -18721,11 +18706,6 @@ CHIP_ERROR DataModelLogger::LogAttribute(const chip::app::ConcreteDataAttributeP ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); return DataModelLogger::LogValue("StatusLightBrightness", 1, value); } - case CameraAvStreamManagement::Attributes::DepthSensorStatus::Id: { - chip::app::Clusters::CameraAvStreamManagement::TriStateAutoEnum value; - ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); - return DataModelLogger::LogValue("DepthSensorStatus", 1, value); - } case CameraAvStreamManagement::Attributes::GeneratedCommandList::Id: { chip::app::DataModel::DecodableList value; ReturnErrorOnFailure(chip::app::DataModel::Decode(*data, value)); diff --git a/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.cpp b/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.cpp index caa60d3532e401..ef977d65e231ed 100644 --- a/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.cpp +++ b/zzz_generated/chip-tool/zap-generated/cluster/logging/EntryToText.cpp @@ -4221,12 +4221,6 @@ char const * AttributeIdToText(chip::ClusterId cluster, chip::AttributeId id) return "NightVision"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::NightVisionIllum::Id: return "NightVisionIllum"; - case chip::app::Clusters::CameraAvStreamManagement::Attributes::AWBEnabled::Id: - return "AWBEnabled"; - case chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::Id: - return "AutoShutterSpeedEnabled"; - case chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoISOEnabled::Id: - return "AutoISOEnabled"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::Viewport::Id: return "Viewport"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerMuted::Id: @@ -4261,8 +4255,6 @@ char const * AttributeIdToText(chip::ClusterId cluster, chip::AttributeId id) return "StatusLightEnabled"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::StatusLightBrightness::Id: return "StatusLightBrightness"; - case chip::app::Clusters::CameraAvStreamManagement::Attributes::DepthSensorStatus::Id: - return "DepthSensorStatus"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::GeneratedCommandList::Id: return "GeneratedCommandList"; case chip::app::Clusters::CameraAvStreamManagement::Attributes::AcceptedCommandList::Id: @@ -5690,14 +5682,6 @@ char const * AcceptedCommandIdToText(chip::ClusterId cluster, chip::CommandId id return "SetStreamPriorities"; case chip::app::Clusters::CameraAvStreamManagement::Commands::CaptureSnapshot::Id: return "CaptureSnapshot"; - case chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Id: - return "SetViewport"; - case chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Id: - return "SetImageRotation"; - case chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Id: - return "SetImageFlipHorizontal"; - case chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Id: - return "SetImageFlipVertical"; default: return "Unknown"; } diff --git a/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h b/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h index bf6bff38ba079b..3fc4c8f49d10a7 100644 --- a/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h +++ b/zzz_generated/darwin-framework-tool/zap-generated/cluster/Commands.h @@ -150638,10 +150638,6 @@ class SubscribeAttributeZoneManagementClusterRevision : public SubscribeAttribut | * SnapshotStreamDeallocate | 0x09 | | * SetStreamPriorities | 0x0A | | * CaptureSnapshot | 0x0B | -| * SetViewport | 0x0D | -| * SetImageRotation | 0x0E | -| * SetImageFlipHorizontal | 0x0F | -| * SetImageFlipVertical | 0x10 | |------------------------------------------------------------------------------| | Attributes: | | | * MaxConcurrentVideoEncoders | 0x0000 | @@ -150670,27 +150666,23 @@ class SubscribeAttributeZoneManagementClusterRevision : public SubscribeAttribut | * HardPrivacyModeOn | 0x0017 | | * NightVision | 0x0018 | | * NightVisionIllum | 0x0019 | -| * AWBEnabled | 0x001A | -| * AutoShutterSpeedEnabled | 0x001B | -| * AutoISOEnabled | 0x001C | -| * Viewport | 0x001D | -| * SpeakerMuted | 0x001E | -| * SpeakerVolumeLevel | 0x001F | -| * SpeakerMaxLevel | 0x0020 | -| * SpeakerMinLevel | 0x0021 | -| * MicrophoneMuted | 0x0022 | -| * MicrophoneVolumeLevel | 0x0023 | -| * MicrophoneMaxLevel | 0x0024 | -| * MicrophoneMinLevel | 0x0025 | -| * MicrophoneAGCEnabled | 0x0026 | -| * ImageRotation | 0x0027 | -| * ImageFlipHorizontal | 0x0028 | -| * ImageFlipVertical | 0x0029 | -| * LocalVideoRecordingEnabled | 0x002A | -| * LocalSnapshotRecordingEnabled | 0x002B | -| * StatusLightEnabled | 0x002C | -| * StatusLightBrightness | 0x002D | -| * DepthSensorStatus | 0x002E | +| * Viewport | 0x001A | +| * SpeakerMuted | 0x001B | +| * SpeakerVolumeLevel | 0x001C | +| * SpeakerMaxLevel | 0x001D | +| * SpeakerMinLevel | 0x001E | +| * MicrophoneMuted | 0x001F | +| * MicrophoneVolumeLevel | 0x0020 | +| * MicrophoneMaxLevel | 0x0021 | +| * MicrophoneMinLevel | 0x0022 | +| * MicrophoneAGCEnabled | 0x0023 | +| * ImageRotation | 0x0024 | +| * ImageFlipHorizontal | 0x0025 | +| * ImageFlipVertical | 0x0026 | +| * LocalVideoRecordingEnabled | 0x0027 | +| * LocalSnapshotRecordingEnabled | 0x0028 | +| * StatusLightEnabled | 0x0029 | +| * StatusLightBrightness | 0x002A | | * GeneratedCommandList | 0xFFF8 | | * AcceptedCommandList | 0xFFF9 | | * AttributeList | 0xFFFB | @@ -151401,224 +151393,6 @@ class CameraAvStreamManagementCaptureSnapshot : public ClusterCommand { TypedComplexArgument mComplex_RequestedResolution; }; -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL -/* - * Command SetViewport - */ -class CameraAvStreamManagementSetViewport : public ClusterCommand { -public: - CameraAvStreamManagementSetViewport() - : ClusterCommand("set-viewport") - , mComplex_Viewport(&mRequest.viewport) - { -#if MTR_ENABLE_PROVISIONAL - AddArgument("Viewport", &mComplex_Viewport); -#endif // MTR_ENABLE_PROVISIONAL - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, commandId, endpointId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRCameraAVStreamManagementClusterSetViewportParams alloc] init]; - params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; -#if MTR_ENABLE_PROVISIONAL - params.viewport = [MTRCameraAVStreamManagementClusterViewportStruct new]; - params.viewport.x1 = [NSNumber numberWithUnsignedShort:mRequest.viewport.x1]; - params.viewport.y1 = [NSNumber numberWithUnsignedShort:mRequest.viewport.y1]; - params.viewport.x2 = [NSNumber numberWithUnsignedShort:mRequest.viewport.x2]; - params.viewport.y2 = [NSNumber numberWithUnsignedShort:mRequest.viewport.y2]; -#endif // MTR_ENABLE_PROVISIONAL - uint16_t repeatCount = mRepeatCount.ValueOr(1); - uint16_t __block responsesNeeded = repeatCount; - while (repeatCount--) { - [cluster setViewportWithParams:params completion: - ^(NSError * _Nullable error) { - responsesNeeded--; - if (error != nil) { - mError = error; - LogNSError("Error", error); - RemoteDataModelLogger::LogCommandErrorAsJSON(@(endpointId), @(clusterId), @(commandId), error); - } - if (responsesNeeded == 0) { - SetCommandExitStatus(mError); - } - }]; - } - return CHIP_NO_ERROR; - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetViewport::Type mRequest; - TypedComplexArgument mComplex_Viewport; -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL -/* - * Command SetImageRotation - */ -class CameraAvStreamManagementSetImageRotation : public ClusterCommand { -public: - CameraAvStreamManagementSetImageRotation() - : ClusterCommand("set-image-rotation") - { -#if MTR_ENABLE_PROVISIONAL - AddArgument("Angle", 0, UINT16_MAX, &mRequest.angle); -#endif // MTR_ENABLE_PROVISIONAL - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, commandId, endpointId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRCameraAVStreamManagementClusterSetImageRotationParams alloc] init]; - params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; -#if MTR_ENABLE_PROVISIONAL - params.angle = [NSNumber numberWithUnsignedShort:mRequest.angle]; -#endif // MTR_ENABLE_PROVISIONAL - uint16_t repeatCount = mRepeatCount.ValueOr(1); - uint16_t __block responsesNeeded = repeatCount; - while (repeatCount--) { - [cluster setImageRotationWithParams:params completion: - ^(NSError * _Nullable error) { - responsesNeeded--; - if (error != nil) { - mError = error; - LogNSError("Error", error); - RemoteDataModelLogger::LogCommandErrorAsJSON(@(endpointId), @(clusterId), @(commandId), error); - } - if (responsesNeeded == 0) { - SetCommandExitStatus(mError); - } - }]; - } - return CHIP_NO_ERROR; - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageRotation::Type mRequest; -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL -/* - * Command SetImageFlipHorizontal - */ -class CameraAvStreamManagementSetImageFlipHorizontal : public ClusterCommand { -public: - CameraAvStreamManagementSetImageFlipHorizontal() - : ClusterCommand("set-image-flip-horizontal") - { -#if MTR_ENABLE_PROVISIONAL - AddArgument("Enabled", 0, 1, &mRequest.enabled); -#endif // MTR_ENABLE_PROVISIONAL - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, commandId, endpointId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRCameraAVStreamManagementClusterSetImageFlipHorizontalParams alloc] init]; - params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; -#if MTR_ENABLE_PROVISIONAL - params.enabled = [NSNumber numberWithBool:mRequest.enabled]; -#endif // MTR_ENABLE_PROVISIONAL - uint16_t repeatCount = mRepeatCount.ValueOr(1); - uint16_t __block responsesNeeded = repeatCount; - while (repeatCount--) { - [cluster setImageFlipHorizontalWithParams:params completion: - ^(NSError * _Nullable error) { - responsesNeeded--; - if (error != nil) { - mError = error; - LogNSError("Error", error); - RemoteDataModelLogger::LogCommandErrorAsJSON(@(endpointId), @(clusterId), @(commandId), error); - } - if (responsesNeeded == 0) { - SetCommandExitStatus(mError); - } - }]; - } - return CHIP_NO_ERROR; - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipHorizontal::Type mRequest; -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL -/* - * Command SetImageFlipVertical - */ -class CameraAvStreamManagementSetImageFlipVertical : public ClusterCommand { -public: - CameraAvStreamManagementSetImageFlipVertical() - : ClusterCommand("set-image-flip-vertical") - { -#if MTR_ENABLE_PROVISIONAL - AddArgument("Enabled", 0, 1, &mRequest.enabled); -#endif // MTR_ENABLE_PROVISIONAL - ClusterCommand::AddArguments(); - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId commandId = chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") command (0x%08" PRIX32 ") on endpoint %u", clusterId, commandId, endpointId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRCameraAVStreamManagementClusterSetImageFlipVerticalParams alloc] init]; - params.timedInvokeTimeoutMs = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; -#if MTR_ENABLE_PROVISIONAL - params.enabled = [NSNumber numberWithBool:mRequest.enabled]; -#endif // MTR_ENABLE_PROVISIONAL - uint16_t repeatCount = mRepeatCount.ValueOr(1); - uint16_t __block responsesNeeded = repeatCount; - while (repeatCount--) { - [cluster setImageFlipVerticalWithParams:params completion: - ^(NSError * _Nullable error) { - responsesNeeded--; - if (error != nil) { - mError = error; - LogNSError("Error", error); - RemoteDataModelLogger::LogCommandErrorAsJSON(@(endpointId), @(clusterId), @(commandId), error); - } - if (responsesNeeded == 0) { - SetCommandExitStatus(mError); - } - }]; - } - return CHIP_NO_ERROR; - } - -private: - chip::app::Clusters::CameraAvStreamManagement::Commands::SetImageFlipVertical::Type mRequest; -}; - #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL @@ -154091,34 +153865,34 @@ class SubscribeAttributeCameraAvStreamManagementNightVisionIllum : public Subscr #if MTR_ENABLE_PROVISIONAL /* - * Attribute AWBEnabled + * Attribute Viewport */ -class ReadCameraAvStreamManagementAWBEnabled : public ReadAttribute { +class ReadCameraAvStreamManagementViewport : public ReadAttribute { public: - ReadCameraAvStreamManagementAWBEnabled() - : ReadAttribute("awbenabled") + ReadCameraAvStreamManagementViewport() + : ReadAttribute("viewport") { } - ~ReadCameraAvStreamManagementAWBEnabled() + ~ReadCameraAvStreamManagementViewport() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AWBEnabled::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::Viewport::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeAWBEnabledWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AWBEnabled response %@", [value description]); + [cluster readAttributeViewportWithCompletion:^(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error) { + NSLog(@"CameraAVStreamManagement.Viewport response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { - LogNSError("CameraAVStreamManagement AWBEnabled read Error", error); + LogNSError("CameraAVStreamManagement Viewport read Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -154127,24 +153901,25 @@ class ReadCameraAvStreamManagementAWBEnabled : public ReadAttribute { } }; -class WriteCameraAvStreamManagementAWBEnabled : public WriteAttribute { +class WriteCameraAvStreamManagementViewport : public WriteAttribute { public: - WriteCameraAvStreamManagementAWBEnabled() - : WriteAttribute("awbenabled") + WriteCameraAvStreamManagementViewport() + : WriteAttribute("viewport") + , mComplex(&mValue) { - AddArgument("attr-name", "awbenabled"); - AddArgument("attr-value", 0, 1, &mValue); + AddArgument("attr-name", "viewport"); + AddArgument("attr-value", &mComplex); WriteAttribute::AddArguments(); } - ~WriteCameraAvStreamManagementAWBEnabled() + ~WriteCameraAvStreamManagementViewport() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AWBEnabled::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::Viewport::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -154152,11 +153927,16 @@ class WriteCameraAvStreamManagementAWBEnabled : public WriteAttribute { __auto_type * params = [[MTRWriteParams alloc] init]; params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithBool:mValue]; - - [cluster writeAttributeAWBEnabledWithValue:value params:params completion:^(NSError * _Nullable error) { + MTRCameraAVStreamManagementClusterViewportStruct * _Nonnull value; + value = [MTRCameraAVStreamManagementClusterViewportStruct new]; + value.x1 = [NSNumber numberWithUnsignedShort:mValue.x1]; + value.y1 = [NSNumber numberWithUnsignedShort:mValue.y1]; + value.x2 = [NSNumber numberWithUnsignedShort:mValue.x2]; + value.y2 = [NSNumber numberWithUnsignedShort:mValue.y2]; + + [cluster writeAttributeViewportWithValue:value params:params completion:^(NSError * _Nullable error) { if (error != nil) { - LogNSError("CameraAVStreamManagement AWBEnabled write Error", error); + LogNSError("CameraAVStreamManagement Viewport write Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -154165,24 +153945,25 @@ class WriteCameraAvStreamManagementAWBEnabled : public WriteAttribute { } private: - bool mValue; + chip::app::Clusters::CameraAvStreamManagement::Structs::ViewportStruct::Type mValue; + TypedComplexArgument mComplex; }; -class SubscribeAttributeCameraAvStreamManagementAWBEnabled : public SubscribeAttribute { +class SubscribeAttributeCameraAvStreamManagementViewport : public SubscribeAttribute { public: - SubscribeAttributeCameraAvStreamManagementAWBEnabled() - : SubscribeAttribute("awbenabled") + SubscribeAttributeCameraAvStreamManagementViewport() + : SubscribeAttribute("viewport") { } - ~SubscribeAttributeCameraAvStreamManagementAWBEnabled() + ~SubscribeAttributeCameraAvStreamManagementViewport() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AWBEnabled::Id; + constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::Viewport::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -154197,10 +153978,10 @@ class SubscribeAttributeCameraAvStreamManagementAWBEnabled : public SubscribeAtt if (mAutoResubscribe.HasValue()) { params.resubscribeAutomatically = mAutoResubscribe.Value(); } - [cluster subscribeAttributeAWBEnabledWithParams:params + [cluster subscribeAttributeViewportWithParams:params subscriptionEstablished:^() { mSubscriptionEstablished = YES; } - reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AWBEnabled response %@", [value description]); + reportHandler:^(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error) { + NSLog(@"CameraAVStreamManagement.Viewport response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { @@ -154217,34 +153998,34 @@ class SubscribeAttributeCameraAvStreamManagementAWBEnabled : public SubscribeAtt #if MTR_ENABLE_PROVISIONAL /* - * Attribute AutoShutterSpeedEnabled + * Attribute SpeakerMuted */ -class ReadCameraAvStreamManagementAutoShutterSpeedEnabled : public ReadAttribute { +class ReadCameraAvStreamManagementSpeakerMuted : public ReadAttribute { public: - ReadCameraAvStreamManagementAutoShutterSpeedEnabled() - : ReadAttribute("auto-shutter-speed-enabled") + ReadCameraAvStreamManagementSpeakerMuted() + : ReadAttribute("speaker-muted") { } - ~ReadCameraAvStreamManagementAutoShutterSpeedEnabled() + ~ReadCameraAvStreamManagementSpeakerMuted() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerMuted::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeAutoShutterSpeedEnabledWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AutoShutterSpeedEnabled response %@", [value description]); + [cluster readAttributeSpeakerMutedWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { + NSLog(@"CameraAVStreamManagement.SpeakerMuted response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { - LogNSError("CameraAVStreamManagement AutoShutterSpeedEnabled read Error", error); + LogNSError("CameraAVStreamManagement SpeakerMuted read Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -154253,24 +154034,24 @@ class ReadCameraAvStreamManagementAutoShutterSpeedEnabled : public ReadAttribute } }; -class WriteCameraAvStreamManagementAutoShutterSpeedEnabled : public WriteAttribute { +class WriteCameraAvStreamManagementSpeakerMuted : public WriteAttribute { public: - WriteCameraAvStreamManagementAutoShutterSpeedEnabled() - : WriteAttribute("auto-shutter-speed-enabled") + WriteCameraAvStreamManagementSpeakerMuted() + : WriteAttribute("speaker-muted") { - AddArgument("attr-name", "auto-shutter-speed-enabled"); + AddArgument("attr-name", "speaker-muted"); AddArgument("attr-value", 0, 1, &mValue); WriteAttribute::AddArguments(); } - ~WriteCameraAvStreamManagementAutoShutterSpeedEnabled() + ~WriteCameraAvStreamManagementSpeakerMuted() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerMuted::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -154280,9 +154061,9 @@ class WriteCameraAvStreamManagementAutoShutterSpeedEnabled : public WriteAttribu params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; NSNumber * _Nonnull value = [NSNumber numberWithBool:mValue]; - [cluster writeAttributeAutoShutterSpeedEnabledWithValue:value params:params completion:^(NSError * _Nullable error) { + [cluster writeAttributeSpeakerMutedWithValue:value params:params completion:^(NSError * _Nullable error) { if (error != nil) { - LogNSError("CameraAVStreamManagement AutoShutterSpeedEnabled write Error", error); + LogNSError("CameraAVStreamManagement SpeakerMuted write Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -154294,21 +154075,21 @@ class WriteCameraAvStreamManagementAutoShutterSpeedEnabled : public WriteAttribu bool mValue; }; -class SubscribeAttributeCameraAvStreamManagementAutoShutterSpeedEnabled : public SubscribeAttribute { +class SubscribeAttributeCameraAvStreamManagementSpeakerMuted : public SubscribeAttribute { public: - SubscribeAttributeCameraAvStreamManagementAutoShutterSpeedEnabled() - : SubscribeAttribute("auto-shutter-speed-enabled") + SubscribeAttributeCameraAvStreamManagementSpeakerMuted() + : SubscribeAttribute("speaker-muted") { } - ~SubscribeAttributeCameraAvStreamManagementAutoShutterSpeedEnabled() + ~SubscribeAttributeCameraAvStreamManagementSpeakerMuted() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoShutterSpeedEnabled::Id; + constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerMuted::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -154323,10 +154104,10 @@ class SubscribeAttributeCameraAvStreamManagementAutoShutterSpeedEnabled : public if (mAutoResubscribe.HasValue()) { params.resubscribeAutomatically = mAutoResubscribe.Value(); } - [cluster subscribeAttributeAutoShutterSpeedEnabledWithParams:params + [cluster subscribeAttributeSpeakerMutedWithParams:params subscriptionEstablished:^() { mSubscriptionEstablished = YES; } reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AutoShutterSpeedEnabled response %@", [value description]); + NSLog(@"CameraAVStreamManagement.SpeakerMuted response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { @@ -154343,34 +154124,34 @@ class SubscribeAttributeCameraAvStreamManagementAutoShutterSpeedEnabled : public #if MTR_ENABLE_PROVISIONAL /* - * Attribute AutoISOEnabled + * Attribute SpeakerVolumeLevel */ -class ReadCameraAvStreamManagementAutoISOEnabled : public ReadAttribute { +class ReadCameraAvStreamManagementSpeakerVolumeLevel : public ReadAttribute { public: - ReadCameraAvStreamManagementAutoISOEnabled() - : ReadAttribute("auto-isoenabled") + ReadCameraAvStreamManagementSpeakerVolumeLevel() + : ReadAttribute("speaker-volume-level") { } - ~ReadCameraAvStreamManagementAutoISOEnabled() + ~ReadCameraAvStreamManagementSpeakerVolumeLevel() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoISOEnabled::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeAutoISOEnabledWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AutoISOEnabled response %@", [value description]); + [cluster readAttributeSpeakerVolumeLevelWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { + NSLog(@"CameraAVStreamManagement.SpeakerVolumeLevel response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { - LogNSError("CameraAVStreamManagement AutoISOEnabled read Error", error); + LogNSError("CameraAVStreamManagement SpeakerVolumeLevel read Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -154379,24 +154160,24 @@ class ReadCameraAvStreamManagementAutoISOEnabled : public ReadAttribute { } }; -class WriteCameraAvStreamManagementAutoISOEnabled : public WriteAttribute { +class WriteCameraAvStreamManagementSpeakerVolumeLevel : public WriteAttribute { public: - WriteCameraAvStreamManagementAutoISOEnabled() - : WriteAttribute("auto-isoenabled") + WriteCameraAvStreamManagementSpeakerVolumeLevel() + : WriteAttribute("speaker-volume-level") { - AddArgument("attr-name", "auto-isoenabled"); - AddArgument("attr-value", 0, 1, &mValue); + AddArgument("attr-name", "speaker-volume-level"); + AddArgument("attr-value", 0, UINT8_MAX, &mValue); WriteAttribute::AddArguments(); } - ~WriteCameraAvStreamManagementAutoISOEnabled() + ~WriteCameraAvStreamManagementSpeakerVolumeLevel() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoISOEnabled::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -154404,11 +154185,11 @@ class WriteCameraAvStreamManagementAutoISOEnabled : public WriteAttribute { __auto_type * params = [[MTRWriteParams alloc] init]; params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithBool:mValue]; + NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - [cluster writeAttributeAutoISOEnabledWithValue:value params:params completion:^(NSError * _Nullable error) { + [cluster writeAttributeSpeakerVolumeLevelWithValue:value params:params completion:^(NSError * _Nullable error) { if (error != nil) { - LogNSError("CameraAVStreamManagement AutoISOEnabled write Error", error); + LogNSError("CameraAVStreamManagement SpeakerVolumeLevel write Error", error); RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); } SetCommandExitStatus(error); @@ -154417,24 +154198,24 @@ class WriteCameraAvStreamManagementAutoISOEnabled : public WriteAttribute { } private: - bool mValue; + uint8_t mValue; }; -class SubscribeAttributeCameraAvStreamManagementAutoISOEnabled : public SubscribeAttribute { +class SubscribeAttributeCameraAvStreamManagementSpeakerVolumeLevel : public SubscribeAttribute { public: - SubscribeAttributeCameraAvStreamManagementAutoISOEnabled() - : SubscribeAttribute("auto-isoenabled") + SubscribeAttributeCameraAvStreamManagementSpeakerVolumeLevel() + : SubscribeAttribute("speaker-volume-level") { } - ~SubscribeAttributeCameraAvStreamManagementAutoISOEnabled() + ~SubscribeAttributeCameraAvStreamManagementSpeakerVolumeLevel() { } CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override { constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::AutoISOEnabled::Id; + constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::Id; ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); @@ -154449,10 +154230,10 @@ class SubscribeAttributeCameraAvStreamManagementAutoISOEnabled : public Subscrib if (mAutoResubscribe.HasValue()) { params.resubscribeAutomatically = mAutoResubscribe.Value(); } - [cluster subscribeAttributeAutoISOEnabledWithParams:params + [cluster subscribeAttributeSpeakerVolumeLevelWithParams:params subscriptionEstablished:^() { mSubscriptionEstablished = YES; } reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.AutoISOEnabled response %@", [value description]); + NSLog(@"CameraAVStreamManagement.SpeakerVolumeLevel response %@", [value description]); if (error == nil) { RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); } else { @@ -154469,346 +154250,9 @@ class SubscribeAttributeCameraAvStreamManagementAutoISOEnabled : public Subscrib #if MTR_ENABLE_PROVISIONAL /* - * Attribute Viewport + * Attribute SpeakerMaxLevel */ -class ReadCameraAvStreamManagementViewport : public ReadAttribute { -public: - ReadCameraAvStreamManagementViewport() - : ReadAttribute("viewport") - { - } - - ~ReadCameraAvStreamManagementViewport() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::Viewport::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeViewportWithCompletion:^(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.Viewport response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - LogNSError("CameraAVStreamManagement Viewport read Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } -}; - -class SubscribeAttributeCameraAvStreamManagementViewport : public SubscribeAttribute { -public: - SubscribeAttributeCameraAvStreamManagementViewport() - : SubscribeAttribute("viewport") - { - } - - ~SubscribeAttributeCameraAvStreamManagementViewport() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::Viewport::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRSubscribeParams alloc] initWithMinInterval:@(mMinInterval) maxInterval:@(mMaxInterval)]; - if (mKeepSubscriptions.HasValue()) { - params.replaceExistingSubscriptions = !mKeepSubscriptions.Value(); - } - if (mFabricFiltered.HasValue()) { - params.filterByFabric = mFabricFiltered.Value(); - } - if (mAutoResubscribe.HasValue()) { - params.resubscribeAutomatically = mAutoResubscribe.Value(); - } - [cluster subscribeAttributeViewportWithParams:params - subscriptionEstablished:^() { mSubscriptionEstablished = YES; } - reportHandler:^(MTRCameraAVStreamManagementClusterViewportStruct * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.Viewport response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - - return CHIP_NO_ERROR; - } -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - -/* - * Attribute SpeakerMuted - */ -class ReadCameraAvStreamManagementSpeakerMuted : public ReadAttribute { -public: - ReadCameraAvStreamManagementSpeakerMuted() - : ReadAttribute("speaker-muted") - { - } - - ~ReadCameraAvStreamManagementSpeakerMuted() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerMuted::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeSpeakerMutedWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.SpeakerMuted response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - LogNSError("CameraAVStreamManagement SpeakerMuted read Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } -}; - -class WriteCameraAvStreamManagementSpeakerMuted : public WriteAttribute { -public: - WriteCameraAvStreamManagementSpeakerMuted() - : WriteAttribute("speaker-muted") - { - AddArgument("attr-name", "speaker-muted"); - AddArgument("attr-value", 0, 1, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementSpeakerMuted() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerMuted::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithBool:mValue]; - - [cluster writeAttributeSpeakerMutedWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement SpeakerMuted write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - bool mValue; -}; - -class SubscribeAttributeCameraAvStreamManagementSpeakerMuted : public SubscribeAttribute { -public: - SubscribeAttributeCameraAvStreamManagementSpeakerMuted() - : SubscribeAttribute("speaker-muted") - { - } - - ~SubscribeAttributeCameraAvStreamManagementSpeakerMuted() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerMuted::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRSubscribeParams alloc] initWithMinInterval:@(mMinInterval) maxInterval:@(mMaxInterval)]; - if (mKeepSubscriptions.HasValue()) { - params.replaceExistingSubscriptions = !mKeepSubscriptions.Value(); - } - if (mFabricFiltered.HasValue()) { - params.filterByFabric = mFabricFiltered.Value(); - } - if (mAutoResubscribe.HasValue()) { - params.resubscribeAutomatically = mAutoResubscribe.Value(); - } - [cluster subscribeAttributeSpeakerMutedWithParams:params - subscriptionEstablished:^() { mSubscriptionEstablished = YES; } - reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.SpeakerMuted response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - - return CHIP_NO_ERROR; - } -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - -/* - * Attribute SpeakerVolumeLevel - */ -class ReadCameraAvStreamManagementSpeakerVolumeLevel : public ReadAttribute { -public: - ReadCameraAvStreamManagementSpeakerVolumeLevel() - : ReadAttribute("speaker-volume-level") - { - } - - ~ReadCameraAvStreamManagementSpeakerVolumeLevel() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeSpeakerVolumeLevelWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.SpeakerVolumeLevel response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - LogNSError("CameraAVStreamManagement SpeakerVolumeLevel read Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } -}; - -class WriteCameraAvStreamManagementSpeakerVolumeLevel : public WriteAttribute { -public: - WriteCameraAvStreamManagementSpeakerVolumeLevel() - : WriteAttribute("speaker-volume-level") - { - AddArgument("attr-name", "speaker-volume-level"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementSpeakerVolumeLevel() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeSpeakerVolumeLevelWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement SpeakerVolumeLevel write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - uint8_t mValue; -}; - -class SubscribeAttributeCameraAvStreamManagementSpeakerVolumeLevel : public SubscribeAttribute { -public: - SubscribeAttributeCameraAvStreamManagementSpeakerVolumeLevel() - : SubscribeAttribute("speaker-volume-level") - { - } - - ~SubscribeAttributeCameraAvStreamManagementSpeakerVolumeLevel() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerVolumeLevel::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRSubscribeParams alloc] initWithMinInterval:@(mMinInterval) maxInterval:@(mMaxInterval)]; - if (mKeepSubscriptions.HasValue()) { - params.replaceExistingSubscriptions = !mKeepSubscriptions.Value(); - } - if (mFabricFiltered.HasValue()) { - params.filterByFabric = mFabricFiltered.Value(); - } - if (mAutoResubscribe.HasValue()) { - params.resubscribeAutomatically = mAutoResubscribe.Value(); - } - [cluster subscribeAttributeSpeakerVolumeLevelWithParams:params - subscriptionEstablished:^() { mSubscriptionEstablished = YES; } - reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.SpeakerVolumeLevel response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - - return CHIP_NO_ERROR; - } -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - -/* - * Attribute SpeakerMaxLevel - */ -class ReadCameraAvStreamManagementSpeakerMaxLevel : public ReadAttribute { +class ReadCameraAvStreamManagementSpeakerMaxLevel : public ReadAttribute { public: ReadCameraAvStreamManagementSpeakerMaxLevel() : ReadAttribute("speaker-max-level") @@ -154842,47 +154286,6 @@ class ReadCameraAvStreamManagementSpeakerMaxLevel : public ReadAttribute { } }; -class WriteCameraAvStreamManagementSpeakerMaxLevel : public WriteAttribute { -public: - WriteCameraAvStreamManagementSpeakerMaxLevel() - : WriteAttribute("speaker-max-level") - { - AddArgument("attr-name", "speaker-max-level"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementSpeakerMaxLevel() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerMaxLevel::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeSpeakerMaxLevelWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement SpeakerMaxLevel write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - uint8_t mValue; -}; - class SubscribeAttributeCameraAvStreamManagementSpeakerMaxLevel : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementSpeakerMaxLevel() @@ -154968,47 +154371,6 @@ class ReadCameraAvStreamManagementSpeakerMinLevel : public ReadAttribute { } }; -class WriteCameraAvStreamManagementSpeakerMinLevel : public WriteAttribute { -public: - WriteCameraAvStreamManagementSpeakerMinLevel() - : WriteAttribute("speaker-min-level") - { - AddArgument("attr-name", "speaker-min-level"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementSpeakerMinLevel() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::SpeakerMinLevel::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeSpeakerMinLevelWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement SpeakerMinLevel write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - uint8_t mValue; -}; - class SubscribeAttributeCameraAvStreamManagementSpeakerMinLevel : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementSpeakerMinLevel() @@ -155342,49 +154704,8 @@ class ReadCameraAvStreamManagementMicrophoneMaxLevel : public ReadAttribute { } SetCommandExitStatus(error); }]; - return CHIP_NO_ERROR; - } -}; - -class WriteCameraAvStreamManagementMicrophoneMaxLevel : public WriteAttribute { -public: - WriteCameraAvStreamManagementMicrophoneMaxLevel() - : WriteAttribute("microphone-max-level") - { - AddArgument("attr-name", "microphone-max-level"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementMicrophoneMaxLevel() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::MicrophoneMaxLevel::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeMicrophoneMaxLevelWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement MicrophoneMaxLevel write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - uint8_t mValue; + return CHIP_NO_ERROR; + } }; class SubscribeAttributeCameraAvStreamManagementMicrophoneMaxLevel : public SubscribeAttribute { @@ -155472,47 +154793,6 @@ class ReadCameraAvStreamManagementMicrophoneMinLevel : public ReadAttribute { } }; -class WriteCameraAvStreamManagementMicrophoneMinLevel : public WriteAttribute { -public: - WriteCameraAvStreamManagementMicrophoneMinLevel() - : WriteAttribute("microphone-min-level") - { - AddArgument("attr-name", "microphone-min-level"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementMicrophoneMinLevel() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::MicrophoneMinLevel::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeMicrophoneMinLevelWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement MicrophoneMinLevel write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - uint8_t mValue; -}; - class SubscribeAttributeCameraAvStreamManagementMicrophoneMinLevel : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementMicrophoneMinLevel() @@ -155724,6 +155004,47 @@ class ReadCameraAvStreamManagementImageRotation : public ReadAttribute { } }; +class WriteCameraAvStreamManagementImageRotation : public WriteAttribute { +public: + WriteCameraAvStreamManagementImageRotation() + : WriteAttribute("image-rotation") + { + AddArgument("attr-name", "image-rotation"); + AddArgument("attr-value", 0, UINT16_MAX, &mValue); + WriteAttribute::AddArguments(); + } + + ~WriteCameraAvStreamManagementImageRotation() + { + } + + CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override + { + constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::ImageRotation::Id; + + ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); + dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; + __auto_type * params = [[MTRWriteParams alloc] init]; + params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; + params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; + NSNumber * _Nonnull value = [NSNumber numberWithUnsignedShort:mValue]; + + [cluster writeAttributeImageRotationWithValue:value params:params completion:^(NSError * _Nullable error) { + if (error != nil) { + LogNSError("CameraAVStreamManagement ImageRotation write Error", error); + RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); + } + SetCommandExitStatus(error); + }]; + return CHIP_NO_ERROR; + } + +private: + uint16_t mValue; +}; + class SubscribeAttributeCameraAvStreamManagementImageRotation : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementImageRotation() @@ -155809,6 +155130,47 @@ class ReadCameraAvStreamManagementImageFlipHorizontal : public ReadAttribute { } }; +class WriteCameraAvStreamManagementImageFlipHorizontal : public WriteAttribute { +public: + WriteCameraAvStreamManagementImageFlipHorizontal() + : WriteAttribute("image-flip-horizontal") + { + AddArgument("attr-name", "image-flip-horizontal"); + AddArgument("attr-value", 0, 1, &mValue); + WriteAttribute::AddArguments(); + } + + ~WriteCameraAvStreamManagementImageFlipHorizontal() + { + } + + CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override + { + constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::ImageFlipHorizontal::Id; + + ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); + dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; + __auto_type * params = [[MTRWriteParams alloc] init]; + params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; + params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; + NSNumber * _Nonnull value = [NSNumber numberWithBool:mValue]; + + [cluster writeAttributeImageFlipHorizontalWithValue:value params:params completion:^(NSError * _Nullable error) { + if (error != nil) { + LogNSError("CameraAVStreamManagement ImageFlipHorizontal write Error", error); + RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); + } + SetCommandExitStatus(error); + }]; + return CHIP_NO_ERROR; + } + +private: + bool mValue; +}; + class SubscribeAttributeCameraAvStreamManagementImageFlipHorizontal : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementImageFlipHorizontal() @@ -155894,6 +155256,47 @@ class ReadCameraAvStreamManagementImageFlipVertical : public ReadAttribute { } }; +class WriteCameraAvStreamManagementImageFlipVertical : public WriteAttribute { +public: + WriteCameraAvStreamManagementImageFlipVertical() + : WriteAttribute("image-flip-vertical") + { + AddArgument("attr-name", "image-flip-vertical"); + AddArgument("attr-value", 0, 1, &mValue); + WriteAttribute::AddArguments(); + } + + ~WriteCameraAvStreamManagementImageFlipVertical() + { + } + + CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override + { + constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; + constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::ImageFlipVertical::Id; + + ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); + dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); + __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; + __auto_type * params = [[MTRWriteParams alloc] init]; + params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; + params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; + NSNumber * _Nonnull value = [NSNumber numberWithBool:mValue]; + + [cluster writeAttributeImageFlipVerticalWithValue:value params:params completion:^(NSError * _Nullable error) { + if (error != nil) { + LogNSError("CameraAVStreamManagement ImageFlipVertical write Error", error); + RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); + } + SetCommandExitStatus(error); + }]; + return CHIP_NO_ERROR; + } + +private: + bool mValue; +}; + class SubscribeAttributeCameraAvStreamManagementImageFlipVertical : public SubscribeAttribute { public: SubscribeAttributeCameraAvStreamManagementImageFlipVertical() @@ -156446,132 +155849,6 @@ class SubscribeAttributeCameraAvStreamManagementStatusLightBrightness : public S #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL -/* - * Attribute DepthSensorStatus - */ -class ReadCameraAvStreamManagementDepthSensorStatus : public ReadAttribute { -public: - ReadCameraAvStreamManagementDepthSensorStatus() - : ReadAttribute("depth-sensor-status") - { - } - - ~ReadCameraAvStreamManagementDepthSensorStatus() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::DepthSensorStatus::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReadAttribute (0x%08" PRIX32 ") on endpoint %u", endpointId, clusterId, attributeId); - - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - [cluster readAttributeDepthSensorStatusWithCompletion:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.DepthSensorStatus response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - LogNSError("CameraAVStreamManagement DepthSensorStatus read Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } -}; - -class WriteCameraAvStreamManagementDepthSensorStatus : public WriteAttribute { -public: - WriteCameraAvStreamManagementDepthSensorStatus() - : WriteAttribute("depth-sensor-status") - { - AddArgument("attr-name", "depth-sensor-status"); - AddArgument("attr-value", 0, UINT8_MAX, &mValue); - WriteAttribute::AddArguments(); - } - - ~WriteCameraAvStreamManagementDepthSensorStatus() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::AttributeId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::DepthSensorStatus::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") WriteAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRWriteParams alloc] init]; - params.timedWriteTimeout = mTimedInteractionTimeoutMs.HasValue() ? [NSNumber numberWithUnsignedShort:mTimedInteractionTimeoutMs.Value()] : nil; - params.dataVersion = mDataVersion.HasValue() ? [NSNumber numberWithUnsignedInt:mDataVersion.Value()] : nil; - NSNumber * _Nonnull value = [NSNumber numberWithUnsignedChar:mValue]; - - [cluster writeAttributeDepthSensorStatusWithValue:value params:params completion:^(NSError * _Nullable error) { - if (error != nil) { - LogNSError("CameraAVStreamManagement DepthSensorStatus write Error", error); - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - return CHIP_NO_ERROR; - } - -private: - uint8_t mValue; -}; - -class SubscribeAttributeCameraAvStreamManagementDepthSensorStatus : public SubscribeAttribute { -public: - SubscribeAttributeCameraAvStreamManagementDepthSensorStatus() - : SubscribeAttribute("depth-sensor-status") - { - } - - ~SubscribeAttributeCameraAvStreamManagementDepthSensorStatus() - { - } - - CHIP_ERROR SendCommand(MTRBaseDevice * device, chip::EndpointId endpointId) override - { - constexpr chip::ClusterId clusterId = chip::app::Clusters::CameraAvStreamManagement::Id; - constexpr chip::CommandId attributeId = chip::app::Clusters::CameraAvStreamManagement::Attributes::DepthSensorStatus::Id; - - ChipLogProgress(chipTool, "Sending cluster (0x%08" PRIX32 ") ReportAttribute (0x%08" PRIX32 ") on endpoint %u", clusterId, attributeId, endpointId); - dispatch_queue_t callbackQueue = dispatch_queue_create("com.chip.command", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL); - __auto_type * cluster = [[MTRBaseClusterCameraAVStreamManagement alloc] initWithDevice:device endpointID:@(endpointId) queue:callbackQueue]; - __auto_type * params = [[MTRSubscribeParams alloc] initWithMinInterval:@(mMinInterval) maxInterval:@(mMaxInterval)]; - if (mKeepSubscriptions.HasValue()) { - params.replaceExistingSubscriptions = !mKeepSubscriptions.Value(); - } - if (mFabricFiltered.HasValue()) { - params.filterByFabric = mFabricFiltered.Value(); - } - if (mAutoResubscribe.HasValue()) { - params.resubscribeAutomatically = mAutoResubscribe.Value(); - } - [cluster subscribeAttributeDepthSensorStatusWithParams:params - subscriptionEstablished:^() { mSubscriptionEstablished = YES; } - reportHandler:^(NSNumber * _Nullable value, NSError * _Nullable error) { - NSLog(@"CameraAVStreamManagement.DepthSensorStatus response %@", [value description]); - if (error == nil) { - RemoteDataModelLogger::LogAttributeAsJSON(@(endpointId), @(clusterId), @(attributeId), value); - } else { - RemoteDataModelLogger::LogAttributeErrorAsJSON(@(endpointId), @(clusterId), @(attributeId), error); - } - SetCommandExitStatus(error); - }]; - - return CHIP_NO_ERROR; - } -}; - -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - /* * Attribute GeneratedCommandList */ @@ -181943,18 +181220,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands) #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // #endif // MTR_ENABLE_PROVISIONAL make_unique(Id), // make_unique(Id), // @@ -182069,23 +181334,9 @@ void registerClusterCameraAvStreamManagement(Commands & commands) make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // - make_unique(), // - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // - make_unique(), // - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // - make_unique(), // - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // + make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL @@ -182100,12 +181351,10 @@ void registerClusterCameraAvStreamManagement(Commands & commands) #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // - make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // - make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL @@ -182120,12 +181369,10 @@ void registerClusterCameraAvStreamManagement(Commands & commands) #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // - make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // - make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL @@ -182135,14 +181382,17 @@ void registerClusterCameraAvStreamManagement(Commands & commands) #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // + make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // + make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // + make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL @@ -182165,11 +181415,6 @@ void registerClusterCameraAvStreamManagement(Commands & commands) make_unique(), // make_unique(), // #endif // MTR_ENABLE_PROVISIONAL -#if MTR_ENABLE_PROVISIONAL - make_unique(), // - make_unique(), // - make_unique(), // -#endif // MTR_ENABLE_PROVISIONAL #if MTR_ENABLE_PROVISIONAL make_unique(), // make_unique(), //